-
1
module ApplicationHelper
-
-
# This is used with flash notices and alertify.
-
1
def flash_class(level)
-
case level
-
when :notice then "alert alert-success"
-
when :success then "alert alert-success"
-
when :error then "alert alert-error"
-
when :alert then "alert alert-error"
-
end
-
end
-
-
1
def link_to_remove_fields(name, f)
-
f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)", class: 'divinline btn btn-primary btn-useryellow add_person_div add_person_fields')
-
end
-
-
1
def link_to_add_fields(name, f, association, path = '')
-
new_object = f.object.class.reflect_on_association(association).klass.new
-
fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
-
render(path + association.to_s.singularize + "_fields", :f => builder)
-
end
-
link_to_function(name, "add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")", class: 'divinline btn btn-primary btn-userblue add_person_div add_person_fields')
-
end
-
end
-
1
module BlogsHelper
-
-
1
def markdown(blogtext)
-
renderOptions = {hard_wrap: true, filter_html: true}
-
markdownOptions = {autolink: true, no_intra_emphasis: true, underline: true, highlight: true, quote: true, space_after_headers: true}
-
markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML.new(renderOptions), markdownOptions)
-
markdown.render(blogtext).html_safe
-
end
-
-
1
def http_checker(url)
-
/^http/.match(url) ? url : 'http://' + url
-
end
-
end
-
1
module FaqCategoriesHelper
-
end
-
1
module ObligationsHelper
-
end
-
1
module ProgramsControllerHelper
-
-
1
def options_for_programs
-
['Toddler (age: 2)', 'Preschool (age: 3)', 'Pre-Kindergarten (age: 4)']
-
end
-
-
1
def select_state
-
["Alabama","Alaska","Arizona","Arkansas","California","Colorado","Connecticut","Delaware","Florida","Georgia","Hawaii","Idaho","Illinois","Indiana","Iowa","Kansas","Kentucky","Louisiana","Maine","Maryland","Massachusetts","Michigan","Minnesota","Mississippi","Missouri","Montana","Nebraska","Nevada","New Hampshire","New Jersey","New Mexico","New York","North Dakota","North Carolina","Ohio","Oklahoma","Oregon","Pennsylvania","Rhode Island","South Carolina","South Dakota","Tennessee","Texas","Utah","Vermont","Virginia","Washington","West Virginia","Wisconsin","Wyoming"]
-
end
-
-
1
def select_relationship
-
['Aunt', 'Brother', 'Daughter', 'Friend', 'Grandparent', 'Husband', 'Significant Other', 'Sister','Son', 'Uncle', 'Wife' ]
-
end
-
-
1
def select_category
-
array = []
-
FaqCategory.all.each do |cat|
-
array.push(cat.name)
-
end
-
array
-
end
-
end
-
1
module RegistrationsHelper
-
end
-
1
module RolesHelper
-
1
def sortable(column, title = nil)
-
title ||= column.titleize
-
css_class = column == sort_column ? 'current ' + sort_direction : nil
-
if column == sort_column && sort_direction == 'asc'
-
css_icon = 'fa fa-chevron-down'
-
elsif column == sort_column && sort_direction == 'desc'
-
css_icon = 'fa fa-chevron-up'
-
else
-
css_icon = nil
-
end
-
direction = column == sort_column && sort_direction == 'asc' ? 'desc' : 'asc'
-
content_tag(:i, link_to(title, {sort: column, direction: direction}, {class: css_class}), class: css_icon)
-
end
-
end
-
1
module UserprofileHelper
-
end
-
1
module VisitorHelper
-
end
-
1
module WelcomeHelper
-
end
-
1
class User < ActiveRecord::Base
-
1
has_many :obligations
-
1
has_many :bugs
-
1
has_many :events
-
1
has_many :blogs
-
1
has_many :parents
-
1
has_many :children, through: :parents
-
1
has_many :adults
-
1
has_many :faq_categories
-
1
accepts_nested_attributes_for :children, reject_if: :all_blank, allow_destroy: true
-
1
accepts_nested_attributes_for :events, allow_destroy: true
-
1
accepts_nested_attributes_for :blogs, allow_destroy: true
-
1
accepts_nested_attributes_for :obligations, allow_destroy: true
-
1
accepts_nested_attributes_for :adults, reject_if: :all_blank, allow_destroy: true
-
-
# attr_accessor :crop_x, :crop_y, :crop_w, :crop_h
-
-
1
validates_presence_of :email
-
1
validates_uniqueness_of :email
-
1
validates_format_of :email, with: /\A([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)\z/i
-
-
1
mount_uploader :image, Uploader
-
1
after_update :crop_image
-
1
before_create :add_guest_role
-
-
# Include default devise modules. Others available are:
-
# :confirmable, :lockable, :timeoutable and :omniauthable
-
1
devise :database_authenticatable, :registerable,
-
:recoverable, :rememberable, :trackable, :validatable
-
-
1
ROLES = ['admin', 'staff', 'member', 'guest']
-
-
1
def roles=(roles)
-
self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.inject(0, :+)
-
if roles.include?('staff') || roles.include?('admin')
-
self.add_staff_to_hstore
-
else
-
self.remove_staff_from_hstore
-
end
-
end
-
-
1
def roles
-
ROLES.reject do |r|
-
((roles_mask.to_i || 0) & 2**ROLES.index(r)).zero?
-
end
-
end
-
-
1
def is?(role)
-
roles.include?(role.to_s)
-
end
-
-
1
def add_guest_role
-
self.roles.push('guest')
-
end
-
-
1
def add_staff_to_hstore
-
work = { a_work_title: '', b_work_phone: '', c_work_street: '', d_work_city: '', e_work_state: '', f_work_zip: '', g_work_occupation: '', h_work_employer: ''}
-
work.each_pair do |key, value|
-
self.work_address[key] = value
-
end
-
self.work_address_will_change!
-
self.save
-
end
-
-
1
def remove_staff_from_hstore
-
work = { a_work_title: '', b_work_phone: '', c_work_street: '', d_work_city: '', e_work_state: '', f_work_zip: ''}
-
work.each_pair do |temp_key, temp_value|
-
self.work_address.delete_if { |key, value| key if key == temp_key.to_s }
-
end
-
self.work_address_will_change!
-
self.save
-
end
-
end
-
-
1
def crop_image
-
if crop_x.present?
-
mini_magick = MiniMagick::Image.open(self.image.path)
-
crop_params = "#{crop_w}x#{crop_h}+#{crop_x}+#{crop_y}"
-
mini_magick.crop(crop_params)
-
mini_magick.write(self.image.large.path)
-
mini_magick.write(self.image.pinhead.path)
-
end
-
end
-
1
class Uploader < CarrierWave::Uploader::Base
-
1
include CarrierWave::MiniMagick
-
-
-
-
-
1
process :resize_to_limit => [600, 600]
-
-
1
version :large do
-
1
process :resize_to_fill => [180, 180]
-
end
-
-
1
storage :file
-
-
1
def store_dir
-
"image_uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
-
end
-
-
1
def extension_white_list
-
%w(jpg jpeg png)
-
end
-
-
1
protected
-
-
1
version :thumb, :if => :is_blog? do
-
1
process :resize_to_fit => [200, 110]
-
end
-
-
1
version :pinhead, :if => :is_user? do
-
1
process :resize_to_fill => [28, 28]
-
end
-
-
1
def is_user? image
-
model.class.name == 'User'
-
end
-
-
1
def is_blog? image
-
model.class.name == 'Blog'
-
end
-
end
-
#--
-
# Copyright (c) 2004-2014 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
1
require 'abstract_controller'
-
1
require 'action_mailer/version'
-
-
# Common Active Support usage in Action Mailer
-
1
require 'active_support/rails'
-
1
require 'active_support/core_ext/class'
-
1
require 'active_support/core_ext/module/attr_internal'
-
1
require 'active_support/core_ext/string/inflections'
-
1
require 'active_support/lazy_load_hooks'
-
-
1
module ActionMailer
-
1
extend ::ActiveSupport::Autoload
-
-
1
eager_autoload do
-
1
autoload :Collector
-
end
-
-
1
autoload :Base
-
1
autoload :DeliveryMethods
-
1
autoload :MailHelper
-
1
autoload :Preview
-
1
autoload :Previews, 'action_mailer/preview'
-
1
autoload :TestCase
-
1
autoload :TestHelper
-
end
-
1
require 'mail'
-
1
require 'action_mailer/collector'
-
1
require 'active_support/core_ext/string/inflections'
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/module/anonymous'
-
-
1
require 'action_mailer/log_subscriber'
-
-
1
module ActionMailer
-
# Action Mailer allows you to send email from your application using a mailer model and views.
-
#
-
# = Mailer Models
-
#
-
# To use Action Mailer, you need to create a mailer model.
-
#
-
# $ rails generate mailer Notifier
-
#
-
# The generated model inherits from <tt>ActionMailer::Base</tt>. A mailer model defines methods
-
# used to generate an email message. In these methods, you can setup variables to be used in
-
# the mailer views, options on the mail itself such as the <tt>:from</tt> address, and attachments.
-
#
-
# class Notifier < ActionMailer::Base
-
# default from: 'no-reply@example.com',
-
# return_path: 'system@example.com'
-
#
-
# def welcome(recipient)
-
# @account = recipient
-
# mail(to: recipient.email_address_with_name,
-
# bcc: ["bcc@example.com", "Order Watcher <watcher@example.com>"])
-
# end
-
# end
-
#
-
# Within the mailer method, you have access to the following methods:
-
#
-
# * <tt>attachments[]=</tt> - Allows you to add attachments to your email in an intuitive
-
# manner; <tt>attachments['filename.png'] = File.read('path/to/filename.png')</tt>
-
#
-
# * <tt>attachments.inline[]=</tt> - Allows you to add an inline attachment to your email
-
# in the same manner as <tt>attachments[]=</tt>
-
#
-
# * <tt>headers[]=</tt> - Allows you to specify any header field in your email such
-
# as <tt>headers['X-No-Spam'] = 'True'</tt>. Note, while most fields like <tt>To:</tt>
-
# <tt>From:</tt> can only appear once in an email header, other fields like <tt>X-Anything</tt>
-
# can appear multiple times. If you want to change a field that can appear multiple times,
-
# you need to set it to nil first so that Mail knows you are replacing it and not adding
-
# another field of the same name.
-
#
-
# * <tt>headers(hash)</tt> - Allows you to specify multiple headers in your email such
-
# as <tt>headers({'X-No-Spam' => 'True', 'In-Reply-To' => '1234@message.id'})</tt>
-
#
-
# * <tt>mail</tt> - Allows you to specify email to be sent.
-
#
-
# The hash passed to the mail method allows you to specify any header that a <tt>Mail::Message</tt>
-
# will accept (any valid email header including optional fields).
-
#
-
# The mail method, if not passed a block, will inspect your views and send all the views with
-
# the same name as the method, so the above action would send the +welcome.text.erb+ view
-
# file as well as the +welcome.text.html.erb+ view file in a +multipart/alternative+ email.
-
#
-
# If you want to explicitly render only certain templates, pass a block:
-
#
-
# mail(to: user.email) do |format|
-
# format.text
-
# format.html
-
# end
-
#
-
# The block syntax is also useful in providing information specific to a part:
-
#
-
# mail(to: user.email) do |format|
-
# format.text(content_transfer_encoding: "base64")
-
# format.html
-
# end
-
#
-
# Or even to render a special view:
-
#
-
# mail(to: user.email) do |format|
-
# format.text
-
# format.html { render "some_other_template" }
-
# end
-
#
-
# = Mailer views
-
#
-
# Like Action Controller, each mailer class has a corresponding view directory in which each
-
# method of the class looks for a template with its name.
-
#
-
# To define a template to be used with a mailing, create an <tt>.erb</tt> file with the same
-
# name as the method in your mailer model. For example, in the mailer defined above, the template at
-
# <tt>app/views/notifier/welcome.text.erb</tt> would be used to generate the email.
-
#
-
# Variables defined in the model are accessible as instance variables in the view.
-
#
-
# Emails by default are sent in plain text, so a sample view for our model example might look like this:
-
#
-
# Hi <%= @account.name %>,
-
# Thanks for joining our service! Please check back often.
-
#
-
# You can even use Action Pack helpers in these views. For example:
-
#
-
# You got a new note!
-
# <%= truncate(@note.body, length: 25) %>
-
#
-
# If you need to access the subject, from or the recipients in the view, you can do that through message object:
-
#
-
# You got a new note from <%= message.from %>!
-
# <%= truncate(@note.body, length: 25) %>
-
#
-
#
-
# = Generating URLs
-
#
-
# URLs can be generated in mailer views using <tt>url_for</tt> or named routes. Unlike controllers from
-
# Action Pack, the mailer instance doesn't have any context about the incoming request, so you'll need
-
# to provide all of the details needed to generate a URL.
-
#
-
# When using <tt>url_for</tt> you'll need to provide the <tt>:host</tt>, <tt>:controller</tt>, and <tt>:action</tt>:
-
#
-
# <%= url_for(host: "example.com", controller: "welcome", action: "greeting") %>
-
#
-
# When using named routes you only need to supply the <tt>:host</tt>:
-
#
-
# <%= users_url(host: "example.com") %>
-
#
-
# You should use the <tt>named_route_url</tt> style (which generates absolute URLs) and avoid using the
-
# <tt>named_route_path</tt> style (which generates relative URLs), since clients reading the mail will
-
# have no concept of a current URL from which to determine a relative path.
-
#
-
# It is also possible to set a default host that will be used in all mailers by setting the <tt>:host</tt>
-
# option as a configuration option in <tt>config/application.rb</tt>:
-
#
-
# config.action_mailer.default_url_options = { host: "example.com" }
-
#
-
# When you decide to set a default <tt>:host</tt> for your mailers, then you need to make sure to use the
-
# <tt>only_path: false</tt> option when using <tt>url_for</tt>. Since the <tt>url_for</tt> view helper
-
# will generate relative URLs by default when a <tt>:host</tt> option isn't explicitly provided, passing
-
# <tt>only_path: false</tt> will ensure that absolute URLs are generated.
-
#
-
# = Sending mail
-
#
-
# Once a mailer action and template are defined, you can deliver your message or create it and save it
-
# for delivery later:
-
#
-
# Notifier.welcome(david).deliver # sends the email
-
# mail = Notifier.welcome(david) # => a Mail::Message object
-
# mail.deliver # sends the email
-
#
-
# You never instantiate your mailer class. Rather, you just call the method you defined on the class itself.
-
#
-
# = Multipart Emails
-
#
-
# Multipart messages can also be used implicitly because Action Mailer will automatically detect and use
-
# multipart templates, where each template is named after the name of the action, followed by the content
-
# type. Each such detected template will be added as a separate part to the message.
-
#
-
# For example, if the following templates exist:
-
# * signup_notification.text.erb
-
# * signup_notification.html.erb
-
# * signup_notification.xml.builder
-
# * signup_notification.yaml.erb
-
#
-
# Each would be rendered and added as a separate part to the message, with the corresponding content
-
# type. The content type for the entire message is automatically set to <tt>multipart/alternative</tt>,
-
# which indicates that the email contains multiple different representations of the same email
-
# body. The same instance variables defined in the action are passed to all email templates.
-
#
-
# Implicit template rendering is not performed if any attachments or parts have been added to the email.
-
# This means that you'll have to manually add each part to the email and set the content type of the email
-
# to <tt>multipart/alternative</tt>.
-
#
-
# = Attachments
-
#
-
# Sending attachment in emails is easy:
-
#
-
# class ApplicationMailer < ActionMailer::Base
-
# def welcome(recipient)
-
# attachments['free_book.pdf'] = File.read('path/to/file.pdf')
-
# mail(to: recipient, subject: "New account information")
-
# end
-
# end
-
#
-
# Which will (if it had both a <tt>welcome.text.erb</tt> and <tt>welcome.html.erb</tt>
-
# template in the view directory), send a complete <tt>multipart/mixed</tt> email with two parts,
-
# the first part being a <tt>multipart/alternative</tt> with the text and HTML email parts inside,
-
# and the second being a <tt>application/pdf</tt> with a Base64 encoded copy of the file.pdf book
-
# with the filename +free_book.pdf+.
-
#
-
# If you need to send attachments with no content, you need to create an empty view for it,
-
# or add an empty body parameter like this:
-
#
-
# class ApplicationMailer < ActionMailer::Base
-
# def welcome(recipient)
-
# attachments['free_book.pdf'] = File.read('path/to/file.pdf')
-
# mail(to: recipient, subject: "New account information", body: "")
-
# end
-
# end
-
#
-
# = Inline Attachments
-
#
-
# You can also specify that a file should be displayed inline with other HTML. This is useful
-
# if you want to display a corporate logo or a photo.
-
#
-
# class ApplicationMailer < ActionMailer::Base
-
# def welcome(recipient)
-
# attachments.inline['photo.png'] = File.read('path/to/photo.png')
-
# mail(to: recipient, subject: "Here is what we look like")
-
# end
-
# end
-
#
-
# And then to reference the image in the view, you create a <tt>welcome.html.erb</tt> file and
-
# make a call to +image_tag+ passing in the attachment you want to display and then call
-
# +url+ on the attachment to get the relative content id path for the image source:
-
#
-
# <h1>Please Don't Cringe</h1>
-
#
-
# <%= image_tag attachments['photo.png'].url -%>
-
#
-
# As we are using Action View's +image_tag+ method, you can pass in any other options you want:
-
#
-
# <h1>Please Don't Cringe</h1>
-
#
-
# <%= image_tag attachments['photo.png'].url, alt: 'Our Photo', class: 'photo' -%>
-
#
-
# = Observing and Intercepting Mails
-
#
-
# Action Mailer provides hooks into the Mail observer and interceptor methods. These allow you to
-
# register classes that are called during the mail delivery life cycle.
-
#
-
# An observer class must implement the <tt>:delivered_email(message)</tt> method which will be
-
# called once for every email sent after the email has been sent.
-
#
-
# An interceptor class must implement the <tt>:delivering_email(message)</tt> method which will be
-
# called before the email is sent, allowing you to make modifications to the email before it hits
-
# the delivery agents. Your class should make any needed modifications directly to the passed
-
# in <tt>Mail::Message</tt> instance.
-
#
-
# = Default Hash
-
#
-
# Action Mailer provides some intelligent defaults for your emails, these are usually specified in a
-
# default method inside the class definition:
-
#
-
# class Notifier < ActionMailer::Base
-
# default sender: 'system@example.com'
-
# end
-
#
-
# You can pass in any header value that a <tt>Mail::Message</tt> accepts. Out of the box,
-
# <tt>ActionMailer::Base</tt> sets the following:
-
#
-
# * <tt>mime_version: "1.0"</tt>
-
# * <tt>charset: "UTF-8",</tt>
-
# * <tt>content_type: "text/plain",</tt>
-
# * <tt>parts_order: [ "text/plain", "text/enriched", "text/html" ]</tt>
-
#
-
# <tt>parts_order</tt> and <tt>charset</tt> are not actually valid <tt>Mail::Message</tt> header fields,
-
# but Action Mailer translates them appropriately and sets the correct values.
-
#
-
# As you can pass in any header, you need to either quote the header as a string, or pass it in as
-
# an underscored symbol, so the following will work:
-
#
-
# class Notifier < ActionMailer::Base
-
# default 'Content-Transfer-Encoding' => '7bit',
-
# content_description: 'This is a description'
-
# end
-
#
-
# Finally, Action Mailer also supports passing <tt>Proc</tt> objects into the default hash, so you
-
# can define methods that evaluate as the message is being generated:
-
#
-
# class Notifier < ActionMailer::Base
-
# default 'X-Special-Header' => Proc.new { my_method }
-
#
-
# private
-
#
-
# def my_method
-
# 'some complex call'
-
# end
-
# end
-
#
-
# Note that the proc is evaluated right at the start of the mail message generation, so if you
-
# set something in the defaults using a proc, and then set the same thing inside of your
-
# mailer method, it will get over written by the mailer method.
-
#
-
# It is also possible to set these default options that will be used in all mailers through
-
# the <tt>default_options=</tt> configuration in <tt>config/application.rb</tt>:
-
#
-
# config.action_mailer.default_options = { from: "no-reply@example.org" }
-
#
-
# = Callbacks
-
#
-
# You can specify callbacks using before_action and after_action for configuring your messages.
-
# This may be useful, for example, when you want to add default inline attachments for all
-
# messages sent out by a certain mailer class:
-
#
-
# class Notifier < ActionMailer::Base
-
# before_action :add_inline_attachment!
-
#
-
# def welcome
-
# mail
-
# end
-
#
-
# private
-
#
-
# def add_inline_attachment!
-
# attachments.inline["footer.jpg"] = File.read('/path/to/filename.jpg')
-
# end
-
# end
-
#
-
# Callbacks in ActionMailer are implemented using AbstractController::Callbacks, so you
-
# can define and configure callbacks in the same manner that you would use callbacks in
-
# classes that inherit from ActionController::Base.
-
#
-
# Note that unless you have a specific reason to do so, you should prefer using before_action
-
# rather than after_action in your ActionMailer classes so that headers are parsed properly.
-
#
-
# = Previewing emails
-
#
-
# You can preview your email templates visually by adding a mailer preview file to the
-
# <tt>ActionMailer::Base.preview_path</tt>. Since most emails do something interesting
-
# with database data, you'll need to write some scenarios to load messages with fake data:
-
#
-
# class NotifierPreview < ActionMailer::Preview
-
# def welcome
-
# Notifier.welcome(User.first)
-
# end
-
# end
-
#
-
# Methods must return a <tt>Mail::Message</tt> object which can be generated by calling the mailer
-
# method without the additional <tt>deliver</tt>. The location of the mailer previews
-
# directory can be configured using the <tt>preview_path</tt> option which has a default
-
# of <tt>test/mailers/previews</tt>:
-
#
-
# config.action_mailer.preview_path = "#{Rails.root}/lib/mailer_previews"
-
#
-
# An overview of all previews is accessible at <tt>http://localhost:3000/rails/mailers</tt>
-
# on a running development server instance.
-
#
-
# Previews can also be intercepted in a similar manner as deliveries can be by registering
-
# a preview interceptor that has a <tt>previewing_email</tt> method:
-
#
-
# class CssInlineStyler
-
# def self.previewing_email(message)
-
# # inline CSS styles
-
# end
-
# end
-
#
-
# config.action_mailer.register_preview_interceptor :css_inline_styler
-
#
-
# Note that interceptors need to be registered both with <tt>register_interceptor</tt>
-
# and <tt>register_preview_interceptor</tt> if they should operate on both sending and
-
# previewing emails.
-
#
-
# = Configuration options
-
#
-
# These options are specified on the class level, like
-
# <tt>ActionMailer::Base.raise_delivery_errors = true</tt>
-
#
-
# * <tt>default_options</tt> - You can pass this in at a class level as well as within the class itself as
-
# per the above section.
-
#
-
# * <tt>logger</tt> - the logger is used for generating information on the mailing run if available.
-
# Can be set to +nil+ for no logging. Compatible with both Ruby's own +Logger+ and Log4r loggers.
-
#
-
# * <tt>smtp_settings</tt> - Allows detailed configuration for <tt>:smtp</tt> delivery method:
-
# * <tt>:address</tt> - Allows you to use a remote mail server. Just change it from its default
-
# "localhost" setting.
-
# * <tt>:port</tt> - On the off chance that your mail server doesn't run on port 25, you can change it.
-
# * <tt>:domain</tt> - If you need to specify a HELO domain, you can do it here.
-
# * <tt>:user_name</tt> - If your mail server requires authentication, set the username in this setting.
-
# * <tt>:password</tt> - If your mail server requires authentication, set the password in this setting.
-
# * <tt>:authentication</tt> - If your mail server requires authentication, you need to specify the
-
# authentication type here.
-
# This is a symbol and one of <tt>:plain</tt> (will send the password in the clear), <tt>:login</tt> (will
-
# send password Base64 encoded) or <tt>:cram_md5</tt> (combines a Challenge/Response mechanism to exchange
-
# information and a cryptographic Message Digest 5 algorithm to hash important information)
-
# * <tt>:enable_starttls_auto</tt> - When set to true, detects if STARTTLS is enabled in your SMTP server
-
# and starts to use it.
-
# * <tt>:openssl_verify_mode</tt> - When using TLS, you can set how OpenSSL checks the certificate. This is
-
# really useful if you need to validate a self-signed and/or a wildcard certificate. You can use the name
-
# of an OpenSSL verify constant (<tt>'none'</tt>, <tt>'peer'</tt>, <tt>'client_once'</tt>,
-
# <tt>'fail_if_no_peer_cert'</tt>) or directly the constant (<tt>OpenSSL::SSL::VERIFY_NONE</tt>,
-
# <tt>OpenSSL::SSL::VERIFY_PEER</tt>, ...).
-
#
-
# * <tt>sendmail_settings</tt> - Allows you to override options for the <tt>:sendmail</tt> delivery method.
-
# * <tt>:location</tt> - The location of the sendmail executable. Defaults to <tt>/usr/sbin/sendmail</tt>.
-
# * <tt>:arguments</tt> - The command line arguments. Defaults to <tt>-i -t</tt> with <tt>-f sender@address</tt>
-
# added automatically before the message is sent.
-
#
-
# * <tt>file_settings</tt> - Allows you to override options for the <tt>:file</tt> delivery method.
-
# * <tt>:location</tt> - The directory into which emails will be written. Defaults to the application
-
# <tt>tmp/mails</tt>.
-
#
-
# * <tt>raise_delivery_errors</tt> - Whether or not errors should be raised if the email fails to be delivered.
-
#
-
# * <tt>delivery_method</tt> - Defines a delivery method. Possible values are <tt>:smtp</tt> (default),
-
# <tt>:sendmail</tt>, <tt>:test</tt>, and <tt>:file</tt>. Or you may provide a custom delivery method
-
# object e.g. +MyOwnDeliveryMethodClass+. See the Mail gem documentation on the interface you need to
-
# implement for a custom delivery agent.
-
#
-
# * <tt>perform_deliveries</tt> - Determines whether emails are actually sent from Action Mailer when you
-
# call <tt>.deliver</tt> on an mail message or on an Action Mailer method. This is on by default but can
-
# be turned off to aid in functional testing.
-
#
-
# * <tt>deliveries</tt> - Keeps an array of all the emails sent out through the Action Mailer with
-
# <tt>delivery_method :test</tt>. Most useful for unit and functional testing.
-
1
class Base < AbstractController::Base
-
1
include DeliveryMethods
-
1
include Previews
-
-
1
abstract!
-
-
1
include AbstractController::Rendering
-
-
1
include AbstractController::Logger
-
1
include AbstractController::Helpers
-
1
include AbstractController::Translation
-
1
include AbstractController::AssetPaths
-
1
include AbstractController::Callbacks
-
-
1
include ActionView::Layouts
-
-
1
PROTECTED_IVARS = AbstractController::Rendering::DEFAULT_PROTECTED_INSTANCE_VARIABLES + [:@_action_has_layout]
-
-
1
def _protected_ivars # :nodoc:
-
PROTECTED_IVARS
-
end
-
-
1
helper ActionMailer::MailHelper
-
-
1
private_class_method :new #:nodoc:
-
-
1
class_attribute :default_params
-
1
self.default_params = {
-
mime_version: "1.0",
-
charset: "UTF-8",
-
content_type: "text/plain",
-
parts_order: [ "text/plain", "text/enriched", "text/html" ]
-
}.freeze
-
-
1
class << self
-
# Register one or more Observers which will be notified when mail is delivered.
-
1
def register_observers(*observers)
-
1
observers.flatten.compact.each { |observer| register_observer(observer) }
-
end
-
-
# Register one or more Interceptors which will be called before mail is sent.
-
1
def register_interceptors(*interceptors)
-
1
interceptors.flatten.compact.each { |interceptor| register_interceptor(interceptor) }
-
end
-
-
# Register an Observer which will be notified when mail is delivered.
-
# Either a class, string or symbol can be passed in as the Observer.
-
# If a string or symbol is passed in it will be camelized and constantized.
-
1
def register_observer(observer)
-
delivery_observer = case observer
-
when String, Symbol
-
observer.to_s.camelize.constantize
-
else
-
observer
-
end
-
-
Mail.register_observer(delivery_observer)
-
end
-
-
# Register an Interceptor which will be called before mail is sent.
-
# Either a class, string or symbol can be passed in as the Interceptor.
-
# If a string or symbol is passed in it will be camelized and constantized.
-
1
def register_interceptor(interceptor)
-
delivery_interceptor = case interceptor
-
when String, Symbol
-
interceptor.to_s.camelize.constantize
-
else
-
interceptor
-
end
-
-
Mail.register_interceptor(delivery_interceptor)
-
end
-
-
# Returns the name of current mailer. This method is also being used as a path for a view lookup.
-
# If this is an anonymous mailer, this method will return +anonymous+ instead.
-
1
def mailer_name
-
@mailer_name ||= anonymous? ? "anonymous" : name.underscore
-
end
-
# Allows to set the name of current mailer.
-
1
attr_writer :mailer_name
-
1
alias :controller_path :mailer_name
-
-
# Sets the defaults through app configuration:
-
#
-
# config.action_mailer.default { from: "no-reply@example.org" }
-
#
-
# Aliased by ::default_options=
-
1
def default(value = nil)
-
self.default_params = default_params.merge(value).freeze if value
-
default_params
-
end
-
# Allows to set defaults through app configuration:
-
#
-
# config.action_mailer.default_options = { from: "no-reply@example.org" }
-
1
alias :default_options= :default
-
-
# Receives a raw email, parses it into an email object, decodes it,
-
# instantiates a new mailer, and passes the email object to the mailer
-
# object's +receive+ method.
-
#
-
# If you want your mailer to be able to process incoming messages, you'll
-
# need to implement a +receive+ method that accepts the raw email string
-
# as a parameter:
-
#
-
# class MyMailer < ActionMailer::Base
-
# def receive(mail)
-
# # ...
-
# end
-
# end
-
1
def receive(raw_mail)
-
ActiveSupport::Notifications.instrument("receive.action_mailer") do |payload|
-
mail = Mail.new(raw_mail)
-
set_payload_for_mail(payload, mail)
-
new.receive(mail)
-
end
-
end
-
-
# Wraps an email delivery inside of <tt>ActiveSupport::Notifications</tt> instrumentation.
-
#
-
# This method is actually called by the <tt>Mail::Message</tt> object itself
-
# through a callback when you call <tt>:deliver</tt> on the <tt>Mail::Message</tt>,
-
# calling +deliver_mail+ directly and passing a <tt>Mail::Message</tt> will do
-
# nothing except tell the logger you sent the email.
-
1
def deliver_mail(mail) #:nodoc:
-
ActiveSupport::Notifications.instrument("deliver.action_mailer") do |payload|
-
set_payload_for_mail(payload, mail)
-
yield # Let Mail do the delivery actions
-
end
-
end
-
-
1
def respond_to?(method, include_private = false) #:nodoc:
-
3
super || action_methods.include?(method.to_s)
-
end
-
-
1
protected
-
-
1
def set_payload_for_mail(payload, mail) #:nodoc:
-
payload[:mailer] = name
-
payload[:message_id] = mail.message_id
-
payload[:subject] = mail.subject
-
payload[:to] = mail.to
-
payload[:from] = mail.from
-
payload[:bcc] = mail.bcc if mail.bcc.present?
-
payload[:cc] = mail.cc if mail.cc.present?
-
payload[:date] = mail.date
-
payload[:mail] = mail.encoded
-
end
-
-
1
def method_missing(method_name, *args) # :nodoc:
-
if respond_to?(method_name)
-
new(method_name, *args).message
-
else
-
super
-
end
-
end
-
end
-
-
1
attr_internal :message
-
-
# Instantiate a new mailer object. If +method_name+ is not +nil+, the mailer
-
# will be initialized according to the named method. If not, the mailer will
-
# remain uninitialized (useful when you only need to invoke the "receive"
-
# method, for instance).
-
1
def initialize(method_name=nil, *args)
-
super()
-
@_mail_was_called = false
-
@_message = Mail.new
-
process(method_name, *args) if method_name
-
end
-
-
1
def process(method_name, *args) #:nodoc:
-
payload = {
-
mailer: self.class.name,
-
action: method_name
-
}
-
-
ActiveSupport::Notifications.instrument("process.action_mailer", payload) do
-
lookup_context.skip_default_locale!
-
-
super
-
@_message = NullMail.new unless @_mail_was_called
-
end
-
end
-
-
1
class NullMail #:nodoc:
-
1
def body; '' end
-
-
1
def method_missing(*args)
-
nil
-
end
-
end
-
-
# Returns the name of the mailer object.
-
1
def mailer_name
-
self.class.mailer_name
-
end
-
-
# Allows you to pass random and unusual headers to the new <tt>Mail::Message</tt>
-
# object which will add them to itself.
-
#
-
# headers['X-Special-Domain-Specific-Header'] = "SecretValue"
-
#
-
# You can also pass a hash into headers of header field names and values,
-
# which will then be set on the <tt>Mail::Message</tt> object:
-
#
-
# headers 'X-Special-Domain-Specific-Header' => "SecretValue",
-
# 'In-Reply-To' => incoming.message_id
-
#
-
# The resulting <tt>Mail::Message</tt> will have the following in its header:
-
#
-
# X-Special-Domain-Specific-Header: SecretValue
-
1
def headers(args = nil)
-
if args
-
@_message.headers(args)
-
else
-
@_message
-
end
-
end
-
-
# Allows you to add attachments to an email, like so:
-
#
-
# mail.attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
-
#
-
# If you do this, then Mail will take the file name and work out the mime type
-
# set the Content-Type, Content-Disposition, Content-Transfer-Encoding and
-
# base64 encode the contents of the attachment all for you.
-
#
-
# You can also specify overrides if you want by passing a hash instead of a string:
-
#
-
# mail.attachments['filename.jpg'] = {mime_type: 'application/x-gzip',
-
# content: File.read('/path/to/filename.jpg')}
-
#
-
# If you want to use a different encoding than Base64, you can pass an encoding in,
-
# but then it is up to you to pass in the content pre-encoded, and don't expect
-
# Mail to know how to decode this data:
-
#
-
# file_content = SpecialEncode(File.read('/path/to/filename.jpg'))
-
# mail.attachments['filename.jpg'] = {mime_type: 'application/x-gzip',
-
# encoding: 'SpecialEncoding',
-
# content: file_content }
-
#
-
# You can also search for specific attachments:
-
#
-
# # By Filename
-
# mail.attachments['filename.jpg'] # => Mail::Part object or nil
-
#
-
# # or by index
-
# mail.attachments[0] # => Mail::Part (first attachment)
-
#
-
1
def attachments
-
@_message.attachments
-
end
-
-
# The main method that creates the message and renders the email templates. There are
-
# two ways to call this method, with a block, or without a block.
-
#
-
# Both methods accept a headers hash. This hash allows you to specify the most used headers
-
# in an email message, these are:
-
#
-
# * +:subject+ - The subject of the message, if this is omitted, Action Mailer will
-
# ask the Rails I18n class for a translated +:subject+ in the scope of
-
# <tt>[mailer_scope, action_name]</tt> or if this is missing, will translate the
-
# humanized version of the +action_name+
-
# * +:to+ - Who the message is destined for, can be a string of addresses, or an array
-
# of addresses.
-
# * +:from+ - Who the message is from
-
# * +:cc+ - Who you would like to Carbon-Copy on this email, can be a string of addresses,
-
# or an array of addresses.
-
# * +:bcc+ - Who you would like to Blind-Carbon-Copy on this email, can be a string of
-
# addresses, or an array of addresses.
-
# * +:reply_to+ - Who to set the Reply-To header of the email to.
-
# * +:date+ - The date to say the email was sent on.
-
#
-
# You can set default values for any of the above headers (except +:date+)
-
# by using the ::default class method:
-
#
-
# class Notifier < ActionMailer::Base
-
# default from: 'no-reply@test.lindsaar.net',
-
# bcc: 'email_logger@test.lindsaar.net',
-
# reply_to: 'bounces@test.lindsaar.net'
-
# end
-
#
-
# If you need other headers not listed above, you can either pass them in
-
# as part of the headers hash or use the <tt>headers['name'] = value</tt>
-
# method.
-
#
-
# When a +:return_path+ is specified as header, that value will be used as
-
# the 'envelope from' address for the Mail message. Setting this is useful
-
# when you want delivery notifications sent to a different address than the
-
# one in +:from+. Mail will actually use the +:return_path+ in preference
-
# to the +:sender+ in preference to the +:from+ field for the 'envelope
-
# from' value.
-
#
-
# If you do not pass a block to the +mail+ method, it will find all
-
# templates in the view paths using by default the mailer name and the
-
# method name that it is being called from, it will then create parts for
-
# each of these templates intelligently, making educated guesses on correct
-
# content type and sequence, and return a fully prepared <tt>Mail::Message</tt>
-
# ready to call <tt>:deliver</tt> on to send.
-
#
-
# For example:
-
#
-
# class Notifier < ActionMailer::Base
-
# default from: 'no-reply@test.lindsaar.net'
-
#
-
# def welcome
-
# mail(to: 'mikel@test.lindsaar.net')
-
# end
-
# end
-
#
-
# Will look for all templates at "app/views/notifier" with name "welcome".
-
# If no welcome template exists, it will raise an ActionView::MissingTemplate error.
-
#
-
# However, those can be customized:
-
#
-
# mail(template_path: 'notifications', template_name: 'another')
-
#
-
# And now it will look for all templates at "app/views/notifications" with name "another".
-
#
-
# If you do pass a block, you can render specific templates of your choice:
-
#
-
# mail(to: 'mikel@test.lindsaar.net') do |format|
-
# format.text
-
# format.html
-
# end
-
#
-
# You can even render plain text directly without using a template:
-
#
-
# mail(to: 'mikel@test.lindsaar.net') do |format|
-
# format.text { render plain: "Hello Mikel!" }
-
# format.html { render html: "<h1>Hello Mikel!</h1>".html_safe }
-
# end
-
#
-
# Which will render a +multipart/alternative+ email with +text/plain+ and
-
# +text/html+ parts.
-
#
-
# The block syntax also allows you to customize the part headers if desired:
-
#
-
# mail(to: 'mikel@test.lindsaar.net') do |format|
-
# format.text(content_transfer_encoding: "base64")
-
# format.html
-
# end
-
#
-
1
def mail(headers = {}, &block)
-
return @_message if @_mail_was_called && headers.blank? && !block
-
-
@_mail_was_called = true
-
m = @_message
-
-
# At the beginning, do not consider class default for content_type
-
content_type = headers[:content_type]
-
-
# Call all the procs (if any)
-
default_values = {}
-
self.class.default.each do |k,v|
-
default_values[k] = v.is_a?(Proc) ? instance_eval(&v) : v
-
end
-
-
# Handle defaults
-
headers = headers.reverse_merge(default_values)
-
headers[:subject] ||= default_i18n_subject
-
-
# Apply charset at the beginning so all fields are properly quoted
-
m.charset = charset = headers[:charset]
-
-
# Set configure delivery behavior
-
wrap_delivery_behavior!(headers.delete(:delivery_method), headers.delete(:delivery_method_options))
-
-
# Assign all headers except parts_order, content_type and body
-
assignable = headers.except(:parts_order, :content_type, :body, :template_name, :template_path)
-
assignable.each { |k, v| m[k] = v }
-
-
# Render the templates and blocks
-
responses = collect_responses(headers, &block)
-
create_parts_from_responses(m, responses)
-
-
# Setup content type, reapply charset and handle parts order
-
m.content_type = set_content_type(m, content_type, headers[:content_type])
-
m.charset = charset
-
-
if m.multipart?
-
m.body.set_sort_order(headers[:parts_order])
-
m.body.sort_parts!
-
end
-
-
m
-
end
-
-
1
protected
-
-
# Used by #mail to set the content type of the message.
-
#
-
# It will use the given +user_content_type+, or multipart if the mail
-
# message has any attachments. If the attachments are inline, the content
-
# type will be "multipart/related", otherwise "multipart/mixed".
-
#
-
# If there is no content type passed in via headers, and there are no
-
# attachments, or the message is multipart, then the default content type is
-
# used.
-
1
def set_content_type(m, user_content_type, class_default)
-
params = m.content_type_parameters || {}
-
case
-
when user_content_type.present?
-
user_content_type
-
when m.has_attachments?
-
if m.attachments.detect { |a| a.inline? }
-
["multipart", "related", params]
-
else
-
["multipart", "mixed", params]
-
end
-
when m.multipart?
-
["multipart", "alternative", params]
-
else
-
m.content_type || class_default
-
end
-
end
-
-
# Translates the +subject+ using Rails I18n class under <tt>[mailer_scope, action_name]</tt> scope.
-
# If it does not find a translation for the +subject+ under the specified scope it will default to a
-
# humanized version of the <tt>action_name</tt>.
-
# If the subject has interpolations, you can pass them through the +interpolations+ parameter.
-
1
def default_i18n_subject(interpolations = {})
-
mailer_scope = self.class.mailer_name.tr('/', '.')
-
I18n.t(:subject, interpolations.merge(scope: [mailer_scope, action_name], default: action_name.humanize))
-
end
-
-
1
def collect_responses(headers) #:nodoc:
-
responses = []
-
-
if block_given?
-
collector = ActionMailer::Collector.new(lookup_context) { render(action_name) }
-
yield(collector)
-
responses = collector.responses
-
elsif headers[:body]
-
responses << {
-
body: headers.delete(:body),
-
content_type: self.class.default[:content_type] || "text/plain"
-
}
-
else
-
templates_path = headers.delete(:template_path) || self.class.mailer_name
-
templates_name = headers.delete(:template_name) || action_name
-
-
each_template(Array(templates_path), templates_name) do |template|
-
self.formats = template.formats
-
-
responses << {
-
body: render(template: template),
-
content_type: template.type.to_s
-
}
-
end
-
end
-
-
responses
-
end
-
-
1
def each_template(paths, name, &block) #:nodoc:
-
templates = lookup_context.find_all(name, paths)
-
if templates.empty?
-
raise ActionView::MissingTemplate.new(paths, name, paths, false, 'mailer')
-
else
-
templates.uniq { |t| t.formats }.each(&block)
-
end
-
end
-
-
1
def create_parts_from_responses(m, responses) #:nodoc:
-
if responses.size == 1 && !m.has_attachments?
-
responses[0].each { |k,v| m[k] = v }
-
elsif responses.size > 1 && m.has_attachments?
-
container = Mail::Part.new
-
container.content_type = "multipart/alternative"
-
responses.each { |r| insert_part(container, r, m.charset) }
-
m.add_part(container)
-
else
-
responses.each { |r| insert_part(m, r, m.charset) }
-
end
-
end
-
-
1
def insert_part(container, response, charset) #:nodoc:
-
response[:charset] ||= charset
-
part = Mail::Part.new(response)
-
container.add_part(part)
-
end
-
-
1
ActiveSupport.run_load_hooks(:action_mailer, self)
-
end
-
end
-
1
require 'abstract_controller/collector'
-
1
require 'active_support/core_ext/hash/reverse_merge'
-
1
require 'active_support/core_ext/array/extract_options'
-
-
1
module ActionMailer
-
1
class Collector
-
1
include AbstractController::Collector
-
1
attr_reader :responses
-
-
1
def initialize(context, &block)
-
@context = context
-
@responses = []
-
@default_render = block
-
end
-
-
1
def any(*args, &block)
-
options = args.extract_options!
-
raise ArgumentError, "You have to supply at least one format" if args.empty?
-
args.each { |type| send(type, options.dup, &block) }
-
end
-
1
alias :all :any
-
-
1
def custom(mime, options = {})
-
options.reverse_merge!(content_type: mime.to_s)
-
@context.formats = [mime.to_sym]
-
options[:body] = block_given? ? yield : @default_render.call
-
@responses << options
-
end
-
end
-
end
-
1
require 'tmpdir'
-
-
1
module ActionMailer
-
# This module handles everything related to mail delivery, from registering
-
# new delivery methods to configuring the mail object to be sent.
-
1
module DeliveryMethods
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
class_attribute :delivery_methods, :delivery_method
-
-
# Do not make this inheritable, because we always want it to propagate
-
1
cattr_accessor :raise_delivery_errors
-
1
self.raise_delivery_errors = true
-
-
1
cattr_accessor :perform_deliveries
-
1
self.perform_deliveries = true
-
-
1
self.delivery_methods = {}.freeze
-
1
self.delivery_method = :smtp
-
-
1
add_delivery_method :smtp, Mail::SMTP,
-
address: "localhost",
-
port: 25,
-
domain: 'localhost.localdomain',
-
user_name: nil,
-
password: nil,
-
authentication: nil,
-
enable_starttls_auto: true
-
-
1
add_delivery_method :file, Mail::FileDelivery,
-
location: defined?(Rails.root) ? "#{Rails.root}/tmp/mails" : "#{Dir.tmpdir}/mails"
-
-
1
add_delivery_method :sendmail, Mail::Sendmail,
-
location: '/usr/sbin/sendmail',
-
arguments: '-i -t'
-
-
1
add_delivery_method :test, Mail::TestMailer
-
end
-
-
# Helpers for creating and wrapping delivery behavior, used by DeliveryMethods.
-
1
module ClassMethods
-
# Provides a list of emails that have been delivered by Mail::TestMailer
-
1
delegate :deliveries, :deliveries=, to: Mail::TestMailer
-
-
# Adds a new delivery method through the given class using the given
-
# symbol as alias and the default options supplied.
-
#
-
# add_delivery_method :sendmail, Mail::Sendmail,
-
# location: '/usr/sbin/sendmail',
-
# arguments: '-i -t'
-
1
def add_delivery_method(symbol, klass, default_options={})
-
4
class_attribute(:"#{symbol}_settings") unless respond_to?(:"#{symbol}_settings")
-
4
send(:"#{symbol}_settings=", default_options)
-
4
self.delivery_methods = delivery_methods.merge(symbol.to_sym => klass).freeze
-
end
-
-
1
def wrap_delivery_behavior(mail, method=nil, options=nil) # :nodoc:
-
method ||= self.delivery_method
-
mail.delivery_handler = self
-
-
case method
-
when NilClass
-
raise "Delivery method cannot be nil"
-
when Symbol
-
if klass = delivery_methods[method]
-
mail.delivery_method(klass, (send(:"#{method}_settings") || {}).merge(options || {}))
-
else
-
raise "Invalid delivery method #{method.inspect}"
-
end
-
else
-
mail.delivery_method(method)
-
end
-
-
mail.perform_deliveries = perform_deliveries
-
mail.raise_delivery_errors = raise_delivery_errors
-
end
-
end
-
-
1
def wrap_delivery_behavior!(*args) # :nodoc:
-
self.class.wrap_delivery_behavior(message, *args)
-
end
-
end
-
end
-
1
module ActionMailer
-
# Returns the version of the currently loaded ActionMailer as a <tt>Gem::Version</tt>
-
1
def self.gem_version
-
Gem::Version.new VERSION::STRING
-
end
-
-
1
module VERSION
-
1
MAJOR = 4
-
1
MINOR = 1
-
1
TINY = 0
-
1
PRE = nil
-
-
1
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
-
end
-
end
-
1
require 'active_support/log_subscriber'
-
-
1
module ActionMailer
-
# Implements the ActiveSupport::LogSubscriber for logging notifications when
-
# email is delivered and received.
-
1
class LogSubscriber < ActiveSupport::LogSubscriber
-
# An email was delivered.
-
1
def deliver(event)
-
return unless logger.info?
-
recipients = Array(event.payload[:to]).join(', ')
-
info("\nSent mail to #{recipients} (#{event.duration.round(1)}ms)")
-
debug(event.payload[:mail])
-
end
-
-
# An email was received.
-
1
def receive(event)
-
return unless logger.info?
-
info("\nReceived mail (#{event.duration.round(1)}ms)")
-
debug(event.payload[:mail])
-
end
-
-
# An email was generated.
-
1
def process(event)
-
mailer = event.payload[:mailer]
-
action = event.payload[:action]
-
debug("\n#{mailer}##{action}: processed outbound mail in #{event.duration.round(1)}ms")
-
end
-
-
# Use the logger configured for ActionMailer::Base
-
1
def logger
-
ActionMailer::Base.logger
-
end
-
end
-
end
-
-
1
ActionMailer::LogSubscriber.attach_to :action_mailer
-
1
module ActionMailer
-
# Provides helper methods for ActionMailer::Base that can be used for easily
-
# formatting messages, accessing mailer or message instances, and the
-
# attachments list.
-
1
module MailHelper
-
# Take the text and format it, indented two spaces for each line, and
-
# wrapped at 72 columns.
-
1
def block_format(text)
-
formatted = text.split(/\n\r?\n/).collect { |paragraph|
-
format_paragraph(paragraph)
-
}.join("\n\n")
-
-
# Make list points stand on their own line
-
formatted.gsub!(/[ ]*([*]+) ([^*]*)/) { |s| " #{$1} #{$2.strip}\n" }
-
formatted.gsub!(/[ ]*([#]+) ([^#]*)/) { |s| " #{$1} #{$2.strip}\n" }
-
-
formatted
-
end
-
-
# Access the mailer instance.
-
1
def mailer
-
@_controller
-
end
-
-
# Access the message instance.
-
1
def message
-
@_message
-
end
-
-
# Access the message attachments list.
-
1
def attachments
-
@_message.attachments
-
end
-
-
# Returns +text+ wrapped at +len+ columns and indented +indent+ spaces.
-
#
-
# my_text = 'Here is a sample text with more than 40 characters'
-
#
-
# format_paragraph(my_text, 25, 4)
-
# # => " Here is a sample text with\n more than 40 characters"
-
1
def format_paragraph(text, len = 72, indent = 2)
-
sentences = [[]]
-
-
text.split.each do |word|
-
if sentences.first.present? && (sentences.last + [word]).join(' ').length > len
-
sentences << [word]
-
else
-
sentences.last << word
-
end
-
end
-
-
indentation = " " * indent
-
sentences.map! { |sentence|
-
"#{indentation}#{sentence.join(' ')}"
-
}.join "\n"
-
end
-
end
-
end
-
1
require "action_mailer"
-
1
require "rails"
-
1
require "abstract_controller/railties/routes_helpers"
-
-
1
module ActionMailer
-
1
class Railtie < Rails::Railtie # :nodoc:
-
1
config.action_mailer = ActiveSupport::OrderedOptions.new
-
1
config.eager_load_namespaces << ActionMailer
-
-
1
initializer "action_mailer.logger" do
-
2
ActiveSupport.on_load(:action_mailer) { self.logger ||= Rails.logger }
-
end
-
-
1
initializer "action_mailer.set_configs" do |app|
-
1
paths = app.config.paths
-
1
options = app.config.action_mailer
-
-
1
options.assets_dir ||= paths["public"].first
-
1
options.javascripts_dir ||= paths["public/javascripts"].first
-
1
options.stylesheets_dir ||= paths["public/stylesheets"].first
-
-
1
if Rails.env.development?
-
options.preview_path ||= defined?(Rails.root) ? "#{Rails.root}/test/mailers/previews" : nil
-
end
-
-
# make sure readers methods get compiled
-
1
options.asset_host ||= app.config.asset_host
-
1
options.relative_url_root ||= app.config.relative_url_root
-
-
1
ActiveSupport.on_load(:action_mailer) do
-
1
include AbstractController::UrlFor
-
1
extend ::AbstractController::Railties::RoutesHelpers.with(app.routes)
-
1
include app.routes.mounted_helpers
-
-
1
register_interceptors(options.delete(:interceptors))
-
1
register_observers(options.delete(:observers))
-
-
7
options.each { |k,v| send("#{k}=", v) }
-
end
-
end
-
-
1
initializer "action_mailer.compile_config_methods" do
-
1
ActiveSupport.on_load(:action_mailer) do
-
1
config.compile_methods! if config.respond_to?(:compile_methods!)
-
end
-
end
-
-
1
config.after_initialize do
-
1
if ActionMailer::Base.preview_path
-
ActiveSupport::Dependencies.autoload_paths << ActionMailer::Base.preview_path
-
end
-
end
-
end
-
end
-
1
require 'active_support/test_case'
-
-
1
module ActionMailer
-
1
class NonInferrableMailerError < ::StandardError
-
1
def initialize(name)
-
super "Unable to determine the mailer to test from #{name}. " +
-
"You'll need to specify it using tests YourMailer in your " +
-
"test case definition"
-
end
-
end
-
-
1
class TestCase < ActiveSupport::TestCase
-
1
module Behavior
-
1
extend ActiveSupport::Concern
-
-
1
include ActiveSupport::Testing::ConstantLookup
-
1
include TestHelper
-
-
1
included do
-
1
class_attribute :_mailer_class
-
1
setup :initialize_test_deliveries
-
1
setup :set_expected_mail
-
end
-
-
1
module ClassMethods
-
1
def tests(mailer)
-
case mailer
-
when String, Symbol
-
self._mailer_class = mailer.to_s.camelize.constantize
-
when Module
-
self._mailer_class = mailer
-
else
-
raise NonInferrableMailerError.new(mailer)
-
end
-
end
-
-
1
def mailer_class
-
if mailer = self._mailer_class
-
mailer
-
else
-
tests determine_default_mailer(name)
-
end
-
end
-
-
1
def determine_default_mailer(name)
-
mailer = determine_constant_from_test_name(name) do |constant|
-
Class === constant && constant < ActionMailer::Base
-
end
-
raise NonInferrableMailerError.new(name) if mailer.nil?
-
mailer
-
end
-
end
-
-
1
protected
-
-
1
def initialize_test_deliveries
-
ActionMailer::Base.delivery_method = :test
-
ActionMailer::Base.perform_deliveries = true
-
ActionMailer::Base.deliveries.clear
-
end
-
-
1
def set_expected_mail
-
@expected = Mail.new
-
@expected.content_type ["text", "plain", { "charset" => charset }]
-
@expected.mime_version = '1.0'
-
end
-
-
1
private
-
-
1
def charset
-
"UTF-8"
-
end
-
-
1
def encode(subject)
-
Mail::Encodings.q_value_encode(subject, charset)
-
end
-
-
1
def read_fixture(action)
-
IO.readlines(File.join(Rails.root, 'test', 'fixtures', self.class.mailer_class.name.underscore, action))
-
end
-
end
-
-
1
include Behavior
-
end
-
end
-
1
module ActionMailer
-
1
module TestHelper
-
# Asserts that the number of emails sent matches the given number.
-
#
-
# def test_emails
-
# assert_emails 0
-
# ContactMailer.welcome.deliver
-
# assert_emails 1
-
# ContactMailer.welcome.deliver
-
# assert_emails 2
-
# end
-
#
-
# If a block is passed, that block should cause the specified number of
-
# emails to be sent.
-
#
-
# def test_emails_again
-
# assert_emails 1 do
-
# ContactMailer.welcome.deliver
-
# end
-
#
-
# assert_emails 2 do
-
# ContactMailer.welcome.deliver
-
# ContactMailer.welcome.deliver
-
# end
-
# end
-
1
def assert_emails(number)
-
if block_given?
-
original_count = ActionMailer::Base.deliveries.size
-
yield
-
new_count = ActionMailer::Base.deliveries.size
-
assert_equal original_count + number, new_count, "#{number} emails expected, but #{new_count - original_count} were sent"
-
else
-
assert_equal number, ActionMailer::Base.deliveries.size
-
end
-
end
-
-
# Assert that no emails have been sent.
-
#
-
# def test_emails
-
# assert_no_emails
-
# ContactMailer.welcome.deliver
-
# assert_emails 1
-
# end
-
#
-
# If a block is passed, that block should not cause any emails to be sent.
-
#
-
# def test_emails_again
-
# assert_no_emails do
-
# # No emails should be sent from this block
-
# end
-
# end
-
#
-
# Note: This assertion is simply a shortcut for:
-
#
-
# assert_emails 0
-
1
def assert_no_emails(&block)
-
assert_emails 0, &block
-
end
-
end
-
end
-
1
require_relative 'gem_version'
-
-
1
module ActionMailer
-
# Returns the version of the currently loaded ActionMailer as a <tt>Gem::Version</tt>
-
1
def self.version
-
gem_version
-
end
-
end
-
1
require 'action_pack'
-
1
require 'active_support/rails'
-
1
require 'active_support/core_ext/module/attr_internal'
-
1
require 'active_support/core_ext/module/anonymous'
-
1
require 'active_support/i18n'
-
-
1
module AbstractController
-
1
extend ActiveSupport::Autoload
-
-
1
autoload :Base
-
1
autoload :Callbacks
-
1
autoload :Collector
-
1
autoload :DoubleRenderError, "abstract_controller/rendering"
-
1
autoload :Helpers
-
1
autoload :Logger
-
1
autoload :Rendering
-
1
autoload :Translation
-
1
autoload :AssetPaths
-
1
autoload :UrlFor
-
end
-
1
module AbstractController
-
1
module AssetPaths #:nodoc:
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
2
config_accessor :asset_host, :assets_dir, :javascripts_dir,
-
:stylesheets_dir, :default_asset_host_protocol, :relative_url_root
-
end
-
end
-
end
-
1
require 'erubis'
-
1
require 'set'
-
1
require 'active_support/configurable'
-
1
require 'active_support/descendants_tracker'
-
1
require 'active_support/core_ext/module/anonymous'
-
-
1
module AbstractController
-
1
class Error < StandardError #:nodoc:
-
end
-
-
1
class ActionNotFound < StandardError #:nodoc:
-
end
-
-
# <tt>AbstractController::Base</tt> is a low-level API. Nobody should be
-
# using it directly, and subclasses (like ActionController::Base) are
-
# expected to provide their own +render+ method, since rendering means
-
# different things depending on the context.
-
1
class Base
-
1
attr_internal :response_body
-
1
attr_internal :action_name
-
1
attr_internal :formats
-
-
1
include ActiveSupport::Configurable
-
1
extend ActiveSupport::DescendantsTracker
-
-
1
undef_method :not_implemented
-
1
class << self
-
1
attr_reader :abstract
-
1
alias_method :abstract?, :abstract
-
-
# Define a controller as abstract. See internal_methods for more
-
# details.
-
1
def abstract!
-
4
@abstract = true
-
end
-
-
1
def inherited(klass) # :nodoc:
-
# Define the abstract ivar on subclasses so that we don't get
-
# uninitialized ivar warnings
-
5
unless klass.instance_variable_defined?(:@abstract)
-
5
klass.instance_variable_set(:@abstract, false)
-
end
-
5
super
-
end
-
-
# A list of all internal methods for a controller. This finds the first
-
# abstract superclass of a controller, and gets a list of all public
-
# instance methods on that abstract class. Public instance methods of
-
# a controller would normally be considered action methods, so methods
-
# declared on abstract classes are being removed.
-
# (ActionController::Metal and ActionController::Base are defined as abstract)
-
1
def internal_methods
-
1
controller = self
-
-
1
controller = controller.superclass until controller.abstract?
-
1
controller.public_instance_methods(true)
-
end
-
-
# The list of hidden actions. Defaults to an empty array.
-
# This can be modified by other modules or subclasses
-
# to specify particular actions as hidden.
-
#
-
# ==== Returns
-
# * <tt>Array</tt> - An array of method names that should not be considered actions.
-
1
def hidden_actions
-
1
[]
-
end
-
-
# A list of method names that should be considered actions. This
-
# includes all public instance methods on a controller, less
-
# any internal methods (see #internal_methods), adding back in
-
# any methods that are internal, but still exist on the class
-
# itself. Finally, #hidden_actions are removed.
-
#
-
# ==== Returns
-
# * <tt>Set</tt> - A set of all methods that should be considered actions.
-
1
def action_methods
-
@action_methods ||= begin
-
# All public instance methods of this class, including ancestors
-
1
methods = (public_instance_methods(true) -
-
# Except for public instance methods of Base and its ancestors
-
internal_methods +
-
# Be sure to include shadowed public instance methods of this class
-
67
public_instance_methods(false)).uniq.map { |x| x.to_s } -
-
# And always exclude explicitly hidden actions
-
hidden_actions.to_a
-
-
# Clear out AS callback method pollution
-
67
Set.new(methods.reject { |method| method =~ /_one_time_conditions/ })
-
1
end
-
end
-
-
# action_methods are cached and there is sometimes need to refresh
-
# them. clear_action_methods! allows you to do that, so next time
-
# you run action_methods, they will be recalculated
-
1
def clear_action_methods!
-
229
@action_methods = nil
-
end
-
-
# Returns the full controller name, underscored, without the ending Controller.
-
# For instance, MyApp::MyPostsController would return "my_app/my_posts" for
-
# controller_path.
-
#
-
# ==== Returns
-
# * <tt>String</tt>
-
1
def controller_path
-
6
@controller_path ||= name.sub(/Controller$/, '').underscore unless anonymous?
-
end
-
-
# Refresh the cached action_methods when a new action_method is added.
-
1
def method_added(name)
-
229
super
-
229
clear_action_methods!
-
end
-
end
-
-
1
abstract!
-
-
# Calls the action going through the entire action dispatch stack.
-
#
-
# The actual method that is called is determined by calling
-
# #method_for_action. If no method can handle the action, then an
-
# ActionNotFound error is raised.
-
#
-
# ==== Returns
-
# * <tt>self</tt>
-
1
def process(action, *args)
-
@_action_name = action_name = action.to_s
-
-
unless action_name = method_for_action(action_name)
-
raise ActionNotFound, "The action '#{action}' could not be found for #{self.class.name}"
-
end
-
-
@_response_body = nil
-
-
process_action(action_name, *args)
-
end
-
-
# Delegates to the class' #controller_path
-
1
def controller_path
-
self.class.controller_path
-
end
-
-
# Delegates to the class' #action_methods
-
1
def action_methods
-
self.class.action_methods
-
end
-
-
# Returns true if a method for the action is available and
-
# can be dispatched, false otherwise.
-
#
-
# Notice that <tt>action_methods.include?("foo")</tt> may return
-
# false and <tt>available_action?("foo")</tt> returns true because
-
# this method considers actions that are also available
-
# through other means, for example, implicit render ones.
-
#
-
# ==== Parameters
-
# * <tt>action_name</tt> - The name of an action to be tested
-
#
-
# ==== Returns
-
# * <tt>TrueClass</tt>, <tt>FalseClass</tt>
-
1
def available_action?(action_name)
-
method_for_action(action_name).present?
-
end
-
-
1
private
-
-
# Returns true if the name can be considered an action because
-
# it has a method defined in the controller.
-
#
-
# ==== Parameters
-
# * <tt>name</tt> - The name of an action to be tested
-
#
-
# ==== Returns
-
# * <tt>TrueClass</tt>, <tt>FalseClass</tt>
-
#
-
# :api: private
-
1
def action_method?(name)
-
self.class.action_methods.include?(name)
-
end
-
-
# Call the action. Override this in a subclass to modify the
-
# behavior around processing an action. This, and not #process,
-
# is the intended way to override action dispatching.
-
#
-
# Notice that the first argument is the method to be dispatched
-
# which is *not* necessarily the same as the action name.
-
1
def process_action(method_name, *args)
-
send_action(method_name, *args)
-
end
-
-
# Actually call the method associated with the action. Override
-
# this method if you wish to change how action methods are called,
-
# not to add additional behavior around it. For example, you would
-
# override #send_action if you want to inject arguments into the
-
# method.
-
1
alias send_action send
-
-
# If the action name was not found, but a method called "action_missing"
-
# was found, #method_for_action will return "_handle_action_missing".
-
# This method calls #action_missing with the current action name.
-
1
def _handle_action_missing(*args)
-
action_missing(@_action_name, *args)
-
end
-
-
# Takes an action name and returns the name of the method that will
-
# handle the action. In normal cases, this method returns the same
-
# name as it receives. By default, if #method_for_action receives
-
# a name that is not an action, it will look for an #action_missing
-
# method and return "_handle_action_missing" if one is found.
-
#
-
# Subclasses may override this method to add additional conditions
-
# that should be considered an action. For instance, an HTTP controller
-
# with a template matching the action name is considered to exist.
-
#
-
# If you override this method to handle additional cases, you may
-
# also provide a method (like _handle_method_missing) to handle
-
# the case.
-
#
-
# If none of these conditions are true, and method_for_action
-
# returns nil, an ActionNotFound exception will be raised.
-
#
-
# ==== Parameters
-
# * <tt>action_name</tt> - An action name to find a method name for
-
#
-
# ==== Returns
-
# * <tt>string</tt> - The name of the method that handles the action
-
# * <tt>nil</tt> - No method name could be found. Raise ActionNotFound.
-
1
def method_for_action(action_name)
-
if action_method?(action_name)
-
action_name
-
elsif respond_to?(:action_missing, true)
-
"_handle_action_missing"
-
end
-
end
-
end
-
end
-
1
module AbstractController
-
1
module Callbacks
-
1
extend ActiveSupport::Concern
-
-
# Uses ActiveSupport::Callbacks as the base functionality. For
-
# more details on the whole callback system, read the documentation
-
# for ActiveSupport::Callbacks.
-
1
include ActiveSupport::Callbacks
-
-
1
included do
-
2
define_callbacks :process_action,
-
terminator: ->(controller,_) { controller.response_body },
-
skip_after_callbacks_if_terminated: true
-
end
-
-
# Override AbstractController::Base's process_action to run the
-
# process_action callbacks around the normal behavior.
-
1
def process_action(*args)
-
run_callbacks(:process_action) do
-
super
-
end
-
end
-
-
1
module ClassMethods
-
# If :only or :except are used, convert the options into the
-
# :unless and :if options of ActiveSupport::Callbacks.
-
# The basic idea is that :only => :index gets converted to
-
# :if => proc {|c| c.action_name == "index" }.
-
#
-
# ==== Options
-
# * <tt>only</tt> - The callback should be run only for this action
-
# * <tt>except</tt> - The callback should be run for all actions except this action
-
1
def _normalize_callback_options(options)
-
2
_normalize_callback_option(options, :only, :if)
-
2
_normalize_callback_option(options, :except, :unless)
-
end
-
-
1
def _normalize_callback_option(options, from, to) # :nodoc:
-
4
if from = options[from]
-
from = Array(from).map {|o| "action_name == '#{o}'"}.join(" || ")
-
options[to] = Array(options[to]).unshift(from)
-
end
-
end
-
-
# Skip before, after, and around action callbacks matching any of the names
-
# Aliased as skip_filter.
-
#
-
# ==== Parameters
-
# * <tt>names</tt> - A list of valid names that could be used for
-
# callbacks. Note that skipping uses Ruby equality, so it's
-
# impossible to skip a callback defined using an anonymous proc
-
# using #skip_filter
-
1
def skip_action_callback(*names)
-
skip_before_action(*names)
-
skip_after_action(*names)
-
skip_around_action(*names)
-
end
-
-
1
alias_method :skip_filter, :skip_action_callback
-
-
# Take callback names and an optional callback proc, normalize them,
-
# then call the block with each callback. This allows us to abstract
-
# the normalization across several methods that use it.
-
#
-
# ==== Parameters
-
# * <tt>callbacks</tt> - An array of callbacks, with an optional
-
# options hash as the last parameter.
-
# * <tt>block</tt> - A proc that should be added to the callbacks.
-
#
-
# ==== Block Parameters
-
# * <tt>name</tt> - The callback to be added
-
# * <tt>options</tt> - A hash of options to be used when adding the callback
-
1
def _insert_callbacks(callbacks, block = nil)
-
2
options = callbacks.extract_options!
-
2
_normalize_callback_options(options)
-
2
callbacks.push(block) if block
-
2
callbacks.each do |callback|
-
3
yield callback, options
-
end
-
end
-
-
##
-
# :method: before_action
-
#
-
# :call-seq: before_action(names, block)
-
#
-
# Append a callback before actions. See _insert_callbacks for parameter details.
-
# Aliased as before_filter.
-
-
##
-
# :method: prepend_before_action
-
#
-
# :call-seq: prepend_before_action(names, block)
-
#
-
# Prepend a callback before actions. See _insert_callbacks for parameter details.
-
# Aliased as prepend_before_filter.
-
-
##
-
# :method: skip_before_action
-
#
-
# :call-seq: skip_before_action(names)
-
#
-
# Skip a callback before actions. See _insert_callbacks for parameter details.
-
# Aliased as skip_before_filter.
-
-
##
-
# :method: append_before_action
-
#
-
# :call-seq: append_before_action(names, block)
-
#
-
# Append a callback before actions. See _insert_callbacks for parameter details.
-
# Aliased as append_before_filter.
-
-
##
-
# :method: after_action
-
#
-
# :call-seq: after_action(names, block)
-
#
-
# Append a callback after actions. See _insert_callbacks for parameter details.
-
# Aliased as after_filter.
-
-
##
-
# :method: prepend_after_action
-
#
-
# :call-seq: prepend_after_action(names, block)
-
#
-
# Prepend a callback after actions. See _insert_callbacks for parameter details.
-
# Aliased as prepend_after_filter.
-
-
##
-
# :method: skip_after_action
-
#
-
# :call-seq: skip_after_action(names)
-
#
-
# Skip a callback after actions. See _insert_callbacks for parameter details.
-
# Aliased as skip_after_filter.
-
-
##
-
# :method: append_after_action
-
#
-
# :call-seq: append_after_action(names, block)
-
#
-
# Append a callback after actions. See _insert_callbacks for parameter details.
-
# Aliased as append_after_filter.
-
-
##
-
# :method: around_action
-
#
-
# :call-seq: around_action(names, block)
-
#
-
# Append a callback around actions. See _insert_callbacks for parameter details.
-
# Aliased as around_filter.
-
-
##
-
# :method: prepend_around_action
-
#
-
# :call-seq: prepend_around_action(names, block)
-
#
-
# Prepend a callback around actions. See _insert_callbacks for parameter details.
-
# Aliased as prepend_around_filter.
-
-
##
-
# :method: skip_around_action
-
#
-
# :call-seq: skip_around_action(names)
-
#
-
# Skip a callback around actions. See _insert_callbacks for parameter details.
-
# Aliased as skip_around_filter.
-
-
##
-
# :method: append_around_action
-
#
-
# :call-seq: append_around_action(names, block)
-
#
-
# Append a callback around actions. See _insert_callbacks for parameter details.
-
# Aliased as append_around_filter.
-
-
# set up before_action, prepend_before_action, skip_before_action, etc.
-
# for each of before, after, and around.
-
1
[:before, :after, :around].each do |callback|
-
3
class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
-
# Append a before, after or around callback. See _insert_callbacks
-
# for details on the allowed parameters.
-
def #{callback}_action(*names, &blk) # def before_action(*names, &blk)
-
_insert_callbacks(names, blk) do |name, options| # _insert_callbacks(names, blk) do |name, options|
-
set_callback(:process_action, :#{callback}, name, options) # set_callback(:process_action, :before, name, options)
-
end # end
-
end # end
-
-
alias_method :#{callback}_filter, :#{callback}_action
-
-
# Prepend a before, after or around callback. See _insert_callbacks
-
# for details on the allowed parameters.
-
def prepend_#{callback}_action(*names, &blk) # def prepend_before_action(*names, &blk)
-
_insert_callbacks(names, blk) do |name, options| # _insert_callbacks(names, blk) do |name, options|
-
set_callback(:process_action, :#{callback}, name, options.merge(:prepend => true)) # set_callback(:process_action, :before, name, options.merge(:prepend => true))
-
end # end
-
end # end
-
-
alias_method :prepend_#{callback}_filter, :prepend_#{callback}_action
-
-
# Skip a before, after or around callback. See _insert_callbacks
-
# for details on the allowed parameters.
-
def skip_#{callback}_action(*names) # def skip_before_action(*names)
-
_insert_callbacks(names) do |name, options| # _insert_callbacks(names) do |name, options|
-
skip_callback(:process_action, :#{callback}, name, options) # skip_callback(:process_action, :before, name, options)
-
end # end
-
end # end
-
-
alias_method :skip_#{callback}_filter, :skip_#{callback}_action
-
-
# *_action is the same as append_*_action
-
alias_method :append_#{callback}_action, :#{callback}_action # alias_method :append_before_action, :before_action
-
alias_method :append_#{callback}_filter, :#{callback}_action # alias_method :append_before_filter, :before_action
-
RUBY_EVAL
-
end
-
end
-
end
-
end
-
1
require "action_dispatch/http/mime_type"
-
-
1
module AbstractController
-
1
module Collector
-
1
def self.generate_method_for_mime(mime)
-
22
sym = mime.is_a?(Symbol) ? mime : mime.to_sym
-
22
const = sym.upcase
-
22
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{sym}(*args, &block) # def html(*args, &block)
-
custom(Mime::#{const}, *args, &block) # custom(Mime::HTML, *args, &block)
-
end # end
-
RUBY
-
end
-
-
1
Mime::SET.each do |mime|
-
22
generate_method_for_mime(mime)
-
end
-
-
1
Mime::Type.register_callback do |mime|
-
generate_method_for_mime(mime) unless self.instance_methods.include?(mime.to_sym)
-
end
-
-
1
protected
-
-
1
def method_missing(symbol, &block)
-
const_name = symbol.upcase
-
-
unless Mime.const_defined?(const_name)
-
raise NoMethodError, "To respond to a custom format, register it as a MIME type first: " \
-
"http://guides.rubyonrails.org/action_controller_overview.html#restful-downloads. " \
-
"If you meant to respond to a variant like :tablet or :phone, not a custom format, " \
-
"be sure to nest your variant response within a format response: " \
-
"format.html { |html| html.tablet { ... } }"
-
end
-
-
mime_constant = Mime.const_get(const_name)
-
-
if Mime::SET.include?(mime_constant)
-
AbstractController::Collector.generate_method_for_mime(mime_constant)
-
send(symbol, &block)
-
else
-
super
-
end
-
end
-
end
-
end
-
1
require 'active_support/dependencies'
-
-
1
module AbstractController
-
1
module Helpers
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
3
class_attribute :_helpers
-
3
self._helpers = Module.new
-
-
3
class_attribute :_helper_methods
-
3
self._helper_methods = Array.new
-
end
-
-
1
class MissingHelperError < LoadError
-
1
def initialize(error, path)
-
1
@error = error
-
1
@path = "helpers/#{path}.rb"
-
1
set_backtrace error.backtrace
-
-
1
if error.path =~ /^#{path}(\.rb)?$/
-
1
super("Missing helper file helpers/%s.rb" % path)
-
else
-
raise error
-
end
-
end
-
end
-
-
1
module ClassMethods
-
1
MissingHelperError = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('AbstractController::Helpers::ClassMethods::MissingHelperError',
-
'AbstractController::Helpers::MissingHelperError')
-
-
# When a class is inherited, wrap its helper module in a new module.
-
# This ensures that the parent class's module can be changed
-
# independently of the child class's.
-
1
def inherited(klass)
-
1
helpers = _helpers
-
2
klass._helpers = Module.new { include helpers }
-
2
klass.class_eval { default_helper_module! } unless klass.anonymous?
-
1
super
-
end
-
-
# Declare a controller method as a helper. For example, the following
-
# makes the +current_user+ controller method available to the view:
-
# class ApplicationController < ActionController::Base
-
# helper_method :current_user, :logged_in?
-
#
-
# def current_user
-
# @current_user ||= User.find_by(id: session[:user])
-
# end
-
#
-
# def logged_in?
-
# current_user != nil
-
# end
-
# end
-
#
-
# In a view:
-
# <% if logged_in? -%>Welcome, <%= current_user.name %><% end -%>
-
#
-
# ==== Parameters
-
# * <tt>method[, method]</tt> - A name or names of a method on the controller
-
# to be made available on the view.
-
1
def helper_method(*meths)
-
9
meths.flatten!
-
9
self._helper_methods += meths
-
-
9
meths.each do |meth|
-
15
_helpers.class_eval <<-ruby_eval, __FILE__, __LINE__ + 1
-
def #{meth}(*args, &blk) # def current_user(*args, &blk)
-
controller.send(%(#{meth}), *args, &blk) # controller.send(:current_user, *args, &blk)
-
end # end
-
ruby_eval
-
end
-
end
-
-
# The +helper+ class method can take a series of helper module names, a block, or both.
-
#
-
# ==== Options
-
# * <tt>*args</tt> - Module, Symbol, String
-
# * <tt>block</tt> - A block defining helper methods
-
#
-
# When the argument is a module it will be included directly in the template class.
-
# helper FooHelper # => includes FooHelper
-
#
-
# When the argument is a string or symbol, the method will provide the "_helper" suffix, require the file
-
# and include the module in the template class. The second form illustrates how to include custom helpers
-
# when working with namespaced controllers, or other cases where the file containing the helper definition is not
-
# in one of Rails' standard load paths:
-
# helper :foo # => requires 'foo_helper' and includes FooHelper
-
# helper 'resources/foo' # => requires 'resources/foo_helper' and includes Resources::FooHelper
-
#
-
# Additionally, the +helper+ class method can receive and evaluate a block, making the methods defined available
-
# to the template.
-
#
-
# # One line
-
# helper { def hello() "Hello, world!" end }
-
#
-
# # Multi-line
-
# helper do
-
# def foo(bar)
-
# "#{bar} is the very best"
-
# end
-
# end
-
#
-
# Finally, all the above styles can be mixed together, and the +helper+ method can be invoked with a mix of
-
# +symbols+, +strings+, +modules+ and blocks.
-
#
-
# helper(:three, BlindHelper) { def mice() 'mice' end }
-
#
-
1
def helper(*args, &block)
-
3
modules_for_helpers(args).each do |mod|
-
16
add_template_helper(mod)
-
end
-
-
2
_helpers.module_eval(&block) if block_given?
-
end
-
-
# Clears up all existing helpers in this class, only keeping the helper
-
# with the same name as this class.
-
1
def clear_helpers
-
inherited_helper_methods = _helper_methods
-
self._helpers = Module.new
-
self._helper_methods = Array.new
-
-
inherited_helper_methods.each { |meth| helper_method meth }
-
default_helper_module! unless anonymous?
-
end
-
-
# Returns a list of modules, normalized from the acceptable kinds of
-
# helpers with the following behavior:
-
#
-
# String or Symbol:: :FooBar or "FooBar" becomes "foo_bar_helper",
-
# and "foo_bar_helper.rb" is loaded using require_dependency.
-
#
-
# Module:: No further processing
-
#
-
# After loading the appropriate files, the corresponding modules
-
# are returned.
-
#
-
# ==== Parameters
-
# * <tt>args</tt> - An array of helpers
-
#
-
# ==== Returns
-
# * <tt>Array</tt> - A normalized list of modules for the list of
-
# helpers provided.
-
1
def modules_for_helpers(args)
-
3
args.flatten.map! do |arg|
-
17
case arg
-
when String, Symbol
-
16
file_name = "#{arg.to_s.underscore}_helper"
-
16
begin
-
16
require_dependency(file_name)
-
rescue LoadError => e
-
1
raise AbstractController::Helpers::MissingHelperError.new(e, file_name)
-
end
-
15
file_name.camelize.constantize
-
when Module
-
1
arg
-
else
-
raise ArgumentError, "helper must be a String, Symbol, or Module"
-
end
-
end
-
end
-
-
1
private
-
# Makes all the (instance) methods in the helper module available to templates
-
# rendered through this controller.
-
#
-
# ==== Parameters
-
# * <tt>module</tt> - The module to include into the current helper module
-
# for the class
-
1
def add_template_helper(mod)
-
32
_helpers.module_eval { include mod }
-
end
-
-
1
def default_helper_module!
-
1
module_name = name.sub(/Controller$/, '')
-
1
module_path = module_name.underscore
-
1
helper module_path
-
rescue MissingSourceFile => e
-
1
raise e unless e.is_missing? "helpers/#{module_path}_helper"
-
rescue NameError => e
-
raise e unless e.missing_name? "#{module_name}Helper"
-
end
-
end
-
end
-
end
-
1
require "active_support/benchmarkable"
-
-
1
module AbstractController
-
1
module Logger #:nodoc:
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
3
config_accessor :logger
-
3
include ActiveSupport::Benchmarkable
-
end
-
end
-
end
-
1
module AbstractController
-
1
module Railties
-
1
module RoutesHelpers
-
1
def self.with(routes)
-
2
Module.new do
-
2
define_method(:inherited) do |klass|
-
1
super(klass)
-
4
if namespace = klass.parents.detect { |m| m.respond_to?(:railtie_routes_url_helpers) }
-
klass.send(:include, namespace.railtie_routes_url_helpers)
-
else
-
1
klass.send(:include, routes.url_helpers)
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/concern'
-
1
require 'active_support/core_ext/class/attribute'
-
1
require 'action_view'
-
1
require 'action_view/view_paths'
-
1
require 'set'
-
-
1
module AbstractController
-
1
class DoubleRenderError < Error
-
1
DEFAULT_MESSAGE = "Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like \"redirect_to(...) and return\"."
-
-
1
def initialize(message = nil)
-
super(message || DEFAULT_MESSAGE)
-
end
-
end
-
-
1
module Rendering
-
1
extend ActiveSupport::Concern
-
1
include ActionView::ViewPaths
-
-
# Normalize arguments, options and then delegates render_to_body and
-
# sticks the result in self.response_body.
-
# :api: public
-
1
def render(*args, &block)
-
options = _normalize_render(*args, &block)
-
self.response_body = render_to_body(options)
-
_process_format(rendered_format, options) if rendered_format
-
self.response_body
-
end
-
-
# Raw rendering of a template to a string.
-
#
-
# It is similar to render, except that it does not
-
# set the response_body and it should be guaranteed
-
# to always return a string.
-
#
-
# If a component extends the semantics of response_body
-
# (as Action Controller extends it to be anything that
-
# responds to the method each), this method needs to be
-
# overridden in order to still return a string.
-
# :api: plugin
-
1
def render_to_string(*args, &block)
-
options = _normalize_render(*args, &block)
-
render_to_body(options)
-
end
-
-
# Performs the actual template rendering.
-
# :api: public
-
1
def render_to_body(options = {})
-
end
-
-
# Returns Content-Type of rendered content
-
# :api: public
-
1
def rendered_format
-
Mime::TEXT
-
end
-
-
1
DEFAULT_PROTECTED_INSTANCE_VARIABLES = Set.new %w(
-
@_action_name @_response_body @_formats @_prefixes @_config
-
@_view_context_class @_view_renderer @_lookup_context
-
@_routes @_db_runtime
-
).map(&:to_sym)
-
-
# This method should return a hash with assigns.
-
# You can overwrite this configuration per controller.
-
# :api: public
-
1
def view_assigns
-
protected_vars = _protected_ivars
-
variables = instance_variables
-
-
variables.reject! { |s| protected_vars.include? s }
-
variables.each_with_object({}) { |name, hash|
-
hash[name.slice(1, name.length)] = instance_variable_get(name)
-
}
-
end
-
-
# Normalize args by converting render "foo" to render :action => "foo" and
-
# render "foo/bar" to render :file => "foo/bar".
-
# :api: plugin
-
1
def _normalize_args(action=nil, options={})
-
if action.is_a? Hash
-
action
-
else
-
options
-
end
-
end
-
-
# Normalize options.
-
# :api: plugin
-
1
def _normalize_options(options)
-
options
-
end
-
-
# Process extra options.
-
# :api: plugin
-
1
def _process_options(options)
-
options
-
end
-
-
# Process the rendered format.
-
# :api: private
-
1
def _process_format(format, options = {})
-
end
-
-
# Normalize args and options.
-
# :api: private
-
1
def _normalize_render(*args, &block)
-
options = _normalize_args(*args, &block)
-
#TODO: remove defined? when we restore AP <=> AV dependency
-
options[:variant] = request.variant if defined?(request) && request.variant.present?
-
_normalize_options(options)
-
options
-
end
-
-
1
def _protected_ivars # :nodoc:
-
DEFAULT_PROTECTED_INSTANCE_VARIABLES
-
end
-
end
-
end
-
1
module AbstractController
-
1
module Translation
-
# Delegates to <tt>I18n.translate</tt>. Also aliased as <tt>t</tt>.
-
#
-
# When the given key starts with a period, it will be scoped by the current
-
# controller and action. So if you call <tt>translate(".foo")</tt> from
-
# <tt>PeopleController#index</tt>, it will convert the call to
-
# <tt>I18n.translate("people.index.foo")</tt>. This makes it less repetitive
-
# to translate many keys within the same controller / action and gives you a
-
# simple framework for scoping them consistently.
-
1
def translate(*args)
-
key = args.first
-
if key.is_a?(String) && (key[0] == '.')
-
key = "#{ controller_path.tr('/', '.') }.#{ action_name }#{ key }"
-
args[0] = key
-
end
-
-
I18n.translate(*args)
-
end
-
1
alias :t :translate
-
-
# Delegates to <tt>I18n.localize</tt>. Also aliased as <tt>l</tt>.
-
1
def localize(*args)
-
I18n.localize(*args)
-
end
-
1
alias :l :localize
-
end
-
end
-
1
module AbstractController
-
# Includes +url_for+ into the host class (e.g. an abstract controller or mailer). The class
-
# has to provide a +RouteSet+ by implementing the <tt>_routes</tt> methods. Otherwise, an
-
# exception will be raised.
-
#
-
# Note that this module is completely decoupled from HTTP - the only requirement is a valid
-
# <tt>_routes</tt> implementation.
-
1
module UrlFor
-
1
extend ActiveSupport::Concern
-
1
include ActionDispatch::Routing::UrlFor
-
-
1
def _routes
-
raise "In order to use #url_for, you must include routing helpers explicitly. " \
-
"For instance, `include Rails.application.routes.url_helpers"
-
end
-
-
1
module ClassMethods
-
1
def _routes
-
nil
-
end
-
-
1
def action_methods
-
@action_methods ||= begin
-
if _routes
-
super - _routes.named_routes.helper_names
-
else
-
super
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/rails'
-
1
require 'abstract_controller'
-
1
require 'action_dispatch'
-
1
require 'action_controller/metal/live'
-
1
require 'action_controller/metal/strong_parameters'
-
-
1
module ActionController
-
1
extend ActiveSupport::Autoload
-
-
1
autoload :Base
-
1
autoload :Caching
-
1
autoload :Metal
-
1
autoload :Middleware
-
-
1
autoload_under "metal" do
-
1
autoload :Compatibility
-
1
autoload :ConditionalGet
-
1
autoload :Cookies
-
1
autoload :DataStreaming
-
1
autoload :Flash
-
1
autoload :ForceSSL
-
1
autoload :Head
-
1
autoload :Helpers
-
1
autoload :HideActions
-
1
autoload :HttpAuthentication
-
1
autoload :ImplicitRender
-
1
autoload :Instrumentation
-
1
autoload :MimeResponds
-
1
autoload :ParamsWrapper
-
1
autoload :RackDelegation
-
1
autoload :Redirecting
-
1
autoload :Renderers
-
1
autoload :Rendering
-
1
autoload :RequestForgeryProtection
-
1
autoload :Rescue
-
1
autoload :Responder
-
1
autoload :Streaming
-
1
autoload :StrongParameters
-
1
autoload :Testing
-
1
autoload :UrlFor
-
end
-
-
1
autoload :TestCase, 'action_controller/test_case'
-
1
autoload :TemplateAssertions, 'action_controller/test_case'
-
-
1
def self.eager_load!
-
super
-
ActionController::Caching.eager_load!
-
end
-
end
-
-
# Common Active Support usage in Action Controller
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/load_error'
-
1
require 'active_support/core_ext/module/attr_internal'
-
1
require 'active_support/core_ext/name_error'
-
1
require 'active_support/core_ext/uri'
-
1
require 'active_support/inflector'
-
1
require 'action_view'
-
1
require "action_controller/log_subscriber"
-
1
require "action_controller/metal/params_wrapper"
-
-
1
module ActionController
-
# Action Controllers are the core of a web request in \Rails. They are made up of one or more actions that are executed
-
# on request and then either it renders a template or redirects to another action. An action is defined as a public method
-
# on the controller, which will automatically be made accessible to the web-server through \Rails Routes.
-
#
-
# By default, only the ApplicationController in a \Rails application inherits from <tt>ActionController::Base</tt>. All other
-
# controllers in turn inherit from ApplicationController. This gives you one class to configure things such as
-
# request forgery protection and filtering of sensitive request parameters.
-
#
-
# A sample controller could look like this:
-
#
-
# class PostsController < ApplicationController
-
# def index
-
# @posts = Post.all
-
# end
-
#
-
# def create
-
# @post = Post.create params[:post]
-
# redirect_to posts_path
-
# end
-
# end
-
#
-
# Actions, by default, render a template in the <tt>app/views</tt> directory corresponding to the name of the controller and action
-
# after executing code in the action. For example, the +index+ action of the PostsController would render the
-
# template <tt>app/views/posts/index.html.erb</tt> by default after populating the <tt>@posts</tt> instance variable.
-
#
-
# Unlike index, the create action will not render a template. After performing its main purpose (creating a
-
# new post), it initiates a redirect instead. This redirect works by returning an external
-
# "302 Moved" HTTP response that takes the user to the index action.
-
#
-
# These two methods represent the two basic action archetypes used in Action Controllers. Get-and-show and do-and-redirect.
-
# Most actions are variations on these themes.
-
#
-
# == Requests
-
#
-
# For every request, the router determines the value of the +controller+ and +action+ keys. These determine which controller
-
# and action are called. The remaining request parameters, the session (if one is available), and the full request with
-
# all the HTTP headers are made available to the action through accessor methods. Then the action is performed.
-
#
-
# The full request object is available via the request accessor and is primarily used to query for HTTP headers:
-
#
-
# def server_ip
-
# location = request.env["SERVER_ADDR"]
-
# render plain: "This server hosted at #{location}"
-
# end
-
#
-
# == Parameters
-
#
-
# All request parameters, whether they come from a GET or POST request, or from the URL, are available through the params method
-
# which returns a hash. For example, an action that was performed through <tt>/posts?category=All&limit=5</tt> will include
-
# <tt>{ "category" => "All", "limit" => "5" }</tt> in params.
-
#
-
# It's also possible to construct multi-dimensional parameter hashes by specifying keys using brackets, such as:
-
#
-
# <input type="text" name="post[name]" value="david">
-
# <input type="text" name="post[address]" value="hyacintvej">
-
#
-
# A request stemming from a form holding these inputs will include <tt>{ "post" => { "name" => "david", "address" => "hyacintvej" } }</tt>.
-
# If the address input had been named <tt>post[address][street]</tt>, the params would have included
-
# <tt>{ "post" => { "address" => { "street" => "hyacintvej" } } }</tt>. There's no limit to the depth of the nesting.
-
#
-
# == Sessions
-
#
-
# Sessions allow you to store objects in between requests. This is useful for objects that are not yet ready to be persisted,
-
# such as a Signup object constructed in a multi-paged process, or objects that don't change much and are needed all the time, such
-
# as a User object for a system that requires login. The session should not be used, however, as a cache for objects where it's likely
-
# they could be changed unknowingly. It's usually too much work to keep it all synchronized -- something databases already excel at.
-
#
-
# You can place objects in the session by using the <tt>session</tt> method, which accesses a hash:
-
#
-
# session[:person] = Person.authenticate(user_name, password)
-
#
-
# And retrieved again through the same hash:
-
#
-
# Hello #{session[:person]}
-
#
-
# For removing objects from the session, you can either assign a single key to +nil+:
-
#
-
# # removes :person from session
-
# session[:person] = nil
-
#
-
# or you can remove the entire session with +reset_session+.
-
#
-
# Sessions are stored by default in a browser cookie that's cryptographically signed, but unencrypted.
-
# This prevents the user from tampering with the session but also allows them to see its contents.
-
#
-
# Do not put secret information in cookie-based sessions!
-
#
-
# == Responses
-
#
-
# Each action results in a response, which holds the headers and document to be sent to the user's browser. The actual response
-
# object is generated automatically through the use of renders and redirects and requires no user intervention.
-
#
-
# == Renders
-
#
-
# Action Controller sends content to the user by using one of five rendering methods. The most versatile and common is the rendering
-
# of a template. Included in the Action Pack is the Action View, which enables rendering of ERB templates. It's automatically configured.
-
# The controller passes objects to the view by assigning instance variables:
-
#
-
# def show
-
# @post = Post.find(params[:id])
-
# end
-
#
-
# Which are then automatically available to the view:
-
#
-
# Title: <%= @post.title %>
-
#
-
# You don't have to rely on the automated rendering. For example, actions that could result in the rendering of different templates
-
# will use the manual rendering methods:
-
#
-
# def search
-
# @results = Search.find(params[:query])
-
# case @results.count
-
# when 0 then render action: "no_results"
-
# when 1 then render action: "show"
-
# when 2..10 then render action: "show_many"
-
# end
-
# end
-
#
-
# Read more about writing ERB and Builder templates in ActionView::Base.
-
#
-
# == Redirects
-
#
-
# Redirects are used to move from one action to another. For example, after a <tt>create</tt> action, which stores a blog entry to the
-
# database, we might like to show the user the new entry. Because we're following good DRY principles (Don't Repeat Yourself), we're
-
# going to reuse (and redirect to) a <tt>show</tt> action that we'll assume has already been created. The code might look like this:
-
#
-
# def create
-
# @entry = Entry.new(params[:entry])
-
# if @entry.save
-
# # The entry was saved correctly, redirect to show
-
# redirect_to action: 'show', id: @entry.id
-
# else
-
# # things didn't go so well, do something else
-
# end
-
# end
-
#
-
# In this case, after saving our new entry to the database, the user is redirected to the <tt>show</tt> method, which is then executed.
-
# Note that this is an external HTTP-level redirection which will cause the browser to make a second request (a GET to the show action),
-
# and not some internal re-routing which calls both "create" and then "show" within one request.
-
#
-
# Learn more about <tt>redirect_to</tt> and what options you have in ActionController::Redirecting.
-
#
-
# == Calling multiple redirects or renders
-
#
-
# An action may contain only a single render or a single redirect. Attempting to try to do either again will result in a DoubleRenderError:
-
#
-
# def do_something
-
# redirect_to action: "elsewhere"
-
# render action: "overthere" # raises DoubleRenderError
-
# end
-
#
-
# If you need to redirect on the condition of something, then be sure to add "and return" to halt execution.
-
#
-
# def do_something
-
# redirect_to(action: "elsewhere") and return if monkeys.nil?
-
# render action: "overthere" # won't be called if monkeys is nil
-
# end
-
#
-
1
class Base < Metal
-
1
abstract!
-
-
# We document the request and response methods here because albeit they are
-
# implemented in ActionController::Metal, the type of the returned objects
-
# is unknown at that level.
-
-
##
-
# :method: request
-
#
-
# Returns an ActionDispatch::Request instance that represents the
-
# current request.
-
-
##
-
# :method: response
-
#
-
# Returns an ActionDispatch::Response that represents the current
-
# response.
-
-
# Shortcut helper that returns all the modules included in
-
# ActionController::Base except the ones passed as arguments:
-
#
-
# class MetalController
-
# ActionController::Base.without_modules(:ParamsWrapper, :Streaming).each do |left|
-
# include left
-
# end
-
# end
-
#
-
# This gives better control over what you want to exclude and makes it
-
# easier to create a bare controller class, instead of listing the modules
-
# required manually.
-
1
def self.without_modules(*modules)
-
modules = modules.map do |m|
-
m.is_a?(Symbol) ? ActionController.const_get(m) : m
-
end
-
-
MODULES - modules
-
end
-
-
1
MODULES = [
-
AbstractController::Rendering,
-
AbstractController::Translation,
-
AbstractController::AssetPaths,
-
-
Helpers,
-
HideActions,
-
UrlFor,
-
Redirecting,
-
ActionView::Layouts,
-
Rendering,
-
Renderers::All,
-
ConditionalGet,
-
RackDelegation,
-
Caching,
-
MimeResponds,
-
ImplicitRender,
-
StrongParameters,
-
-
Cookies,
-
Flash,
-
RequestForgeryProtection,
-
ForceSSL,
-
Streaming,
-
DataStreaming,
-
HttpAuthentication::Basic::ControllerMethods,
-
HttpAuthentication::Digest::ControllerMethods,
-
HttpAuthentication::Token::ControllerMethods,
-
-
# Before callbacks should also be executed the earliest as possible, so
-
# also include them at the bottom.
-
AbstractController::Callbacks,
-
-
# Append rescue at the bottom to wrap as much as possible.
-
Rescue,
-
-
# Add instrumentations hooks at the bottom, to ensure they instrument
-
# all the methods properly.
-
Instrumentation,
-
-
# Params wrapper should come before instrumentation so they are
-
# properly showed in logs
-
ParamsWrapper
-
]
-
-
1
MODULES.each do |mod|
-
29
include mod
-
end
-
-
# Define some internal variables that should not be propagated to the view.
-
1
PROTECTED_IVARS = AbstractController::Rendering::DEFAULT_PROTECTED_INSTANCE_VARIABLES + [
-
:@_status, :@_headers, :@_params, :@_env, :@_response, :@_request,
-
:@_view_runtime, :@_stream, :@_url_options, :@_action_has_layout ]
-
-
1
def _protected_ivars # :nodoc:
-
PROTECTED_IVARS
-
end
-
-
1
def self.protected_instance_variables
-
PROTECTED_IVARS
-
end
-
-
1
ActiveSupport.run_load_hooks(:action_controller, self)
-
end
-
end
-
1
require 'fileutils'
-
1
require 'uri'
-
1
require 'set'
-
-
1
module ActionController
-
# \Caching is a cheap way of speeding up slow applications by keeping the result of
-
# calculations, renderings, and database calls around for subsequent requests.
-
#
-
# You can read more about each approach by clicking the modules below.
-
#
-
# Note: To turn off all caching, set
-
# config.action_controller.perform_caching = false
-
#
-
# == \Caching stores
-
#
-
# All the caching stores from ActiveSupport::Cache are available to be used as backends
-
# for Action Controller caching.
-
#
-
# Configuration examples (MemoryStore is the default):
-
#
-
# config.action_controller.cache_store = :memory_store
-
# config.action_controller.cache_store = :file_store, '/path/to/cache/directory'
-
# config.action_controller.cache_store = :mem_cache_store, 'localhost'
-
# config.action_controller.cache_store = :mem_cache_store, Memcached::Rails.new('localhost:11211')
-
# config.action_controller.cache_store = MyOwnStore.new('parameter')
-
1
module Caching
-
1
extend ActiveSupport::Concern
-
1
extend ActiveSupport::Autoload
-
-
1
eager_autoload do
-
1
autoload :Fragments
-
end
-
-
1
module ConfigMethods
-
1
def cache_store
-
config.cache_store
-
end
-
-
1
def cache_store=(store)
-
1
config.cache_store = ActiveSupport::Cache.lookup_store(store)
-
end
-
-
1
private
-
1
def cache_configured?
-
perform_caching && cache_store
-
end
-
end
-
-
1
include RackDelegation
-
1
include AbstractController::Callbacks
-
-
1
include ConfigMethods
-
1
include Fragments
-
-
1
included do
-
1
extend ConfigMethods
-
-
1
config_accessor :default_static_extension
-
1
self.default_static_extension ||= '.html'
-
-
1
config_accessor :perform_caching
-
1
self.perform_caching = true if perform_caching.nil?
-
-
1
class_attribute :_view_cache_dependencies
-
1
self._view_cache_dependencies = []
-
1
helper_method :view_cache_dependencies if respond_to?(:helper_method)
-
end
-
-
1
module ClassMethods
-
1
def view_cache_dependency(&dependency)
-
self._view_cache_dependencies += [dependency]
-
end
-
end
-
-
1
def view_cache_dependencies
-
self.class._view_cache_dependencies.map { |dep| instance_exec(&dep) }.compact
-
end
-
-
1
protected
-
# Convenience accessor.
-
1
def cache(key, options = {}, &block)
-
if cache_configured?
-
cache_store.fetch(ActiveSupport::Cache.expand_cache_key(key, :controller), options, &block)
-
else
-
yield
-
end
-
end
-
end
-
end
-
1
module ActionController
-
1
module Caching
-
# Fragment caching is used for caching various blocks within
-
# views without caching the entire action as a whole. This is
-
# useful when certain elements of an action change frequently or
-
# depend on complicated state while other parts rarely change or
-
# can be shared amongst multiple parties. The caching is done using
-
# the +cache+ helper available in the Action View. See
-
# ActionView::Helpers::CacheHelper for more information.
-
#
-
# While it's strongly recommended that you use key-based cache
-
# expiration (see links in CacheHelper for more information),
-
# it is also possible to manually expire caches. For example:
-
#
-
# expire_fragment('name_of_cache')
-
1
module Fragments
-
# Given a key (as described in +expire_fragment+), returns
-
# a key suitable for use in reading, writing, or expiring a
-
# cached fragment. All keys are prefixed with <tt>views/</tt> and uses
-
# ActiveSupport::Cache.expand_cache_key for the expansion.
-
1
def fragment_cache_key(key)
-
ActiveSupport::Cache.expand_cache_key(key.is_a?(Hash) ? url_for(key).split("://").last : key, :views)
-
end
-
-
# Writes +content+ to the location signified by
-
# +key+ (see +expire_fragment+ for acceptable formats).
-
1
def write_fragment(key, content, options = nil)
-
return content unless cache_configured?
-
-
key = fragment_cache_key(key)
-
instrument_fragment_cache :write_fragment, key do
-
content = content.to_str
-
cache_store.write(key, content, options)
-
end
-
content
-
end
-
-
# Reads a cached fragment from the location signified by +key+
-
# (see +expire_fragment+ for acceptable formats).
-
1
def read_fragment(key, options = nil)
-
return unless cache_configured?
-
-
key = fragment_cache_key(key)
-
instrument_fragment_cache :read_fragment, key do
-
result = cache_store.read(key, options)
-
result.respond_to?(:html_safe) ? result.html_safe : result
-
end
-
end
-
-
# Check if a cached fragment from the location signified by
-
# +key+ exists (see +expire_fragment+ for acceptable formats).
-
1
def fragment_exist?(key, options = nil)
-
return unless cache_configured?
-
key = fragment_cache_key(key)
-
-
instrument_fragment_cache :exist_fragment?, key do
-
cache_store.exist?(key, options)
-
end
-
end
-
-
# Removes fragments from the cache.
-
#
-
# +key+ can take one of three forms:
-
#
-
# * String - This would normally take the form of a path, like
-
# <tt>pages/45/notes</tt>.
-
# * Hash - Treated as an implicit call to +url_for+, like
-
# <tt>{ controller: 'pages', action: 'notes', id: 45}</tt>
-
# * Regexp - Will remove any fragment that matches, so
-
# <tt>%r{pages/\d*/notes}</tt> might remove all notes. Make sure you
-
# don't use anchors in the regex (<tt>^</tt> or <tt>$</tt>) because
-
# the actual filename matched looks like
-
# <tt>./cache/filename/path.cache</tt>. Note: Regexp expiration is
-
# only supported on caches that can iterate over all keys (unlike
-
# memcached).
-
#
-
# +options+ is passed through to the cache store's +delete+
-
# method (or <tt>delete_matched</tt>, for Regexp keys).
-
1
def expire_fragment(key, options = nil)
-
return unless cache_configured?
-
key = fragment_cache_key(key) unless key.is_a?(Regexp)
-
-
instrument_fragment_cache :expire_fragment, key do
-
if key.is_a?(Regexp)
-
cache_store.delete_matched(key, options)
-
else
-
cache_store.delete(key, options)
-
end
-
end
-
end
-
-
1
def instrument_fragment_cache(name, key) # :nodoc:
-
ActiveSupport::Notifications.instrument("#{name}.action_controller", :key => key){ yield }
-
end
-
end
-
end
-
end
-
-
1
module ActionController
-
1
class LogSubscriber < ActiveSupport::LogSubscriber
-
1
INTERNAL_PARAMS = %w(controller action format _method only_path)
-
-
1
def start_processing(event)
-
return unless logger.info?
-
-
payload = event.payload
-
params = payload[:params].except(*INTERNAL_PARAMS)
-
format = payload[:format]
-
format = format.to_s.upcase if format.is_a?(Symbol)
-
-
info "Processing by #{payload[:controller]}##{payload[:action]} as #{format}"
-
info " Parameters: #{params.inspect}" unless params.empty?
-
end
-
-
1
def process_action(event)
-
return unless logger.info?
-
-
payload = event.payload
-
additions = ActionController::Base.log_process_action(payload)
-
-
status = payload[:status]
-
if status.nil? && payload[:exception].present?
-
exception_class_name = payload[:exception].first
-
status = ActionDispatch::ExceptionWrapper.status_code_for_exception(exception_class_name)
-
end
-
message = "Completed #{status} #{Rack::Utils::HTTP_STATUS_CODES[status]} in #{event.duration.round}ms"
-
message << " (#{additions.join(" | ")})" unless additions.blank?
-
-
info(message)
-
end
-
-
1
def halted_callback(event)
-
info("Filter chain halted as #{event.payload[:filter].inspect} rendered or redirected")
-
end
-
-
1
def send_file(event)
-
info("Sent file #{event.payload[:path]} (#{event.duration.round(1)}ms)")
-
end
-
-
1
def redirect_to(event)
-
info("Redirected to #{event.payload[:location]}")
-
end
-
-
1
def send_data(event)
-
info("Sent data #{event.payload[:filename]} (#{event.duration.round(1)}ms)")
-
end
-
-
1
def unpermitted_parameters(event)
-
unpermitted_keys = event.payload[:keys]
-
debug("Unpermitted parameters: #{unpermitted_keys.join(", ")}")
-
end
-
-
1
def deep_munge(event)
-
message = "Value for params[:#{event.payload[:keys].join('][:')}] was set "\
-
"to nil, because it was one of [], [null] or [null, null, ...]. "\
-
"Go to http://guides.rubyonrails.org/security.html#unsafe-query-generation "\
-
"for more information."\
-
-
debug(message)
-
end
-
-
%w(write_fragment read_fragment exist_fragment?
-
1
expire_fragment expire_page write_page).each do |method|
-
6
class_eval <<-METHOD, __FILE__, __LINE__ + 1
-
def #{method}(event)
-
return unless logger.info?
-
key_or_path = event.payload[:key] || event.payload[:path]
-
human_name = #{method.to_s.humanize.inspect}
-
info("\#{human_name} \#{key_or_path} (\#{event.duration.round(1)}ms)")
-
end
-
METHOD
-
end
-
-
1
def logger
-
ActionController::Base.logger
-
end
-
end
-
end
-
-
1
ActionController::LogSubscriber.attach_to :action_controller
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'action_dispatch/middleware/stack'
-
-
1
module ActionController
-
# Extend ActionDispatch middleware stack to make it aware of options
-
# allowing the following syntax in controllers:
-
#
-
# class PostsController < ApplicationController
-
# use AuthenticationMiddleware, except: [:index, :show]
-
# end
-
#
-
1
class MiddlewareStack < ActionDispatch::MiddlewareStack #:nodoc:
-
1
class Middleware < ActionDispatch::MiddlewareStack::Middleware #:nodoc:
-
1
def initialize(klass, *args, &block)
-
options = args.extract_options!
-
@only = Array(options.delete(:only)).map(&:to_s)
-
@except = Array(options.delete(:except)).map(&:to_s)
-
args << options unless options.empty?
-
super
-
end
-
-
1
def valid?(action)
-
if @only.present?
-
@only.include?(action)
-
elsif @except.present?
-
!@except.include?(action)
-
else
-
true
-
end
-
end
-
end
-
-
1
def build(action, app=nil, &block)
-
app ||= block
-
action = action.to_s
-
raise "MiddlewareStack#build requires an app" unless app
-
-
middlewares.reverse.inject(app) do |a, middleware|
-
middleware.valid?(action) ? middleware.build(a) : a
-
end
-
end
-
end
-
-
# <tt>ActionController::Metal</tt> is the simplest possible controller, providing a
-
# valid Rack interface without the additional niceties provided by
-
# <tt>ActionController::Base</tt>.
-
#
-
# A sample metal controller might look like this:
-
#
-
# class HelloController < ActionController::Metal
-
# def index
-
# self.response_body = "Hello World!"
-
# end
-
# end
-
#
-
# And then to route requests to your metal controller, you would add
-
# something like this to <tt>config/routes.rb</tt>:
-
#
-
# get 'hello', to: HelloController.action(:index)
-
#
-
# The +action+ method returns a valid Rack application for the \Rails
-
# router to dispatch to.
-
#
-
# == Rendering Helpers
-
#
-
# <tt>ActionController::Metal</tt> by default provides no utilities for rendering
-
# views, partials, or other responses aside from explicitly calling of
-
# <tt>response_body=</tt>, <tt>content_type=</tt>, and <tt>status=</tt>. To
-
# add the render helpers you're used to having in a normal controller, you
-
# can do the following:
-
#
-
# class HelloController < ActionController::Metal
-
# include ActionController::Rendering
-
# append_view_path "#{Rails.root}/app/views"
-
#
-
# def index
-
# render "hello/index"
-
# end
-
# end
-
#
-
# == Redirection Helpers
-
#
-
# To add redirection helpers to your metal controller, do the following:
-
#
-
# class HelloController < ActionController::Metal
-
# include ActionController::Redirecting
-
# include Rails.application.routes.url_helpers
-
#
-
# def index
-
# redirect_to root_url
-
# end
-
# end
-
#
-
# == Other Helpers
-
#
-
# You can refer to the modules included in <tt>ActionController::Base</tt> to see
-
# other features you can bring into your metal controller.
-
#
-
1
class Metal < AbstractController::Base
-
1
abstract!
-
-
1
attr_internal_writer :env
-
-
1
def env
-
@_env ||= {}
-
end
-
-
# Returns the last part of the controller's name, underscored, without the ending
-
# <tt>Controller</tt>. For instance, PostsController returns <tt>posts</tt>.
-
# Namespaces are left out, so Admin::PostsController returns <tt>posts</tt> as well.
-
#
-
# ==== Returns
-
# * <tt>string</tt>
-
1
def self.controller_name
-
@controller_name ||= name.demodulize.sub(/Controller$/, '').underscore
-
end
-
-
# Delegates to the class' <tt>controller_name</tt>
-
1
def controller_name
-
self.class.controller_name
-
end
-
-
# The details below can be overridden to support a specific
-
# Request and Response object. The default ActionController::Base
-
# implementation includes RackDelegation, which makes a request
-
# and response object available. You might wish to control the
-
# environment and response manually for performance reasons.
-
-
1
attr_internal :headers, :response, :request
-
1
delegate :session, :to => "@_request"
-
-
1
def initialize
-
@_headers = {"Content-Type" => "text/html"}
-
@_status = 200
-
@_request = nil
-
@_response = nil
-
@_routes = nil
-
super
-
end
-
-
1
def params
-
@_params ||= request.parameters
-
end
-
-
1
def params=(val)
-
@_params = val
-
end
-
-
# Basic implementations for content_type=, location=, and headers are
-
# provided to reduce the dependency on the RackDelegation module
-
# in Renderer and Redirector.
-
-
1
def content_type=(type)
-
headers["Content-Type"] = type.to_s
-
end
-
-
1
def content_type
-
headers["Content-Type"]
-
end
-
-
1
def location
-
headers["Location"]
-
end
-
-
1
def location=(url)
-
headers["Location"] = url
-
end
-
-
# basic url_for that can be overridden for more robust functionality
-
1
def url_for(string)
-
string
-
end
-
-
1
def status
-
@_status
-
end
-
-
1
def status=(status)
-
@_status = Rack::Utils.status_code(status)
-
end
-
-
1
def response_body=(body)
-
body = [body] unless body.nil? || body.respond_to?(:each)
-
super
-
end
-
-
1
def performed?
-
response_body || (response && response.committed?)
-
end
-
-
1
def dispatch(name, request) #:nodoc:
-
@_request = request
-
@_env = request.env
-
@_env['action_controller.instance'] = self
-
process(name)
-
to_a
-
end
-
-
1
def to_a #:nodoc:
-
response ? response.to_a : [status, headers, response_body]
-
end
-
-
1
class_attribute :middleware_stack
-
1
self.middleware_stack = ActionController::MiddlewareStack.new
-
-
1
def self.inherited(base) # :nodoc:
-
3
base.middleware_stack = middleware_stack.dup
-
3
super
-
end
-
-
# Pushes the given Rack middleware and its arguments to the bottom of the
-
# middleware stack.
-
1
def self.use(*args, &block)
-
middleware_stack.use(*args, &block)
-
end
-
-
# Alias for +middleware_stack+.
-
1
def self.middleware
-
middleware_stack
-
end
-
-
# Makes the controller a Rack endpoint that runs the action in the given
-
# +env+'s +action_dispatch.request.path_parameters+ key.
-
1
def self.call(env)
-
action(env['action_dispatch.request.path_parameters'][:action]).call(env)
-
end
-
-
# Returns a Rack endpoint for the given action name.
-
1
def self.action(name, klass = ActionDispatch::Request)
-
middleware_stack.build(name.to_s) do |env|
-
new.dispatch(name, klass.new(env))
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/keys'
-
-
1
module ActionController
-
1
module ConditionalGet
-
1
extend ActiveSupport::Concern
-
-
1
include RackDelegation
-
1
include Head
-
-
1
included do
-
1
class_attribute :etaggers
-
1
self.etaggers = []
-
end
-
-
1
module ClassMethods
-
# Allows you to consider additional controller-wide information when generating an etag.
-
# For example, if you serve pages tailored depending on who's logged in at the moment, you
-
# may want to add the current user id to be part of the etag to prevent authorized displaying
-
# of cached pages.
-
#
-
# class InvoicesController < ApplicationController
-
# etag { current_user.try :id }
-
#
-
# def show
-
# # Etag will differ even for the same invoice when it's viewed by a different current_user
-
# @invoice = Invoice.find(params[:id])
-
# fresh_when(@invoice)
-
# end
-
# end
-
1
def etag(&etagger)
-
self.etaggers += [etagger]
-
end
-
end
-
-
# Sets the etag, +last_modified+, or both on the response and renders a
-
# <tt>304 Not Modified</tt> response if the request is already fresh.
-
#
-
# === Parameters:
-
#
-
# * <tt>:etag</tt>.
-
# * <tt>:last_modified</tt>.
-
# * <tt>:public</tt> By default the Cache-Control header is private, set this to
-
# +true+ if you want your application to be cachable by other devices (proxy caches).
-
#
-
# === Example:
-
#
-
# def show
-
# @article = Article.find(params[:id])
-
# fresh_when(etag: @article, last_modified: @article.created_at, public: true)
-
# end
-
#
-
# This will render the show template if the request isn't sending a matching etag or
-
# If-Modified-Since header and just a <tt>304 Not Modified</tt> response if there's a match.
-
#
-
# You can also just pass a record where +last_modified+ will be set by calling
-
# +updated_at+ and the etag by passing the object itself.
-
#
-
# def show
-
# @article = Article.find(params[:id])
-
# fresh_when(@article)
-
# end
-
#
-
# When passing a record, you can still set whether the public header:
-
#
-
# def show
-
# @article = Article.find(params[:id])
-
# fresh_when(@article, public: true)
-
# end
-
1
def fresh_when(record_or_options, additional_options = {})
-
if record_or_options.is_a? Hash
-
options = record_or_options
-
options.assert_valid_keys(:etag, :last_modified, :public)
-
else
-
record = record_or_options
-
options = { etag: record, last_modified: record.try(:updated_at) }.merge!(additional_options)
-
end
-
-
response.etag = combine_etags(options[:etag]) if options[:etag]
-
response.last_modified = options[:last_modified] if options[:last_modified]
-
response.cache_control[:public] = true if options[:public]
-
-
head :not_modified if request.fresh?(response)
-
end
-
-
# Sets the +etag+ and/or +last_modified+ on the response and checks it against
-
# the client request. If the request doesn't match the options provided, the
-
# request is considered stale and should be generated from scratch. Otherwise,
-
# it's fresh and we don't need to generate anything and a reply of <tt>304 Not Modified</tt> is sent.
-
#
-
# === Parameters:
-
#
-
# * <tt>:etag</tt>.
-
# * <tt>:last_modified</tt>.
-
# * <tt>:public</tt> By default the Cache-Control header is private, set this to
-
# +true+ if you want your application to be cachable by other devices (proxy caches).
-
#
-
# === Example:
-
#
-
# def show
-
# @article = Article.find(params[:id])
-
#
-
# if stale?(etag: @article, last_modified: @article.created_at)
-
# @statistics = @article.really_expensive_call
-
# respond_to do |format|
-
# # all the supported formats
-
# end
-
# end
-
# end
-
#
-
# You can also just pass a record where +last_modified+ will be set by calling
-
# updated_at and the etag by passing the object itself.
-
#
-
# def show
-
# @article = Article.find(params[:id])
-
#
-
# if stale?(@article)
-
# @statistics = @article.really_expensive_call
-
# respond_to do |format|
-
# # all the supported formats
-
# end
-
# end
-
# end
-
#
-
# When passing a record, you can still set whether the public header:
-
#
-
# def show
-
# @article = Article.find(params[:id])
-
#
-
# if stale?(@article, public: true)
-
# @statistics = @article.really_expensive_call
-
# respond_to do |format|
-
# # all the supported formats
-
# end
-
# end
-
# end
-
1
def stale?(record_or_options, additional_options = {})
-
fresh_when(record_or_options, additional_options)
-
!request.fresh?(response)
-
end
-
-
# Sets a HTTP 1.1 Cache-Control header. Defaults to issuing a +private+
-
# instruction, so that intermediate caches must not cache the response.
-
#
-
# expires_in 20.minutes
-
# expires_in 3.hours, public: true
-
# expires_in 3.hours, public: true, must_revalidate: true
-
#
-
# This method will overwrite an existing Cache-Control header.
-
# See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html for more possibilities.
-
#
-
# The method will also ensure a HTTP Date header for client compatibility.
-
1
def expires_in(seconds, options = {})
-
response.cache_control.merge!(
-
:max_age => seconds,
-
:public => options.delete(:public),
-
:must_revalidate => options.delete(:must_revalidate)
-
)
-
options.delete(:private)
-
-
response.cache_control[:extras] = options.map {|k,v| "#{k}=#{v}"}
-
response.date = Time.now unless response.date?
-
end
-
-
# Sets a HTTP 1.1 Cache-Control header of <tt>no-cache</tt> so no caching should
-
# occur by the browser or intermediate caches (like caching proxy servers).
-
1
def expires_now
-
response.cache_control.replace(:no_cache => true)
-
end
-
-
1
private
-
1
def combine_etags(etag)
-
[ etag, *etaggers.map { |etagger| instance_exec(&etagger) }.compact ]
-
end
-
end
-
end
-
1
module ActionController #:nodoc:
-
1
module Cookies
-
1
extend ActiveSupport::Concern
-
-
1
include RackDelegation
-
-
1
included do
-
1
helper_method :cookies
-
end
-
-
1
private
-
1
def cookies
-
request.cookie_jar
-
end
-
end
-
end
-
1
require 'action_controller/metal/exceptions'
-
-
1
module ActionController #:nodoc:
-
# Methods for sending arbitrary data and for streaming files to the browser,
-
# instead of rendering.
-
1
module DataStreaming
-
1
extend ActiveSupport::Concern
-
-
1
include ActionController::Rendering
-
-
1
DEFAULT_SEND_FILE_TYPE = 'application/octet-stream'.freeze #:nodoc:
-
1
DEFAULT_SEND_FILE_DISPOSITION = 'attachment'.freeze #:nodoc:
-
-
1
protected
-
# Sends the file. This uses a server-appropriate method (such as X-Sendfile)
-
# via the Rack::Sendfile middleware. The header to use is set via
-
# +config.action_dispatch.x_sendfile_header+.
-
# Your server can also configure this for you by setting the X-Sendfile-Type header.
-
#
-
# Be careful to sanitize the path parameter if it is coming from a web
-
# page. <tt>send_file(params[:path])</tt> allows a malicious user to
-
# download any file on your server.
-
#
-
# Options:
-
# * <tt>:filename</tt> - suggests a filename for the browser to use.
-
# Defaults to <tt>File.basename(path)</tt>.
-
# * <tt>:type</tt> - specifies an HTTP content type.
-
# You can specify either a string or a symbol for a registered type register with
-
# <tt>Mime::Type.register</tt>, for example :json
-
# If omitted, type will be guessed from the file extension specified in <tt>:filename</tt>.
-
# If no content type is registered for the extension, default type 'application/octet-stream' will be used.
-
# * <tt>:disposition</tt> - specifies whether the file will be shown inline or downloaded.
-
# Valid values are 'inline' and 'attachment' (default).
-
# * <tt>:status</tt> - specifies the status code to send with the response. Defaults to 200.
-
# * <tt>:url_based_filename</tt> - set to +true+ if you want the browser guess the filename from
-
# the URL, which is necessary for i18n filenames on certain browsers
-
# (setting <tt>:filename</tt> overrides this option).
-
#
-
# The default Content-Type and Content-Disposition headers are
-
# set to download arbitrary binary files in as many browsers as
-
# possible. IE versions 4, 5, 5.5, and 6 are all known to have
-
# a variety of quirks (especially when downloading over SSL).
-
#
-
# Simple download:
-
#
-
# send_file '/path/to.zip'
-
#
-
# Show a JPEG in the browser:
-
#
-
# send_file '/path/to.jpeg', type: 'image/jpeg', disposition: 'inline'
-
#
-
# Show a 404 page in the browser:
-
#
-
# send_file '/path/to/404.html', type: 'text/html; charset=utf-8', status: 404
-
#
-
# Read about the other Content-* HTTP headers if you'd like to
-
# provide the user with more information (such as Content-Description) in
-
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11.
-
#
-
# Also be aware that the document may be cached by proxies and browsers.
-
# The Pragma and Cache-Control headers declare how the file may be cached
-
# by intermediaries. They default to require clients to validate with
-
# the server before releasing cached responses. See
-
# http://www.mnot.net/cache_docs/ for an overview of web caching and
-
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
-
# for the Cache-Control header spec.
-
1
def send_file(path, options = {}) #:doc:
-
raise MissingFile, "Cannot read file #{path}" unless File.file?(path) and File.readable?(path)
-
-
options[:filename] ||= File.basename(path) unless options[:url_based_filename]
-
send_file_headers! options
-
-
self.status = options[:status] || 200
-
self.content_type = options[:content_type] if options.key?(:content_type)
-
self.response_body = FileBody.new(path)
-
end
-
-
# Avoid having to pass an open file handle as the response body.
-
# Rack::Sendfile will usually intercept the response and uses
-
# the path directly, so there is no reason to open the file.
-
1
class FileBody #:nodoc:
-
1
attr_reader :to_path
-
-
1
def initialize(path)
-
@to_path = path
-
end
-
-
# Stream the file's contents if Rack::Sendfile isn't present.
-
1
def each
-
File.open(to_path, 'rb') do |file|
-
while chunk = file.read(16384)
-
yield chunk
-
end
-
end
-
end
-
end
-
-
# Sends the given binary data to the browser. This method is similar to
-
# <tt>render plain: data</tt>, but also allows you to specify whether
-
# the browser should display the response as a file attachment (i.e. in a
-
# download dialog) or as inline data. You may also set the content type,
-
# the apparent file name, and other things.
-
#
-
# Options:
-
# * <tt>:filename</tt> - suggests a filename for the browser to use.
-
# * <tt>:type</tt> - specifies an HTTP content type. Defaults to 'application/octet-stream'. You can specify
-
# either a string or a symbol for a registered type register with <tt>Mime::Type.register</tt>, for example :json
-
# If omitted, type will be guessed from the file extension specified in <tt>:filename</tt>.
-
# If no content type is registered for the extension, default type 'application/octet-stream' will be used.
-
# * <tt>:disposition</tt> - specifies whether the file will be shown inline or downloaded.
-
# Valid values are 'inline' and 'attachment' (default).
-
# * <tt>:status</tt> - specifies the status code to send with the response. Defaults to 200.
-
#
-
# Generic data download:
-
#
-
# send_data buffer
-
#
-
# Download a dynamically-generated tarball:
-
#
-
# send_data generate_tgz('dir'), filename: 'dir.tgz'
-
#
-
# Display an image Active Record in the browser:
-
#
-
# send_data image.data, type: image.content_type, disposition: 'inline'
-
#
-
# See +send_file+ for more information on HTTP Content-* headers and caching.
-
1
def send_data(data, options = {}) #:doc:
-
send_file_headers! options
-
render options.slice(:status, :content_type).merge(:text => data)
-
end
-
-
1
private
-
1
def send_file_headers!(options)
-
type_provided = options.has_key?(:type)
-
-
content_type = options.fetch(:type, DEFAULT_SEND_FILE_TYPE)
-
raise ArgumentError, ":type option required" if content_type.nil?
-
-
if content_type.is_a?(Symbol)
-
extension = Mime[content_type]
-
raise ArgumentError, "Unknown MIME type #{options[:type]}" unless extension
-
self.content_type = extension
-
else
-
if !type_provided && options[:filename]
-
# If type wasn't provided, try guessing from file extension.
-
content_type = Mime::Type.lookup_by_extension(File.extname(options[:filename]).downcase.delete('.')) || content_type
-
end
-
self.content_type = content_type
-
end
-
-
disposition = options.fetch(:disposition, DEFAULT_SEND_FILE_DISPOSITION)
-
unless disposition.nil?
-
disposition = disposition.to_s
-
disposition += %(; filename="#{options[:filename]}") if options[:filename]
-
headers['Content-Disposition'] = disposition
-
end
-
-
headers['Content-Transfer-Encoding'] = 'binary'
-
-
response.sending_file = true
-
-
# Fix a problem with IE 6.0 on opening downloaded files:
-
# If Cache-Control: no-cache is set (which Rails does by default),
-
# IE removes the file it just downloaded from its cache immediately
-
# after it displays the "open/save" dialog, which means that if you
-
# hit "open" the file isn't there anymore when the application that
-
# is called for handling the download is run, so let's workaround that
-
response.cache_control[:public] ||= false
-
end
-
end
-
end
-
1
module ActionController
-
1
class ActionControllerError < StandardError #:nodoc:
-
end
-
-
1
class BadRequest < ActionControllerError #:nodoc:
-
1
attr_reader :original_exception
-
-
1
def initialize(type = nil, e = nil)
-
return super() unless type && e
-
-
super("Invalid #{type} parameters: #{e.message}")
-
@original_exception = e
-
set_backtrace e.backtrace
-
end
-
end
-
-
1
class RenderError < ActionControllerError #:nodoc:
-
end
-
-
1
class RoutingError < ActionControllerError #:nodoc:
-
1
attr_reader :failures
-
1
def initialize(message, failures=[])
-
super(message)
-
@failures = failures
-
end
-
end
-
-
1
class ActionController::UrlGenerationError < RoutingError #:nodoc:
-
end
-
-
1
class MethodNotAllowed < ActionControllerError #:nodoc:
-
1
def initialize(*allowed_methods)
-
super("Only #{allowed_methods.to_sentence(:locale => :en)} requests are allowed.")
-
end
-
end
-
-
1
class NotImplemented < MethodNotAllowed #:nodoc:
-
end
-
-
1
class UnknownController < ActionControllerError #:nodoc:
-
end
-
-
1
class MissingFile < ActionControllerError #:nodoc:
-
end
-
-
1
class SessionOverflowError < ActionControllerError #:nodoc:
-
1
DEFAULT_MESSAGE = 'Your session data is larger than the data column in which it is to be stored. You must increase the size of your data column if you intend to store large data.'
-
-
1
def initialize(message = nil)
-
super(message || DEFAULT_MESSAGE)
-
end
-
end
-
-
1
class UnknownHttpMethod < ActionControllerError #:nodoc:
-
end
-
-
1
class UnknownFormat < ActionControllerError #:nodoc:
-
end
-
end
-
1
module ActionController #:nodoc:
-
1
module Flash
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
class_attribute :_flash_types, instance_accessor: false
-
1
self._flash_types = []
-
-
1
delegate :flash, to: :request
-
1
add_flash_types(:alert, :notice)
-
end
-
-
1
module ClassMethods
-
# Creates new flash types. You can pass as many types as you want to create
-
# flash types other than the default <tt>alert</tt> and <tt>notice</tt> in
-
# your controllers and views. For instance:
-
#
-
# # in application_controller.rb
-
# class ApplicationController < ActionController::Base
-
# add_flash_types :warning
-
# end
-
#
-
# # in your controller
-
# redirect_to user_path(@user), warning: "Incomplete profile"
-
#
-
# # in your view
-
# <%= warning %>
-
#
-
# This method will automatically define a new method for each of the given
-
# names, and it will be available in your views.
-
1
def add_flash_types(*types)
-
1
types.each do |type|
-
2
next if _flash_types.include?(type)
-
-
2
define_method(type) do
-
request.flash[type]
-
end
-
2
helper_method type
-
-
2
self._flash_types += [type]
-
end
-
end
-
end
-
-
1
protected
-
1
def redirect_to(options = {}, response_status_and_flash = {}) #:doc:
-
self.class._flash_types.each do |flash_type|
-
if type = response_status_and_flash.delete(flash_type)
-
flash[flash_type] = type
-
end
-
end
-
-
if other_flashes = response_status_and_flash.delete(:flash)
-
flash.update(other_flashes)
-
end
-
-
super(options, response_status_and_flash)
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/hash/slice'
-
-
1
module ActionController
-
# This module provides a method which will redirect browser to use HTTPS
-
# protocol. This will ensure that user's sensitive information will be
-
# transferred safely over the internet. You _should_ always force browser
-
# to use HTTPS when you're transferring sensitive information such as
-
# user authentication, account information, or credit card information.
-
#
-
# Note that if you are really concerned about your application security,
-
# you might consider using +config.force_ssl+ in your config file instead.
-
# That will ensure all the data transferred via HTTPS protocol and prevent
-
# user from getting session hijacked when accessing the site under unsecured
-
# HTTP protocol.
-
1
module ForceSSL
-
1
extend ActiveSupport::Concern
-
1
include AbstractController::Callbacks
-
-
1
ACTION_OPTIONS = [:only, :except, :if, :unless]
-
1
URL_OPTIONS = [:protocol, :host, :domain, :subdomain, :port, :path]
-
1
REDIRECT_OPTIONS = [:status, :flash, :alert, :notice]
-
-
1
module ClassMethods
-
# Force the request to this particular controller or specified actions to be
-
# under HTTPS protocol.
-
#
-
# If you need to disable this for any reason (e.g. development) then you can use
-
# an +:if+ or +:unless+ condition.
-
#
-
# class AccountsController < ApplicationController
-
# force_ssl if: :ssl_configured?
-
#
-
# def ssl_configured?
-
# !Rails.env.development?
-
# end
-
# end
-
#
-
# ==== URL Options
-
# You can pass any of the following options to affect the redirect url
-
# * <tt>host</tt> - Redirect to a different host name
-
# * <tt>subdomain</tt> - Redirect to a different subdomain
-
# * <tt>domain</tt> - Redirect to a different domain
-
# * <tt>port</tt> - Redirect to a non-standard port
-
# * <tt>path</tt> - Redirect to a different path
-
#
-
# ==== Redirect Options
-
# You can pass any of the following options to affect the redirect status and response
-
# * <tt>status</tt> - Redirect with a custom status (default is 301 Moved Permanently)
-
# * <tt>flash</tt> - Set a flash message when redirecting
-
# * <tt>alert</tt> - Set an alert message when redirecting
-
# * <tt>notice</tt> - Set a notice message when redirecting
-
#
-
# ==== Action Options
-
# You can pass any of the following options to affect the before_action callback
-
# * <tt>only</tt> - The callback should be run only for this action
-
# * <tt>except</tt> - The callback should be run for all actions except this action
-
# * <tt>if</tt> - A symbol naming an instance method or a proc; the callback
-
# will be called only when it returns a true value.
-
# * <tt>unless</tt> - A symbol naming an instance method or a proc; the callback
-
# will be called only when it returns a false value.
-
1
def force_ssl(options = {})
-
action_options = options.slice(*ACTION_OPTIONS)
-
redirect_options = options.except(*ACTION_OPTIONS)
-
before_action(action_options) do
-
force_ssl_redirect(redirect_options)
-
end
-
end
-
end
-
-
# Redirect the existing request to use the HTTPS protocol.
-
#
-
# ==== Parameters
-
# * <tt>host_or_options</tt> - Either a host name or any of the url & redirect options
-
# available to the <tt>force_ssl</tt> method.
-
1
def force_ssl_redirect(host_or_options = nil)
-
unless request.ssl?
-
options = {
-
:protocol => 'https://',
-
:host => request.host,
-
:path => request.fullpath,
-
:status => :moved_permanently
-
}
-
-
if host_or_options.is_a?(Hash)
-
options.merge!(host_or_options)
-
elsif host_or_options
-
options.merge!(:host => host_or_options)
-
end
-
-
secure_url = ActionDispatch::Http::URL.url_for(options.slice(*URL_OPTIONS))
-
flash.keep if respond_to?(:flash)
-
redirect_to secure_url, options.slice(*REDIRECT_OPTIONS)
-
end
-
end
-
end
-
end
-
1
module ActionController
-
1
module Head
-
# Returns a response that has no content (merely headers). The options
-
# argument is interpreted to be a hash of header names and values.
-
# This allows you to easily return a response that consists only of
-
# significant headers:
-
#
-
# head :created, location: person_path(@person)
-
#
-
# head :created, location: @person
-
#
-
# It can also be used to return exceptional conditions:
-
#
-
# return head(:method_not_allowed) unless request.post?
-
# return head(:bad_request) unless valid_request?
-
# render
-
1
def head(status, options = {})
-
options, status = status, nil if status.is_a?(Hash)
-
status ||= options.delete(:status) || :ok
-
location = options.delete(:location)
-
content_type = options.delete(:content_type)
-
-
options.each do |key, value|
-
headers[key.to_s.dasherize.split('-').each { |v| v[0] = v[0].chr.upcase }.join('-')] = value.to_s
-
end
-
-
self.status = status
-
self.location = url_for(location) if location
-
-
if include_content?(self.status)
-
self.content_type = content_type || (Mime[formats.first] if formats)
-
self.response.charset = false if self.response
-
self.response_body = " "
-
else
-
headers.delete('Content-Type')
-
headers.delete('Content-Length')
-
self.response_body = ""
-
end
-
end
-
-
1
private
-
# :nodoc:
-
1
def include_content?(status)
-
case status
-
when 100..199
-
false
-
when 204, 205, 304
-
false
-
else
-
true
-
end
-
end
-
end
-
end
-
1
module ActionController
-
# The \Rails framework provides a large number of helpers for working with assets, dates, forms,
-
# numbers and model objects, to name a few. These helpers are available to all templates
-
# by default.
-
#
-
# In addition to using the standard template helpers provided, creating custom helpers to
-
# extract complicated logic or reusable functionality is strongly encouraged. By default, each controller
-
# will include all helpers. These helpers are only accessible on the controller through <tt>.helpers</tt>
-
#
-
# In previous versions of \Rails the controller will include a helper whose
-
# name matches that of the controller, e.g., <tt>MyController</tt> will automatically
-
# include <tt>MyHelper</tt>. To return old behavior set +config.action_controller.include_all_helpers+ to +false+.
-
#
-
# Additional helpers can be specified using the +helper+ class method in ActionController::Base or any
-
# controller which inherits from it.
-
#
-
# The +to_s+ method from the \Time class can be wrapped in a helper method to display a custom message if
-
# a \Time object is blank:
-
#
-
# module FormattedTimeHelper
-
# def format_time(time, format=:long, blank_message=" ")
-
# time.blank? ? blank_message : time.to_s(format)
-
# end
-
# end
-
#
-
# FormattedTimeHelper can now be included in a controller, using the +helper+ class method:
-
#
-
# class EventsController < ActionController::Base
-
# helper FormattedTimeHelper
-
# def index
-
# @events = Event.all
-
# end
-
# end
-
#
-
# Then, in any view rendered by <tt>EventController</tt>, the <tt>format_time</tt> method can be called:
-
#
-
# <% @events.each do |event| -%>
-
# <p>
-
# <%= format_time(event.time, :short, "N/A") %> | <%= event.name %>
-
# </p>
-
# <% end -%>
-
#
-
# Finally, assuming we have two event instances, one which has a time and one which does not,
-
# the output might look like this:
-
#
-
# 23 Aug 11:30 | Carolina Railhawks Soccer Match
-
# N/A | Carolina Railhaws Training Workshop
-
#
-
1
module Helpers
-
1
extend ActiveSupport::Concern
-
-
2
class << self; attr_accessor :helpers_path; end
-
1
include AbstractController::Helpers
-
-
1
included do
-
1
class_attribute :helpers_path, :include_all_helpers
-
1
self.helpers_path ||= []
-
1
self.include_all_helpers = true
-
end
-
-
1
module ClassMethods
-
# Declares helper accessors for controller attributes. For example, the
-
# following adds new +name+ and <tt>name=</tt> instance methods to a
-
# controller and makes them available to the view:
-
# attr_accessor :name
-
# helper_attr :name
-
#
-
# ==== Parameters
-
# * <tt>attrs</tt> - Names of attributes to be converted into helpers.
-
1
def helper_attr(*attrs)
-
attrs.flatten.each { |attr| helper_method(attr, "#{attr}=") }
-
end
-
-
# Provides a proxy to access helpers methods from outside the view.
-
1
def helpers
-
@helper_proxy ||= begin
-
proxy = ActionView::Base.new
-
proxy.config = config.inheritable_copy
-
proxy.extend(_helpers)
-
end
-
end
-
-
# Overwrite modules_for_helpers to accept :all as argument, which loads
-
# all helpers in helpers_path.
-
#
-
# ==== Parameters
-
# * <tt>args</tt> - A list of helpers
-
#
-
# ==== Returns
-
# * <tt>array</tt> - A normalized list of modules for the list of helpers provided.
-
1
def modules_for_helpers(args)
-
2
args += all_application_helpers if args.delete(:all)
-
2
super(args)
-
end
-
-
1
def all_helpers_from_path(path)
-
1
helpers = Array(path).flat_map do |_path|
-
3
extract = /^#{Regexp.quote(_path.to_s)}\/?(.*)_helper.rb$/
-
18
names = Dir["#{_path}/**/*_helper.rb"].map { |file| file.sub(extract, '\1') }
-
3
names.sort!
-
end
-
1
helpers.uniq!
-
1
helpers
-
end
-
-
1
private
-
# Extract helper names from files in <tt>app/helpers/**/*_helper.rb</tt>
-
1
def all_application_helpers
-
1
all_helpers_from_path(helpers_path)
-
end
-
end
-
end
-
end
-
-
1
module ActionController
-
# Adds the ability to prevent public methods on a controller to be called as actions.
-
1
module HideActions
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
class_attribute :hidden_actions
-
1
self.hidden_actions = Set.new.freeze
-
end
-
-
1
private
-
-
# Overrides AbstractController::Base#action_method? to return false if the
-
# action name is in the list of hidden actions.
-
1
def method_for_action(action_name)
-
self.class.visible_action?(action_name) && super
-
end
-
-
1
module ClassMethods
-
# Sets all of the actions passed in as hidden actions.
-
#
-
# ==== Parameters
-
# * <tt>args</tt> - A list of actions
-
1
def hide_action(*args)
-
self.hidden_actions = hidden_actions.dup.merge(args.map(&:to_s)).freeze
-
end
-
-
1
def visible_action?(action_name)
-
not hidden_actions.include?(action_name)
-
end
-
-
# Overrides AbstractController::Base#action_methods to remove any methods
-
# that are listed as hidden methods.
-
1
def action_methods
-
@action_methods ||= Set.new(super.reject { |name| hidden_actions.include?(name) }).freeze
-
end
-
end
-
end
-
end
-
1
require 'base64'
-
-
1
module ActionController
-
# Makes it dead easy to do HTTP Basic, Digest and Token authentication.
-
1
module HttpAuthentication
-
# Makes it dead easy to do HTTP \Basic authentication.
-
#
-
# === Simple \Basic example
-
#
-
# class PostsController < ApplicationController
-
# http_basic_authenticate_with name: "dhh", password: "secret", except: :index
-
#
-
# def index
-
# render plain: "Everyone can see me!"
-
# end
-
#
-
# def edit
-
# render plain: "I'm only accessible if you know the password"
-
# end
-
# end
-
#
-
# === Advanced \Basic example
-
#
-
# Here is a more advanced \Basic example where only Atom feeds and the XML API is protected by HTTP authentication,
-
# the regular HTML interface is protected by a session approach:
-
#
-
# class ApplicationController < ActionController::Base
-
# before_action :set_account, :authenticate
-
#
-
# protected
-
# def set_account
-
# @account = Account.find_by(url_name: request.subdomains.first)
-
# end
-
#
-
# def authenticate
-
# case request.format
-
# when Mime::XML, Mime::ATOM
-
# if user = authenticate_with_http_basic { |u, p| @account.users.authenticate(u, p) }
-
# @current_user = user
-
# else
-
# request_http_basic_authentication
-
# end
-
# else
-
# if session_authenticated?
-
# @current_user = @account.users.find(session[:authenticated][:user_id])
-
# else
-
# redirect_to(login_url) and return false
-
# end
-
# end
-
# end
-
# end
-
#
-
# In your integration tests, you can do something like this:
-
#
-
# def test_access_granted_from_xml
-
# get(
-
# "/notes/1.xml", nil,
-
# 'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Basic.encode_credentials(users(:dhh).name, users(:dhh).password)
-
# )
-
#
-
# assert_equal 200, status
-
# end
-
1
module Basic
-
1
extend self
-
-
1
module ControllerMethods
-
1
extend ActiveSupport::Concern
-
-
1
module ClassMethods
-
1
def http_basic_authenticate_with(options = {})
-
before_action(options.except(:name, :password, :realm)) do
-
authenticate_or_request_with_http_basic(options[:realm] || "Application") do |name, password|
-
name == options[:name] && password == options[:password]
-
end
-
end
-
end
-
end
-
-
1
def authenticate_or_request_with_http_basic(realm = "Application", &login_procedure)
-
authenticate_with_http_basic(&login_procedure) || request_http_basic_authentication(realm)
-
end
-
-
1
def authenticate_with_http_basic(&login_procedure)
-
HttpAuthentication::Basic.authenticate(request, &login_procedure)
-
end
-
-
1
def request_http_basic_authentication(realm = "Application")
-
HttpAuthentication::Basic.authentication_request(self, realm)
-
end
-
end
-
-
1
def authenticate(request, &login_procedure)
-
unless request.authorization.blank?
-
login_procedure.call(*user_name_and_password(request))
-
end
-
end
-
-
1
def user_name_and_password(request)
-
decode_credentials(request).split(/:/, 2)
-
end
-
-
1
def decode_credentials(request)
-
::Base64.decode64(request.authorization.split(' ', 2).last || '')
-
end
-
-
1
def encode_credentials(user_name, password)
-
"Basic #{::Base64.strict_encode64("#{user_name}:#{password}")}"
-
end
-
-
1
def authentication_request(controller, realm)
-
controller.headers["WWW-Authenticate"] = %(Basic realm="#{realm.gsub(/"/, "")}")
-
controller.response_body = "HTTP Basic: Access denied.\n"
-
controller.status = 401
-
end
-
end
-
-
# Makes it dead easy to do HTTP \Digest authentication.
-
#
-
# === Simple \Digest example
-
#
-
# require 'digest/md5'
-
# class PostsController < ApplicationController
-
# REALM = "SuperSecret"
-
# USERS = {"dhh" => "secret", #plain text password
-
# "dap" => Digest::MD5.hexdigest(["dap",REALM,"secret"].join(":"))} #ha1 digest password
-
#
-
# before_action :authenticate, except: [:index]
-
#
-
# def index
-
# render plain: "Everyone can see me!"
-
# end
-
#
-
# def edit
-
# render plain: "I'm only accessible if you know the password"
-
# end
-
#
-
# private
-
# def authenticate
-
# authenticate_or_request_with_http_digest(REALM) do |username|
-
# USERS[username]
-
# end
-
# end
-
# end
-
#
-
# === Notes
-
#
-
# The +authenticate_or_request_with_http_digest+ block must return the user's password
-
# or the ha1 digest hash so the framework can appropriately hash to check the user's
-
# credentials. Returning +nil+ will cause authentication to fail.
-
#
-
# Storing the ha1 hash: MD5(username:realm:password), is better than storing a plain password. If
-
# the password file or database is compromised, the attacker would be able to use the ha1 hash to
-
# authenticate as the user at this +realm+, but would not have the user's password to try using at
-
# other sites.
-
#
-
# In rare instances, web servers or front proxies strip authorization headers before
-
# they reach your application. You can debug this situation by logging all environment
-
# variables, and check for HTTP_AUTHORIZATION, amongst others.
-
1
module Digest
-
1
extend self
-
-
1
module ControllerMethods
-
1
def authenticate_or_request_with_http_digest(realm = "Application", &password_procedure)
-
authenticate_with_http_digest(realm, &password_procedure) || request_http_digest_authentication(realm)
-
end
-
-
# Authenticate with HTTP Digest, returns true or false
-
1
def authenticate_with_http_digest(realm = "Application", &password_procedure)
-
HttpAuthentication::Digest.authenticate(request, realm, &password_procedure)
-
end
-
-
# Render output including the HTTP Digest authentication header
-
1
def request_http_digest_authentication(realm = "Application", message = nil)
-
HttpAuthentication::Digest.authentication_request(self, realm, message)
-
end
-
end
-
-
# Returns false on a valid response, true otherwise
-
1
def authenticate(request, realm, &password_procedure)
-
request.authorization && validate_digest_response(request, realm, &password_procedure)
-
end
-
-
# Returns false unless the request credentials response value matches the expected value.
-
# First try the password as a ha1 digest password. If this fails, then try it as a plain
-
# text password.
-
1
def validate_digest_response(request, realm, &password_procedure)
-
secret_key = secret_token(request)
-
credentials = decode_credentials_header(request)
-
valid_nonce = validate_nonce(secret_key, request, credentials[:nonce])
-
-
if valid_nonce && realm == credentials[:realm] && opaque(secret_key) == credentials[:opaque]
-
password = password_procedure.call(credentials[:username])
-
return false unless password
-
-
method = request.env['rack.methodoverride.original_method'] || request.env['REQUEST_METHOD']
-
uri = credentials[:uri]
-
-
[true, false].any? do |trailing_question_mark|
-
[true, false].any? do |password_is_ha1|
-
_uri = trailing_question_mark ? uri + "?" : uri
-
expected = expected_response(method, _uri, credentials, password, password_is_ha1)
-
expected == credentials[:response]
-
end
-
end
-
end
-
end
-
-
# Returns the expected response for a request of +http_method+ to +uri+ with the decoded +credentials+ and the expected +password+
-
# Optional parameter +password_is_ha1+ is set to +true+ by default, since best practice is to store ha1 digest instead
-
# of a plain-text password.
-
1
def expected_response(http_method, uri, credentials, password, password_is_ha1=true)
-
ha1 = password_is_ha1 ? password : ha1(credentials, password)
-
ha2 = ::Digest::MD5.hexdigest([http_method.to_s.upcase, uri].join(':'))
-
::Digest::MD5.hexdigest([ha1, credentials[:nonce], credentials[:nc], credentials[:cnonce], credentials[:qop], ha2].join(':'))
-
end
-
-
1
def ha1(credentials, password)
-
::Digest::MD5.hexdigest([credentials[:username], credentials[:realm], password].join(':'))
-
end
-
-
1
def encode_credentials(http_method, credentials, password, password_is_ha1)
-
credentials[:response] = expected_response(http_method, credentials[:uri], credentials, password, password_is_ha1)
-
"Digest " + credentials.sort_by {|x| x[0].to_s }.map {|v| "#{v[0]}='#{v[1]}'" }.join(', ')
-
end
-
-
1
def decode_credentials_header(request)
-
decode_credentials(request.authorization)
-
end
-
-
1
def decode_credentials(header)
-
ActiveSupport::HashWithIndifferentAccess[header.to_s.gsub(/^Digest\s+/, '').split(',').map do |pair|
-
key, value = pair.split('=', 2)
-
[key.strip, value.to_s.gsub(/^"|"$/,'').delete('\'')]
-
end]
-
end
-
-
1
def authentication_header(controller, realm)
-
secret_key = secret_token(controller.request)
-
nonce = self.nonce(secret_key)
-
opaque = opaque(secret_key)
-
controller.headers["WWW-Authenticate"] = %(Digest realm="#{realm}", qop="auth", algorithm=MD5, nonce="#{nonce}", opaque="#{opaque}")
-
end
-
-
1
def authentication_request(controller, realm, message = nil)
-
message ||= "HTTP Digest: Access denied.\n"
-
authentication_header(controller, realm)
-
controller.response_body = message
-
controller.status = 401
-
end
-
-
1
def secret_token(request)
-
key_generator = request.env["action_dispatch.key_generator"]
-
http_auth_salt = request.env["action_dispatch.http_auth_salt"]
-
key_generator.generate_key(http_auth_salt)
-
end
-
-
# Uses an MD5 digest based on time to generate a value to be used only once.
-
#
-
# A server-specified data string which should be uniquely generated each time a 401 response is made.
-
# It is recommended that this string be base64 or hexadecimal data.
-
# Specifically, since the string is passed in the header lines as a quoted string, the double-quote character is not allowed.
-
#
-
# The contents of the nonce are implementation dependent.
-
# The quality of the implementation depends on a good choice.
-
# A nonce might, for example, be constructed as the base 64 encoding of
-
#
-
# time-stamp H(time-stamp ":" ETag ":" private-key)
-
#
-
# where time-stamp is a server-generated time or other non-repeating value,
-
# ETag is the value of the HTTP ETag header associated with the requested entity,
-
# and private-key is data known only to the server.
-
# With a nonce of this form a server would recalculate the hash portion after receiving the client authentication header and
-
# reject the request if it did not match the nonce from that header or
-
# if the time-stamp value is not recent enough. In this way the server can limit the time of the nonce's validity.
-
# The inclusion of the ETag prevents a replay request for an updated version of the resource.
-
# (Note: including the IP address of the client in the nonce would appear to offer the server the ability
-
# to limit the reuse of the nonce to the same client that originally got it.
-
# However, that would break proxy farms, where requests from a single user often go through different proxies in the farm.
-
# Also, IP address spoofing is not that hard.)
-
#
-
# An implementation might choose not to accept a previously used nonce or a previously used digest, in order to
-
# protect against a replay attack. Or, an implementation might choose to use one-time nonces or digests for
-
# POST, PUT, or PATCH requests and a time-stamp for GET requests. For more details on the issues involved see Section 4
-
# of this document.
-
#
-
# The nonce is opaque to the client. Composed of Time, and hash of Time with secret
-
# key from the Rails session secret generated upon creation of project. Ensures
-
# the time cannot be modified by client.
-
1
def nonce(secret_key, time = Time.now)
-
t = time.to_i
-
hashed = [t, secret_key]
-
digest = ::Digest::MD5.hexdigest(hashed.join(":"))
-
::Base64.strict_encode64("#{t}:#{digest}")
-
end
-
-
# Might want a shorter timeout depending on whether the request
-
# is a PATCH, PUT, or POST, and if client is browser or web service.
-
# Can be much shorter if the Stale directive is implemented. This would
-
# allow a user to use new nonce without prompting user again for their
-
# username and password.
-
1
def validate_nonce(secret_key, request, value, seconds_to_timeout=5*60)
-
return false if value.nil?
-
t = ::Base64.decode64(value).split(":").first.to_i
-
nonce(secret_key, t) == value && (t - Time.now.to_i).abs <= seconds_to_timeout
-
end
-
-
# Opaque based on random generation - but changing each request?
-
1
def opaque(secret_key)
-
::Digest::MD5.hexdigest(secret_key)
-
end
-
-
end
-
-
# Makes it dead easy to do HTTP Token authentication.
-
#
-
# Simple Token example:
-
#
-
# class PostsController < ApplicationController
-
# TOKEN = "secret"
-
#
-
# before_action :authenticate, except: [ :index ]
-
#
-
# def index
-
# render plain: "Everyone can see me!"
-
# end
-
#
-
# def edit
-
# render plain: "I'm only accessible if you know the password"
-
# end
-
#
-
# private
-
# def authenticate
-
# authenticate_or_request_with_http_token do |token, options|
-
# token == TOKEN
-
# end
-
# end
-
# end
-
#
-
#
-
# Here is a more advanced Token example where only Atom feeds and the XML API is protected by HTTP token authentication,
-
# the regular HTML interface is protected by a session approach:
-
#
-
# class ApplicationController < ActionController::Base
-
# before_action :set_account, :authenticate
-
#
-
# protected
-
# def set_account
-
# @account = Account.find_by(url_name: request.subdomains.first)
-
# end
-
#
-
# def authenticate
-
# case request.format
-
# when Mime::XML, Mime::ATOM
-
# if user = authenticate_with_http_token { |t, o| @account.users.authenticate(t, o) }
-
# @current_user = user
-
# else
-
# request_http_token_authentication
-
# end
-
# else
-
# if session_authenticated?
-
# @current_user = @account.users.find(session[:authenticated][:user_id])
-
# else
-
# redirect_to(login_url) and return false
-
# end
-
# end
-
# end
-
# end
-
#
-
#
-
# In your integration tests, you can do something like this:
-
#
-
# def test_access_granted_from_xml
-
# get(
-
# "/notes/1.xml", nil,
-
# 'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Token.encode_credentials(users(:dhh).token)
-
# )
-
#
-
# assert_equal 200, status
-
# end
-
#
-
#
-
# On shared hosts, Apache sometimes doesn't pass authentication headers to
-
# FCGI instances. If your environment matches this description and you cannot
-
# authenticate, try this rule in your Apache setup:
-
#
-
# RewriteRule ^(.*)$ dispatch.fcgi [E=X-HTTP_AUTHORIZATION:%{HTTP:Authorization},QSA,L]
-
1
module Token
-
1
TOKEN_REGEX = /^Token /
-
1
AUTHN_PAIR_DELIMITERS = /(?:,|;|\t+)/
-
1
extend self
-
-
1
module ControllerMethods
-
1
def authenticate_or_request_with_http_token(realm = "Application", &login_procedure)
-
authenticate_with_http_token(&login_procedure) || request_http_token_authentication(realm)
-
end
-
-
1
def authenticate_with_http_token(&login_procedure)
-
Token.authenticate(self, &login_procedure)
-
end
-
-
1
def request_http_token_authentication(realm = "Application")
-
Token.authentication_request(self, realm)
-
end
-
end
-
-
# If token Authorization header is present, call the login
-
# procedure with the present token and options.
-
#
-
# [controller]
-
# ActionController::Base instance for the current request.
-
#
-
# [login_procedure]
-
# Proc to call if a token is present. The Proc should take two arguments:
-
#
-
# authenticate(controller) { |token, options| ... }
-
#
-
# Returns the return value of <tt>login_procedure</tt> if a
-
# token is found. Returns <tt>nil</tt> if no token is found.
-
-
1
def authenticate(controller, &login_procedure)
-
token, options = token_and_options(controller.request)
-
unless token.blank?
-
login_procedure.call(token, options)
-
end
-
end
-
-
# Parses the token and options out of the token authorization header. If
-
# the header looks like this:
-
# Authorization: Token token="abc", nonce="def"
-
# Then the returned token is "abc", and the options is {nonce: "def"}
-
#
-
# request - ActionDispatch::Request instance with the current headers.
-
#
-
# Returns an Array of [String, Hash] if a token is present.
-
# Returns nil if no token is found.
-
1
def token_and_options(request)
-
authorization_request = request.authorization.to_s
-
if authorization_request[TOKEN_REGEX]
-
params = token_params_from authorization_request
-
[params.shift.last, Hash[params].with_indifferent_access]
-
end
-
end
-
-
1
def token_params_from(auth)
-
rewrite_param_values params_array_from raw_params auth
-
end
-
-
# Takes raw_params and turns it into an array of parameters
-
1
def params_array_from(raw_params)
-
raw_params.map { |param| param.split %r/=(.+)?/ }
-
end
-
-
# This removes the `"` characters wrapping the value.
-
1
def rewrite_param_values(array_params)
-
array_params.each { |param| param.last.gsub! %r/^"|"$/, '' }
-
end
-
-
# This method takes an authorization body and splits up the key-value
-
# pairs by the standardized `:`, `;`, or `\t` delimiters defined in
-
# `AUTHN_PAIR_DELIMITERS`.
-
1
def raw_params(auth)
-
auth.sub(TOKEN_REGEX, '').split(/"\s*#{AUTHN_PAIR_DELIMITERS}\s*/)
-
end
-
-
# Encodes the given token and options into an Authorization header value.
-
#
-
# token - String token.
-
# options - optional Hash of the options.
-
#
-
# Returns String.
-
1
def encode_credentials(token, options = {})
-
values = ["token=#{token.to_s.inspect}"] + options.map do |key, value|
-
"#{key}=#{value.to_s.inspect}"
-
end
-
"Token #{values * ", "}"
-
end
-
-
# Sets a WWW-Authenticate to let the client know a token is desired.
-
#
-
# controller - ActionController::Base instance for the outgoing response.
-
# realm - String realm to use in the header.
-
#
-
# Returns nothing.
-
1
def authentication_request(controller, realm)
-
controller.headers["WWW-Authenticate"] = %(Token realm="#{realm.gsub(/"/, "")}")
-
controller.__send__ :render, :text => "HTTP Token: Access denied.\n", :status => :unauthorized
-
end
-
end
-
end
-
end
-
1
module ActionController
-
1
module ImplicitRender
-
1
def send_action(method, *args)
-
ret = super
-
default_render unless performed?
-
ret
-
end
-
-
1
def default_render(*args)
-
render(*args)
-
end
-
-
1
def method_for_action(action_name)
-
super || if template_exists?(action_name.to_s, _prefixes)
-
"default_render"
-
end
-
end
-
end
-
end
-
1
require 'benchmark'
-
1
require 'abstract_controller/logger'
-
-
1
module ActionController
-
# Adds instrumentation to several ends in ActionController::Base. It also provides
-
# some hooks related with process_action, this allows an ORM like Active Record
-
# and/or DataMapper to plug in ActionController and show related information.
-
#
-
# Check ActiveRecord::Railties::ControllerRuntime for an example.
-
1
module Instrumentation
-
1
extend ActiveSupport::Concern
-
-
1
include AbstractController::Logger
-
1
include ActionController::RackDelegation
-
-
1
attr_internal :view_runtime
-
-
1
def process_action(*args)
-
raw_payload = {
-
:controller => self.class.name,
-
:action => self.action_name,
-
:params => request.filtered_parameters,
-
:format => request.format.try(:ref),
-
:method => request.method,
-
:path => (request.fullpath rescue "unknown")
-
}
-
-
ActiveSupport::Notifications.instrument("start_processing.action_controller", raw_payload.dup)
-
-
ActiveSupport::Notifications.instrument("process_action.action_controller", raw_payload) do |payload|
-
result = super
-
payload[:status] = response.status
-
append_info_to_payload(payload)
-
result
-
end
-
end
-
-
1
def render(*args)
-
render_output = nil
-
self.view_runtime = cleanup_view_runtime do
-
Benchmark.ms { render_output = super }
-
end
-
render_output
-
end
-
-
1
def send_file(path, options={})
-
ActiveSupport::Notifications.instrument("send_file.action_controller",
-
options.merge(:path => path)) do
-
super
-
end
-
end
-
-
1
def send_data(data, options = {})
-
ActiveSupport::Notifications.instrument("send_data.action_controller", options) do
-
super
-
end
-
end
-
-
1
def redirect_to(*args)
-
ActiveSupport::Notifications.instrument("redirect_to.action_controller") do |payload|
-
result = super
-
payload[:status] = response.status
-
payload[:location] = response.filtered_location
-
result
-
end
-
end
-
-
1
private
-
-
# A hook invoked every time a before callback is halted.
-
1
def halted_callback_hook(filter)
-
ActiveSupport::Notifications.instrument("halted_callback.action_controller", :filter => filter)
-
end
-
-
# A hook which allows you to clean up any time taken into account in
-
# views wrongly, like database querying time.
-
#
-
# def cleanup_view_runtime
-
# super - time_taken_in_something_expensive
-
# end
-
#
-
# :api: plugin
-
1
def cleanup_view_runtime #:nodoc:
-
yield
-
end
-
-
# Every time after an action is processed, this method is invoked
-
# with the payload, so you can add more information.
-
# :api: plugin
-
1
def append_info_to_payload(payload) #:nodoc:
-
payload[:view_runtime] = view_runtime
-
end
-
-
1
module ClassMethods
-
# A hook which allows other frameworks to log what happened during
-
# controller process action. This method should return an array
-
# with the messages to be added.
-
# :api: plugin
-
1
def log_process_action(payload) #:nodoc:
-
messages, view_runtime = [], payload[:view_runtime]
-
messages << ("Views: %.1fms" % view_runtime.to_f) if view_runtime
-
messages
-
end
-
end
-
end
-
end
-
1
require 'action_dispatch/http/response'
-
1
require 'delegate'
-
1
require 'active_support/json'
-
-
1
module ActionController
-
# Mix this module in to your controller, and all actions in that controller
-
# will be able to stream data to the client as it's written.
-
#
-
# class MyController < ActionController::Base
-
# include ActionController::Live
-
#
-
# def stream
-
# response.headers['Content-Type'] = 'text/event-stream'
-
# 100.times {
-
# response.stream.write "hello world\n"
-
# sleep 1
-
# }
-
# ensure
-
# response.stream.close
-
# end
-
# end
-
#
-
# There are a few caveats with this use. You *cannot* write headers after the
-
# response has been committed (Response#committed? will return truthy).
-
# Calling +write+ or +close+ on the response stream will cause the response
-
# object to be committed. Make sure all headers are set before calling write
-
# or close on your stream.
-
#
-
# You *must* call close on your stream when you're finished, otherwise the
-
# socket may be left open forever.
-
#
-
# The final caveat is that your actions are executed in a separate thread than
-
# the main thread. Make sure your actions are thread safe, and this shouldn't
-
# be a problem (don't share state across threads, etc).
-
1
module Live
-
# This class provides the ability to write an SSE (Server Sent Event)
-
# to an IO stream. The class is initialized with a stream and can be used
-
# to either write a JSON string or an object which can be converted to JSON.
-
#
-
# Writing an object will convert it into standard SSE format with whatever
-
# options you have configured. You may choose to set the following options:
-
#
-
# 1) Event. If specified, an event with this name will be dispatched on
-
# the browser.
-
# 2) Retry. The reconnection time in milliseconds used when attempting
-
# to send the event.
-
# 3) Id. If the connection dies while sending an SSE to the browser, then
-
# the server will receive a +Last-Event-ID+ header with value equal to +id+.
-
#
-
# After setting an option in the constructor of the SSE object, all future
-
# SSEs sent across the stream will use those options unless overridden.
-
#
-
# Example Usage:
-
#
-
# class MyController < ActionController::Base
-
# include ActionController::Live
-
#
-
# def index
-
# response.headers['Content-Type'] = 'text/event-stream'
-
# sse = SSE.new(response.stream, retry: 300, event: "event-name")
-
# sse.write({ name: 'John'})
-
# sse.write({ name: 'John'}, id: 10)
-
# sse.write({ name: 'John'}, id: 10, event: "other-event")
-
# sse.write({ name: 'John'}, id: 10, event: "other-event", retry: 500)
-
# ensure
-
# sse.close
-
# end
-
# end
-
#
-
# Note: SSEs are not currently supported by IE. However, they are supported
-
# by Chrome, Firefox, Opera, and Safari.
-
1
class SSE
-
-
1
WHITELISTED_OPTIONS = %w( retry event id )
-
-
1
def initialize(stream, options = {})
-
@stream = stream
-
@options = options
-
end
-
-
1
def close
-
@stream.close
-
end
-
-
1
def write(object, options = {})
-
case object
-
when String
-
perform_write(object, options)
-
else
-
perform_write(ActiveSupport::JSON.encode(object), options)
-
end
-
end
-
-
1
private
-
-
1
def perform_write(json, options)
-
current_options = @options.merge(options).stringify_keys
-
-
WHITELISTED_OPTIONS.each do |option_name|
-
if (option_value = current_options[option_name])
-
@stream.write "#{option_name}: #{option_value}\n"
-
end
-
end
-
-
@stream.write "data: #{json}\n\n"
-
end
-
end
-
-
1
class Buffer < ActionDispatch::Response::Buffer #:nodoc:
-
1
include MonitorMixin
-
-
1
def initialize(response)
-
@error_callback = lambda { true }
-
@cv = new_cond
-
super(response, SizedQueue.new(10))
-
end
-
-
1
def write(string)
-
unless @response.committed?
-
@response.headers["Cache-Control"] = "no-cache"
-
@response.headers.delete "Content-Length"
-
end
-
-
super
-
end
-
-
1
def each
-
@response.sending!
-
while str = @buf.pop
-
yield str
-
end
-
@response.sent!
-
end
-
-
1
def close
-
synchronize do
-
super
-
@buf.push nil
-
@cv.broadcast
-
end
-
end
-
-
1
def await_close
-
synchronize do
-
@cv.wait_until { @closed }
-
end
-
end
-
-
1
def on_error(&block)
-
@error_callback = block
-
end
-
-
1
def call_on_error
-
@error_callback.call
-
end
-
end
-
-
1
class Response < ActionDispatch::Response #:nodoc: all
-
1
class Header < DelegateClass(Hash)
-
1
def initialize(response, header)
-
@response = response
-
super(header)
-
end
-
-
1
def []=(k,v)
-
if @response.committed?
-
raise ActionDispatch::IllegalStateError, 'header already sent'
-
end
-
-
super
-
end
-
-
1
def merge(other)
-
self.class.new @response, __getobj__.merge(other)
-
end
-
-
1
def to_hash
-
__getobj__.dup
-
end
-
end
-
-
1
private
-
-
1
def before_committed
-
super
-
jar = request.cookie_jar
-
# The response can be committed multiple times
-
jar.write self unless committed?
-
end
-
-
1
def before_sending
-
super
-
request.cookie_jar.commit!
-
headers.freeze
-
end
-
-
1
def build_buffer(response, body)
-
buf = Live::Buffer.new response
-
body.each { |part| buf.write part }
-
buf
-
end
-
-
1
def merge_default_headers(original, default)
-
Header.new self, super
-
end
-
-
1
def handle_conditional_get!
-
super unless committed?
-
end
-
end
-
-
1
def process(name)
-
t1 = Thread.current
-
locals = t1.keys.map { |key| [key, t1[key]] }
-
-
error = nil
-
# This processes the action in a child thread. It lets us return the
-
# response code and headers back up the rack stack, and still process
-
# the body in parallel with sending data to the client
-
Thread.new {
-
t2 = Thread.current
-
t2.abort_on_exception = true
-
-
# Since we're processing the view in a different thread, copy the
-
# thread locals from the main thread to the child thread. :'(
-
locals.each { |k,v| t2[k] = v }
-
-
begin
-
super(name)
-
rescue => e
-
if @_response.committed?
-
begin
-
@_response.stream.write(ActionView::Base.streaming_completion_on_exception) if request.format == :html
-
@_response.stream.call_on_error
-
rescue => exception
-
log_error(exception)
-
ensure
-
log_error(e)
-
@_response.stream.close
-
end
-
else
-
error = e
-
end
-
ensure
-
@_response.commit!
-
end
-
}
-
-
@_response.await_commit
-
raise error if error
-
end
-
-
1
def log_error(exception)
-
logger = ActionController::Base.logger
-
return unless logger
-
-
message = "\n#{exception.class} (#{exception.message}):\n"
-
message << exception.annoted_source_code.to_s if exception.respond_to?(:annoted_source_code)
-
message << " " << exception.backtrace.join("\n ")
-
logger.fatal("#{message}\n\n")
-
end
-
-
1
def response_body=(body)
-
super
-
response.close if response
-
end
-
-
1
def set_response!(request)
-
if request.env["HTTP_VERSION"] == "HTTP/1.0"
-
super
-
else
-
@_response = Live::Response.new
-
@_response.request = request
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'abstract_controller/collector'
-
-
1
module ActionController #:nodoc:
-
1
module MimeResponds
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
class_attribute :responder, :mimes_for_respond_to
-
1
self.responder = ActionController::Responder
-
1
clear_respond_to
-
end
-
-
1
module ClassMethods
-
# Defines mime types that are rendered by default when invoking
-
# <tt>respond_with</tt>.
-
#
-
# respond_to :html, :xml, :json
-
#
-
# Specifies that all actions in the controller respond to requests
-
# for <tt>:html</tt>, <tt>:xml</tt> and <tt>:json</tt>.
-
#
-
# To specify on per-action basis, use <tt>:only</tt> and
-
# <tt>:except</tt> with an array of actions or a single action:
-
#
-
# respond_to :html
-
# respond_to :xml, :json, except: [ :edit ]
-
#
-
# This specifies that all actions respond to <tt>:html</tt>
-
# and all actions except <tt>:edit</tt> respond to <tt>:xml</tt> and
-
# <tt>:json</tt>.
-
#
-
# respond_to :json, only: :create
-
#
-
# This specifies that the <tt>:create</tt> action and no other responds
-
# to <tt>:json</tt>.
-
1
def respond_to(*mimes)
-
options = mimes.extract_options!
-
-
only_actions = Array(options.delete(:only)).map(&:to_s)
-
except_actions = Array(options.delete(:except)).map(&:to_s)
-
-
new = mimes_for_respond_to.dup
-
mimes.each do |mime|
-
mime = mime.to_sym
-
new[mime] = {}
-
new[mime][:only] = only_actions unless only_actions.empty?
-
new[mime][:except] = except_actions unless except_actions.empty?
-
end
-
self.mimes_for_respond_to = new.freeze
-
end
-
-
# Clear all mime types in <tt>respond_to</tt>.
-
#
-
1
def clear_respond_to
-
1
self.mimes_for_respond_to = Hash.new.freeze
-
end
-
end
-
-
# Without web-service support, an action which collects the data for displaying a list of people
-
# might look something like this:
-
#
-
# def index
-
# @people = Person.all
-
# end
-
#
-
# Here's the same action, with web-service support baked in:
-
#
-
# def index
-
# @people = Person.all
-
#
-
# respond_to do |format|
-
# format.html
-
# format.xml { render xml: @people }
-
# end
-
# end
-
#
-
# What that says is, "if the client wants HTML in response to this action, just respond as we
-
# would have before, but if the client wants XML, return them the list of people in XML format."
-
# (Rails determines the desired response format from the HTTP Accept header submitted by the client.)
-
#
-
# Supposing you have an action that adds a new person, optionally creating their company
-
# (by name) if it does not already exist, without web-services, it might look like this:
-
#
-
# def create
-
# @company = Company.find_or_create_by(name: params[:company][:name])
-
# @person = @company.people.create(params[:person])
-
#
-
# redirect_to(person_list_url)
-
# end
-
#
-
# Here's the same action, with web-service support baked in:
-
#
-
# def create
-
# company = params[:person].delete(:company)
-
# @company = Company.find_or_create_by(name: company[:name])
-
# @person = @company.people.create(params[:person])
-
#
-
# respond_to do |format|
-
# format.html { redirect_to(person_list_url) }
-
# format.js
-
# format.xml { render xml: @person.to_xml(include: @company) }
-
# end
-
# end
-
#
-
# If the client wants HTML, we just redirect them back to the person list. If they want JavaScript,
-
# then it is an Ajax request and we render the JavaScript template associated with this action.
-
# Lastly, if the client wants XML, we render the created person as XML, but with a twist: we also
-
# include the person's company in the rendered XML, so you get something like this:
-
#
-
# <person>
-
# <id>...</id>
-
# ...
-
# <company>
-
# <id>...</id>
-
# <name>...</name>
-
# ...
-
# </company>
-
# </person>
-
#
-
# Note, however, the extra bit at the top of that action:
-
#
-
# company = params[:person].delete(:company)
-
# @company = Company.find_or_create_by(name: company[:name])
-
#
-
# This is because the incoming XML document (if a web-service request is in process) can only contain a
-
# single root-node. So, we have to rearrange things so that the request looks like this (url-encoded):
-
#
-
# person[name]=...&person[company][name]=...&...
-
#
-
# And, like this (xml-encoded):
-
#
-
# <person>
-
# <name>...</name>
-
# <company>
-
# <name>...</name>
-
# </company>
-
# </person>
-
#
-
# In other words, we make the request so that it operates on a single entity's person. Then, in the action,
-
# we extract the company data from the request, find or create the company, and then create the new person
-
# with the remaining data.
-
#
-
# Note that you can define your own XML parameter parser which would allow you to describe multiple entities
-
# in a single request (i.e., by wrapping them all in a single root node), but if you just go with the flow
-
# and accept Rails' defaults, life will be much easier.
-
#
-
# If you need to use a MIME type which isn't supported by default, you can register your own handlers in
-
# config/initializers/mime_types.rb as follows.
-
#
-
# Mime::Type.register "image/jpg", :jpg
-
#
-
# Respond to also allows you to specify a common block for different formats by using any:
-
#
-
# def index
-
# @people = Person.all
-
#
-
# respond_to do |format|
-
# format.html
-
# format.any(:xml, :json) { render request.format.to_sym => @people }
-
# end
-
# end
-
#
-
# In the example above, if the format is xml, it will render:
-
#
-
# render xml: @people
-
#
-
# Or if the format is json:
-
#
-
# render json: @people
-
#
-
# Since this is a common pattern, you can use the class method respond_to
-
# with the respond_with method to have the same results:
-
#
-
# class PeopleController < ApplicationController
-
# respond_to :html, :xml, :json
-
#
-
# def index
-
# @people = Person.all
-
# respond_with(@people)
-
# end
-
# end
-
#
-
# Formats can have different variants.
-
#
-
# The request variant is a specialization of the request format, like <tt>:tablet</tt>,
-
# <tt>:phone</tt>, or <tt>:desktop</tt>.
-
#
-
# We often want to render different html/json/xml templates for phones,
-
# tablets, and desktop browsers. Variants make it easy.
-
#
-
# You can set the variant in a +before_action+:
-
#
-
# request.variant = :tablet if request.user_agent =~ /iPad/
-
#
-
# Respond to variants in the action just like you respond to formats:
-
#
-
# respond_to do |format|
-
# format.html do |variant|
-
# variant.tablet # renders app/views/projects/show.html+tablet.erb
-
# variant.phone { extra_setup; render ... }
-
# variant.none { special_setup } # executed only if there is no variant set
-
# end
-
# end
-
#
-
# Provide separate templates for each format and variant:
-
#
-
# app/views/projects/show.html.erb
-
# app/views/projects/show.html+tablet.erb
-
# app/views/projects/show.html+phone.erb
-
#
-
# When you're not sharing any code within the format, you can simplify defining variants
-
# using the inline syntax:
-
#
-
# respond_to do |format|
-
# format.js { render "trash" }
-
# format.html.phone { redirect_to progress_path }
-
# format.html.none { render "trash" }
-
# end
-
#
-
# Variants also support common `any`/`all` block that formats have.
-
#
-
# It works for both inline:
-
#
-
# respond_to do |format|
-
# format.html.any { render text: "any" }
-
# format.html.phone { render text: "phone" }
-
# end
-
#
-
# and block syntax:
-
#
-
# respond_to do |format|
-
# format.html do |variant|
-
# variant.any(:tablet, :phablet){ render text: "any" }
-
# variant.phone { render text: "phone" }
-
# end
-
# end
-
#
-
# You can also set an array of variants:
-
#
-
# request.variant = [:tablet, :phone]
-
#
-
# which will work similarly to formats and MIME types negotiation. If there will be no
-
# :tablet variant declared, :phone variant will be picked:
-
#
-
# respond_to do |format|
-
# format.html.none
-
# format.html.phone # this gets rendered
-
# end
-
#
-
# Be sure to check the documentation of +respond_with+ and
-
# <tt>ActionController::MimeResponds.respond_to</tt> for more examples.
-
1
def respond_to(*mimes, &block)
-
raise ArgumentError, "respond_to takes either types or a block, never both" if mimes.any? && block_given?
-
-
if collector = retrieve_collector_from_mimes(mimes, &block)
-
response = collector.response
-
response ? response.call : render({})
-
end
-
end
-
-
# For a given controller action, respond_with generates an appropriate
-
# response based on the mime-type requested by the client.
-
#
-
# If the method is called with just a resource, as in this example -
-
#
-
# class PeopleController < ApplicationController
-
# respond_to :html, :xml, :json
-
#
-
# def index
-
# @people = Person.all
-
# respond_with @people
-
# end
-
# end
-
#
-
# then the mime-type of the response is typically selected based on the
-
# request's Accept header and the set of available formats declared
-
# by previous calls to the controller's class method +respond_to+. Alternatively
-
# the mime-type can be selected by explicitly setting <tt>request.format</tt> in
-
# the controller.
-
#
-
# If an acceptable format is not identified, the application returns a
-
# '406 - not acceptable' status. Otherwise, the default response is to render
-
# a template named after the current action and the selected format,
-
# e.g. <tt>index.html.erb</tt>. If no template is available, the behavior
-
# depends on the selected format:
-
#
-
# * for an html response - if the request method is +get+, an exception
-
# is raised but for other requests such as +post+ the response
-
# depends on whether the resource has any validation errors (i.e.
-
# assuming that an attempt has been made to save the resource,
-
# e.g. by a +create+ action) -
-
# 1. If there are no errors, i.e. the resource
-
# was saved successfully, the response +redirect+'s to the resource
-
# i.e. its +show+ action.
-
# 2. If there are validation errors, the response
-
# renders a default action, which is <tt>:new</tt> for a
-
# +post+ request or <tt>:edit</tt> for +patch+ or +put+.
-
# Thus an example like this -
-
#
-
# respond_to :html, :xml
-
#
-
# def create
-
# @user = User.new(params[:user])
-
# flash[:notice] = 'User was successfully created.' if @user.save
-
# respond_with(@user)
-
# end
-
#
-
# is equivalent, in the absence of <tt>create.html.erb</tt>, to -
-
#
-
# def create
-
# @user = User.new(params[:user])
-
# respond_to do |format|
-
# if @user.save
-
# flash[:notice] = 'User was successfully created.'
-
# format.html { redirect_to(@user) }
-
# format.xml { render xml: @user }
-
# else
-
# format.html { render action: "new" }
-
# format.xml { render xml: @user }
-
# end
-
# end
-
# end
-
#
-
# * for a javascript request - if the template isn't found, an exception is
-
# raised.
-
# * for other requests - i.e. data formats such as xml, json, csv etc, if
-
# the resource passed to +respond_with+ responds to <code>to_<format></code>,
-
# the method attempts to render the resource in the requested format
-
# directly, e.g. for an xml request, the response is equivalent to calling
-
# <code>render xml: resource</code>.
-
#
-
# === Nested resources
-
#
-
# As outlined above, the +resources+ argument passed to +respond_with+
-
# can play two roles. It can be used to generate the redirect url
-
# for successful html requests (e.g. for +create+ actions when
-
# no template exists), while for formats other than html and javascript
-
# it is the object that gets rendered, by being converted directly to the
-
# required format (again assuming no template exists).
-
#
-
# For redirecting successful html requests, +respond_with+ also supports
-
# the use of nested resources, which are supplied in the same way as
-
# in <code>form_for</code> and <code>polymorphic_url</code>. For example -
-
#
-
# def create
-
# @project = Project.find(params[:project_id])
-
# @task = @project.comments.build(params[:task])
-
# flash[:notice] = 'Task was successfully created.' if @task.save
-
# respond_with(@project, @task)
-
# end
-
#
-
# This would cause +respond_with+ to redirect to <code>project_task_url</code>
-
# instead of <code>task_url</code>. For request formats other than html or
-
# javascript, if multiple resources are passed in this way, it is the last
-
# one specified that is rendered.
-
#
-
# === Customizing response behavior
-
#
-
# Like +respond_to+, +respond_with+ may also be called with a block that
-
# can be used to overwrite any of the default responses, e.g. -
-
#
-
# def create
-
# @user = User.new(params[:user])
-
# flash[:notice] = "User was successfully created." if @user.save
-
#
-
# respond_with(@user) do |format|
-
# format.html { render }
-
# end
-
# end
-
#
-
# The argument passed to the block is an ActionController::MimeResponds::Collector
-
# object which stores the responses for the formats defined within the
-
# block. Note that formats with responses defined explicitly in this way
-
# do not have to first be declared using the class method +respond_to+.
-
#
-
# Also, a hash passed to +respond_with+ immediately after the specified
-
# resource(s) is interpreted as a set of options relevant to all
-
# formats. Any option accepted by +render+ can be used, e.g.
-
# respond_with @people, status: 200
-
# However, note that these options are ignored after an unsuccessful attempt
-
# to save a resource, e.g. when automatically rendering <tt>:new</tt>
-
# after a post request.
-
#
-
# Two additional options are relevant specifically to +respond_with+ -
-
# 1. <tt>:location</tt> - overwrites the default redirect location used after
-
# a successful html +post+ request.
-
# 2. <tt>:action</tt> - overwrites the default render action used after an
-
# unsuccessful html +post+ request.
-
1
def respond_with(*resources, &block)
-
if self.class.mimes_for_respond_to.empty?
-
raise "In order to use respond_with, first you need to declare the " \
-
"formats your controller responds to in the class level."
-
end
-
-
if collector = retrieve_collector_from_mimes(&block)
-
options = resources.size == 1 ? {} : resources.extract_options!
-
options = options.clone
-
options[:default_response] = collector.response
-
(options.delete(:responder) || self.class.responder).call(self, resources, options)
-
end
-
end
-
-
1
protected
-
-
# Collect mimes declared in the class method respond_to valid for the
-
# current action.
-
1
def collect_mimes_from_class_level #:nodoc:
-
action = action_name.to_s
-
-
self.class.mimes_for_respond_to.keys.select do |mime|
-
config = self.class.mimes_for_respond_to[mime]
-
-
if config[:except]
-
!config[:except].include?(action)
-
elsif config[:only]
-
config[:only].include?(action)
-
else
-
true
-
end
-
end
-
end
-
-
# Returns a Collector object containing the appropriate mime-type response
-
# for the current request, based on the available responses defined by a block.
-
# In typical usage this is the block passed to +respond_with+ or +respond_to+.
-
#
-
# Sends :not_acceptable to the client and returns nil if no suitable format
-
# is available.
-
1
def retrieve_collector_from_mimes(mimes=nil, &block) #:nodoc:
-
mimes ||= collect_mimes_from_class_level
-
collector = Collector.new(mimes, request.variant)
-
block.call(collector) if block_given?
-
format = collector.negotiate_format(request)
-
-
if format
-
_process_format(format)
-
collector
-
else
-
raise ActionController::UnknownFormat
-
end
-
end
-
-
# A container for responses available from the current controller for
-
# requests for different mime-types sent to a particular action.
-
#
-
# The public controller methods +respond_with+ and +respond_to+ may be called
-
# with a block that is used to define responses to different mime-types, e.g.
-
# for +respond_to+ :
-
#
-
# respond_to do |format|
-
# format.html
-
# format.xml { render xml: @people }
-
# end
-
#
-
# In this usage, the argument passed to the block (+format+ above) is an
-
# instance of the ActionController::MimeResponds::Collector class. This
-
# object serves as a container in which available responses can be stored by
-
# calling any of the dynamically generated, mime-type-specific methods such
-
# as +html+, +xml+ etc on the Collector. Each response is represented by a
-
# corresponding block if present.
-
#
-
# A subsequent call to #negotiate_format(request) will enable the Collector
-
# to determine which specific mime-type it should respond with for the current
-
# request, with this response then being accessible by calling #response.
-
1
class Collector
-
1
include AbstractController::Collector
-
1
attr_accessor :format
-
-
1
def initialize(mimes, variant = nil)
-
@responses = {}
-
@variant = variant
-
-
mimes.each { |mime| @responses["Mime::#{mime.upcase}".constantize] = nil }
-
end
-
-
1
def any(*args, &block)
-
if args.any?
-
args.each { |type| send(type, &block) }
-
else
-
custom(Mime::ALL, &block)
-
end
-
end
-
1
alias :all :any
-
-
1
def custom(mime_type, &block)
-
mime_type = Mime::Type.lookup(mime_type.to_s) unless mime_type.is_a?(Mime::Type)
-
@responses[mime_type] ||= if block_given?
-
block
-
else
-
VariantCollector.new(@variant)
-
end
-
end
-
-
1
def response
-
response = @responses.fetch(format, @responses[Mime::ALL])
-
if response.is_a?(VariantCollector) # `format.html.phone` - variant inline syntax
-
response.variant
-
elsif response.nil? || response.arity == 0 # `format.html` - just a format, call its block
-
response
-
else # `format.html{ |variant| variant.phone }` - variant block syntax
-
variant_collector = VariantCollector.new(@variant)
-
response.call(variant_collector) # call format block with variants collector
-
variant_collector.variant
-
end
-
end
-
-
1
def negotiate_format(request)
-
@format = request.negotiate_mime(@responses.keys)
-
end
-
-
1
class VariantCollector #:nodoc:
-
1
def initialize(variant = nil)
-
@variant = variant
-
@variants = {}
-
end
-
-
1
def any(*args, &block)
-
if block_given?
-
if args.any? && args.none?{ |a| a == @variant }
-
args.each{ |v| @variants[v] = block }
-
else
-
@variants[:any] = block
-
end
-
end
-
end
-
1
alias :all :any
-
-
1
def method_missing(name, *args, &block)
-
@variants[name] = block if block_given?
-
end
-
-
1
def variant
-
if @variant.nil?
-
@variants[:none] || @variants[:any]
-
elsif (@variants.keys & @variant).any?
-
@variant.each do |v|
-
return @variants[v] if @variants.key?(v)
-
end
-
else
-
@variants[:any]
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/slice'
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/module/anonymous'
-
1
require 'active_support/core_ext/struct'
-
1
require 'action_dispatch/http/mime_type'
-
-
1
module ActionController
-
# Wraps the parameters hash into a nested hash. This will allow clients to submit
-
# POST requests without having to specify any root elements.
-
#
-
# This functionality is enabled in +config/initializers/wrap_parameters.rb+
-
# and can be customized. If you are upgrading to \Rails 3.1, this file will
-
# need to be created for the functionality to be enabled.
-
#
-
# You could also turn it on per controller by setting the format array to
-
# a non-empty array:
-
#
-
# class UsersController < ApplicationController
-
# wrap_parameters format: [:json, :xml]
-
# end
-
#
-
# If you enable +ParamsWrapper+ for +:json+ format, instead of having to
-
# send JSON parameters like this:
-
#
-
# {"user": {"name": "Konata"}}
-
#
-
# You can send parameters like this:
-
#
-
# {"name": "Konata"}
-
#
-
# And it will be wrapped into a nested hash with the key name matching the
-
# controller's name. For example, if you're posting to +UsersController+,
-
# your new +params+ hash will look like this:
-
#
-
# {"name" => "Konata", "user" => {"name" => "Konata"}}
-
#
-
# You can also specify the key in which the parameters should be wrapped to,
-
# and also the list of attributes it should wrap by using either +:include+ or
-
# +:exclude+ options like this:
-
#
-
# class UsersController < ApplicationController
-
# wrap_parameters :person, include: [:username, :password]
-
# end
-
#
-
# On ActiveRecord models with no +:include+ or +:exclude+ option set,
-
# it will only wrap the parameters returned by the class method
-
# <tt>attribute_names</tt>.
-
#
-
# If you're going to pass the parameters to an +ActiveModel+ object (such as
-
# <tt>User.new(params[:user])</tt>), you might consider passing the model class to
-
# the method instead. The +ParamsWrapper+ will actually try to determine the
-
# list of attribute names from the model and only wrap those attributes:
-
#
-
# class UsersController < ApplicationController
-
# wrap_parameters Person
-
# end
-
#
-
# You still could pass +:include+ and +:exclude+ to set the list of attributes
-
# you want to wrap.
-
#
-
# By default, if you don't specify the key in which the parameters would be
-
# wrapped to, +ParamsWrapper+ will actually try to determine if there's
-
# a model related to it or not. This controller, for example:
-
#
-
# class Admin::UsersController < ApplicationController
-
# end
-
#
-
# will try to check if <tt>Admin::User</tt> or +User+ model exists, and use it to
-
# determine the wrapper key respectively. If both models don't exist,
-
# it will then fallback to use +user+ as the key.
-
1
module ParamsWrapper
-
1
extend ActiveSupport::Concern
-
-
1
EXCLUDE_PARAMETERS = %w(authenticity_token _method utf8)
-
-
1
require 'mutex_m'
-
-
1
class Options < Struct.new(:name, :format, :include, :exclude, :klass, :model) # :nodoc:
-
1
include Mutex_m
-
-
1
def self.from_hash(hash)
-
2
name = hash[:name]
-
2
format = Array(hash[:format])
-
2
include = hash[:include] && Array(hash[:include]).collect(&:to_s)
-
2
exclude = hash[:exclude] && Array(hash[:exclude]).collect(&:to_s)
-
2
new name, format, include, exclude, nil, nil
-
end
-
-
1
def initialize(name, format, include, exclude, klass, model) # nodoc
-
2
super
-
2
@include_set = include
-
2
@name_set = name
-
end
-
-
1
def model
-
super || synchronize { super || self.model = _default_wrap_model }
-
end
-
-
1
def include
-
return super if @include_set
-
-
m = model
-
synchronize do
-
return super if @include_set
-
-
@include_set = true
-
-
unless super || exclude
-
if m.respond_to?(:attribute_names) && m.attribute_names.any?
-
self.include = m.attribute_names
-
end
-
end
-
end
-
end
-
-
1
def name
-
return super if @name_set
-
-
m = model
-
synchronize do
-
return super if @name_set
-
-
@name_set = true
-
-
unless super || klass.anonymous?
-
self.name = m ? m.to_s.demodulize.underscore :
-
klass.controller_name.singularize
-
end
-
end
-
end
-
-
1
private
-
# Determine the wrapper model from the controller's name. By convention,
-
# this could be done by trying to find the defined model that has the
-
# same singularize name as the controller. For example, +UsersController+
-
# will try to find if the +User+ model exists.
-
#
-
# This method also does namespace lookup. Foo::Bar::UsersController will
-
# try to find Foo::Bar::User, Foo::User and finally User.
-
1
def _default_wrap_model #:nodoc:
-
return nil if klass.anonymous?
-
model_name = klass.name.sub(/Controller$/, '').classify
-
-
begin
-
if model_klass = model_name.safe_constantize
-
model_klass
-
else
-
namespaces = model_name.split("::")
-
namespaces.delete_at(-2)
-
break if namespaces.last == model_name
-
model_name = namespaces.join("::")
-
end
-
end until model_klass
-
-
model_klass
-
end
-
end
-
-
1
included do
-
1
class_attribute :_wrapper_options
-
1
self._wrapper_options = Options.from_hash(format: [])
-
end
-
-
1
module ClassMethods
-
1
def _set_wrapper_options(options)
-
self._wrapper_options = Options.from_hash(options)
-
end
-
-
# Sets the name of the wrapper key, or the model which +ParamsWrapper+
-
# would use to determine the attribute names from.
-
#
-
# ==== Examples
-
# wrap_parameters format: :xml
-
# # enables the parameter wrapper for XML format
-
#
-
# wrap_parameters :person
-
# # wraps parameters into +params[:person]+ hash
-
#
-
# wrap_parameters Person
-
# # wraps parameters by determining the wrapper key from Person class
-
# (+person+, in this case) and the list of attribute names
-
#
-
# wrap_parameters include: [:username, :title]
-
# # wraps only +:username+ and +:title+ attributes from parameters.
-
#
-
# wrap_parameters false
-
# # disables parameters wrapping for this controller altogether.
-
#
-
# ==== Options
-
# * <tt>:format</tt> - The list of formats in which the parameters wrapper
-
# will be enabled.
-
# * <tt>:include</tt> - The list of attribute names which parameters wrapper
-
# will wrap into a nested hash.
-
# * <tt>:exclude</tt> - The list of attribute names which parameters wrapper
-
# will exclude from a nested hash.
-
1
def wrap_parameters(name_or_model_or_options, options = {})
-
1
model = nil
-
-
1
case name_or_model_or_options
-
when Hash
-
1
options = name_or_model_or_options
-
when false
-
options = options.merge(:format => [])
-
when Symbol, String
-
options = options.merge(:name => name_or_model_or_options)
-
else
-
model = name_or_model_or_options
-
end
-
-
1
opts = Options.from_hash _wrapper_options.to_h.slice(:format).merge(options)
-
1
opts.model = model
-
1
opts.klass = self
-
-
1
self._wrapper_options = opts
-
end
-
-
# Sets the default wrapper key or model which will be used to determine
-
# wrapper key and attribute names. Will be called automatically when the
-
# module is inherited.
-
1
def inherited(klass)
-
1
if klass._wrapper_options.format.any?
-
1
params = klass._wrapper_options.dup
-
1
params.klass = klass
-
1
klass._wrapper_options = params
-
end
-
1
super
-
end
-
end
-
-
# Performs parameters wrapping upon the request. Will be called automatically
-
# by the metal call stack.
-
1
def process_action(*args)
-
if _wrapper_enabled?
-
if request.parameters[_wrapper_key].present?
-
wrapped_hash = _extract_parameters(request.parameters)
-
else
-
wrapped_hash = _wrap_parameters request.request_parameters
-
end
-
-
wrapped_keys = request.request_parameters.keys
-
wrapped_filtered_hash = _wrap_parameters request.filtered_parameters.slice(*wrapped_keys)
-
-
# This will make the wrapped hash accessible from controller and view
-
request.parameters.merge! wrapped_hash
-
request.request_parameters.merge! wrapped_hash
-
-
# This will make the wrapped hash displayed in the log file
-
request.filtered_parameters.merge! wrapped_filtered_hash
-
end
-
super
-
end
-
-
1
private
-
-
# Returns the wrapper key which will use to stored wrapped parameters.
-
1
def _wrapper_key
-
_wrapper_options.name
-
end
-
-
# Returns the list of enabled formats.
-
1
def _wrapper_formats
-
_wrapper_options.format
-
end
-
-
# Returns the list of parameters which will be selected for wrapped.
-
1
def _wrap_parameters(parameters)
-
{ _wrapper_key => _extract_parameters(parameters) }
-
end
-
-
1
def _extract_parameters(parameters)
-
if include_only = _wrapper_options.include
-
parameters.slice(*include_only)
-
else
-
exclude = _wrapper_options.exclude || []
-
parameters.except(*(exclude + EXCLUDE_PARAMETERS))
-
end
-
end
-
-
# Checks if we should perform parameters wrapping.
-
1
def _wrapper_enabled?
-
ref = request.content_mime_type.try(:ref)
-
_wrapper_formats.include?(ref) && _wrapper_key && !request.request_parameters[_wrapper_key]
-
end
-
end
-
end
-
1
require 'action_dispatch/http/request'
-
1
require 'action_dispatch/http/response'
-
-
1
module ActionController
-
1
module RackDelegation
-
1
extend ActiveSupport::Concern
-
-
1
delegate :headers, :status=, :location=, :content_type=,
-
:status, :location, :content_type, :to => "@_response"
-
-
1
def dispatch(action, request)
-
set_response!(request)
-
super(action, request)
-
end
-
-
1
def response_body=(body)
-
response.body = body if response
-
super
-
end
-
-
1
def reset_session
-
@_request.reset_session
-
end
-
-
1
private
-
-
1
def set_response!(request)
-
@_response = ActionDispatch::Response.new
-
@_response.request = request
-
end
-
end
-
end
-
1
module ActionController
-
1
class RedirectBackError < AbstractController::Error #:nodoc:
-
1
DEFAULT_MESSAGE = 'No HTTP_REFERER was set in the request to this action, so redirect_to :back could not be called successfully. If this is a test, make sure to specify request.env["HTTP_REFERER"].'
-
-
1
def initialize(message = nil)
-
super(message || DEFAULT_MESSAGE)
-
end
-
end
-
-
1
module Redirecting
-
1
extend ActiveSupport::Concern
-
-
1
include AbstractController::Logger
-
1
include ActionController::RackDelegation
-
1
include ActionController::UrlFor
-
-
# Redirects the browser to the target specified in +options+. This parameter can take one of three forms:
-
#
-
# * <tt>Hash</tt> - The URL will be generated by calling url_for with the +options+.
-
# * <tt>Record</tt> - The URL will be generated by calling url_for with the +options+, which will reference a named URL for that record.
-
# * <tt>String</tt> starting with <tt>protocol://</tt> (like <tt>http://</tt>) or a protocol relative reference (like <tt>//</tt>) - Is passed straight through as the target for redirection.
-
# * <tt>String</tt> not containing a protocol - The current protocol and host is prepended to the string.
-
# * <tt>Proc</tt> - A block that will be executed in the controller's context. Should return any option accepted by +redirect_to+.
-
# * <tt>:back</tt> - Back to the page that issued the request. Useful for forms that are triggered from multiple places.
-
# Short-hand for <tt>redirect_to(request.env["HTTP_REFERER"])</tt>
-
#
-
# redirect_to action: "show", id: 5
-
# redirect_to post
-
# redirect_to "http://www.rubyonrails.org"
-
# redirect_to "/images/screenshot.jpg"
-
# redirect_to articles_url
-
# redirect_to :back
-
# redirect_to proc { edit_post_url(@post) }
-
#
-
# The redirection happens as a "302 Found" header unless otherwise specified.
-
#
-
# redirect_to post_url(@post), status: :found
-
# redirect_to action: 'atom', status: :moved_permanently
-
# redirect_to post_url(@post), status: 301
-
# redirect_to action: 'atom', status: 302
-
#
-
# The status code can either be a standard {HTTP Status code}[http://www.iana.org/assignments/http-status-codes] as an
-
# integer, or a symbol representing the downcased, underscored and symbolized description.
-
# Note that the status code must be a 3xx HTTP code, or redirection will not occur.
-
#
-
# If you are using XHR requests other than GET or POST and redirecting after the
-
# request then some browsers will follow the redirect using the original request
-
# method. This may lead to undesirable behavior such as a double DELETE. To work
-
# around this you can return a <tt>303 See Other</tt> status code which will be
-
# followed using a GET request.
-
#
-
# redirect_to posts_url, status: :see_other
-
# redirect_to action: 'index', status: 303
-
#
-
# It is also possible to assign a flash message as part of the redirection. There are two special accessors for the commonly used flash names
-
# +alert+ and +notice+ as well as a general purpose +flash+ bucket.
-
#
-
# redirect_to post_url(@post), alert: "Watch it, mister!"
-
# redirect_to post_url(@post), status: :found, notice: "Pay attention to the road"
-
# redirect_to post_url(@post), status: 301, flash: { updated_post_id: @post.id }
-
# redirect_to({ action: 'atom' }, alert: "Something serious happened")
-
#
-
# When using <tt>redirect_to :back</tt>, if there is no referrer, ActionController::RedirectBackError will be raised. You may specify some fallback
-
# behavior for this case by rescuing ActionController::RedirectBackError.
-
1
def redirect_to(options = {}, response_status = {}) #:doc:
-
raise ActionControllerError.new("Cannot redirect to nil!") unless options
-
raise AbstractController::DoubleRenderError if response_body
-
-
self.status = _extract_redirect_to_status(options, response_status)
-
self.location = _compute_redirect_to_location(options)
-
self.response_body = "<html><body>You are being <a href=\"#{ERB::Util.h(location)}\">redirected</a>.</body></html>"
-
end
-
-
1
def _compute_redirect_to_location(options) #:nodoc:
-
case options
-
# The scheme name consist of a letter followed by any combination of
-
# letters, digits, and the plus ("+"), period ("."), or hyphen ("-")
-
# characters; and is terminated by a colon (":").
-
# See http://tools.ietf.org/html/rfc3986#section-3.1
-
# The protocol relative scheme starts with a double slash "//".
-
when /\A([a-z][a-z\d\-+\.]*:|\/\/).*/i
-
options
-
when String
-
request.protocol + request.host_with_port + options
-
when :back
-
request.headers["Referer"] or raise RedirectBackError
-
when Proc
-
_compute_redirect_to_location options.call
-
else
-
url_for(options)
-
end.delete("\0\r\n")
-
end
-
-
1
private
-
1
def _extract_redirect_to_status(options, response_status)
-
if options.is_a?(Hash) && options.key?(:status)
-
Rack::Utils.status_code(options.delete(:status))
-
elsif response_status.key?(:status)
-
Rack::Utils.status_code(response_status[:status])
-
else
-
302
-
end
-
end
-
end
-
end
-
1
require 'set'
-
-
1
module ActionController
-
# See <tt>Renderers.add</tt>
-
1
def self.add_renderer(key, &block)
-
Renderers.add(key, &block)
-
end
-
-
1
class MissingRenderer < LoadError
-
1
def initialize(format)
-
super "No renderer defined for format: #{format}"
-
end
-
end
-
-
1
module Renderers
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
class_attribute :_renderers
-
1
self._renderers = Set.new.freeze
-
end
-
-
1
module ClassMethods
-
1
def use_renderers(*args)
-
renderers = _renderers + args
-
self._renderers = renderers.freeze
-
end
-
1
alias use_renderer use_renderers
-
end
-
-
1
def render_to_body(options)
-
_handle_render_options(options) || super
-
end
-
-
1
def _handle_render_options(options)
-
_renderers.each do |name|
-
if options.key?(name)
-
_process_options(options)
-
return send("_render_option_#{name}", options.delete(name), options)
-
end
-
end
-
nil
-
end
-
-
# Hash of available renderers, mapping a renderer name to its proc.
-
# Default keys are <tt>:json</tt>, <tt>:js</tt>, <tt>:xml</tt>.
-
1
RENDERERS = Set.new
-
-
# Adds a new renderer to call within controller actions.
-
# A renderer is invoked by passing its name as an option to
-
# <tt>AbstractController::Rendering#render</tt>. To create a renderer
-
# pass it a name and a block. The block takes two arguments, the first
-
# is the value paired with its key and the second is the remaining
-
# hash of options passed to +render+.
-
#
-
# Create a csv renderer:
-
#
-
# ActionController::Renderers.add :csv do |obj, options|
-
# filename = options[:filename] || 'data'
-
# str = obj.respond_to?(:to_csv) ? obj.to_csv : obj.to_s
-
# send_data str, type: Mime::CSV,
-
# disposition: "attachment; filename=#{filename}.csv"
-
# end
-
#
-
# Note that we used Mime::CSV for the csv mime type as it comes with Rails.
-
# For a custom renderer, you'll need to register a mime type with
-
# <tt>Mime::Type.register</tt>.
-
#
-
# To use the csv renderer in a controller action:
-
#
-
# def show
-
# @csvable = Csvable.find(params[:id])
-
# respond_to do |format|
-
# format.html
-
# format.csv { render csv: @csvable, filename: @csvable.name }
-
# }
-
# end
-
# To use renderers and their mime types in more concise ways, see
-
# <tt>ActionController::MimeResponds::ClassMethods.respond_to</tt> and
-
# <tt>ActionController::MimeResponds#respond_with</tt>
-
1
def self.add(key, &block)
-
3
define_method("_render_option_#{key}", &block)
-
3
RENDERERS << key.to_sym
-
end
-
-
1
module All
-
1
extend ActiveSupport::Concern
-
1
include Renderers
-
-
1
included do
-
1
self._renderers = RENDERERS
-
end
-
end
-
-
1
add :json do |json, options|
-
json = json.to_json(options) unless json.kind_of?(String)
-
-
if options[:callback].present?
-
self.content_type ||= Mime::JS
-
"#{options[:callback]}(#{json})"
-
else
-
self.content_type ||= Mime::JSON
-
json
-
end
-
end
-
-
1
add :js do |js, options|
-
self.content_type ||= Mime::JS
-
js.respond_to?(:to_js) ? js.to_js(options) : js
-
end
-
-
1
add :xml do |xml, options|
-
self.content_type ||= Mime::XML
-
xml.respond_to?(:to_xml) ? xml.to_xml(options) : xml
-
end
-
end
-
end
-
1
module ActionController
-
1
module Rendering
-
1
extend ActiveSupport::Concern
-
-
1
RENDER_FORMATS_IN_PRIORITY = [:body, :text, :plain, :html]
-
-
# Before processing, set the request formats in current controller formats.
-
1
def process_action(*) #:nodoc:
-
self.formats = request.formats.map(&:ref).compact
-
super
-
end
-
-
# Check for double render errors and set the content_type after rendering.
-
1
def render(*args) #:nodoc:
-
raise ::AbstractController::DoubleRenderError if self.response_body
-
super
-
end
-
-
# Overwrite render_to_string because body can now be set to a rack body.
-
1
def render_to_string(*)
-
result = super
-
if result.respond_to?(:each)
-
string = ""
-
result.each { |r| string << r }
-
string
-
else
-
result
-
end
-
end
-
-
1
def render_to_body(options = {})
-
super || _render_in_priorities(options) || ' '
-
end
-
-
1
private
-
-
1
def _render_in_priorities(options)
-
RENDER_FORMATS_IN_PRIORITY.each do |format|
-
return options[format] if options.key?(format)
-
end
-
-
nil
-
end
-
-
1
def _process_format(format, options = {})
-
super
-
-
if options[:plain]
-
self.content_type = Mime::TEXT
-
else
-
self.content_type ||= format.to_s
-
end
-
end
-
-
# Normalize arguments by catching blocks and setting them on :update.
-
1
def _normalize_args(action=nil, options={}, &blk) #:nodoc:
-
options = super
-
options[:update] = blk if block_given?
-
options
-
end
-
-
# Normalize both text and status options.
-
1
def _normalize_options(options) #:nodoc:
-
_normalize_text(options)
-
-
if options[:html]
-
options[:html] = ERB::Util.html_escape(options[:html])
-
end
-
-
if options.delete(:nothing) || _any_render_format_is_nil?(options)
-
options[:body] = " "
-
end
-
-
if options[:status]
-
options[:status] = Rack::Utils.status_code(options[:status])
-
end
-
-
super
-
end
-
-
1
def _normalize_text(options)
-
RENDER_FORMATS_IN_PRIORITY.each do |format|
-
if options.key?(format) && options[format].respond_to?(:to_text)
-
options[format] = options[format].to_text
-
end
-
end
-
end
-
-
1
def _any_render_format_is_nil?(options)
-
RENDER_FORMATS_IN_PRIORITY.any? { |format| options.key?(format) && options[format].nil? }
-
end
-
-
# Process controller specific options, as status, content-type and location.
-
1
def _process_options(options) #:nodoc:
-
status, content_type, location = options.values_at(:status, :content_type, :location)
-
-
self.status = status if status
-
self.content_type = content_type if content_type
-
self.headers["Location"] = url_for(location) if location
-
-
super
-
end
-
end
-
end
-
1
require 'rack/session/abstract/id'
-
1
require 'action_controller/metal/exceptions'
-
-
1
module ActionController #:nodoc:
-
1
class InvalidAuthenticityToken < ActionControllerError #:nodoc:
-
end
-
-
1
class InvalidCrossOriginRequest < ActionControllerError #:nodoc:
-
end
-
-
# Controller actions are protected from Cross-Site Request Forgery (CSRF) attacks
-
# by including a token in the rendered html for your application. This token is
-
# stored as a random string in the session, to which an attacker does not have
-
# access. When a request reaches your application, \Rails verifies the received
-
# token with the token in the session. Only HTML and JavaScript requests are checked,
-
# so this will not protect your XML API (presumably you'll have a different
-
# authentication scheme there anyway).
-
#
-
# GET requests are not protected since they don't have side effects like writing
-
# to the database and don't leak sensitive information. JavaScript requests are
-
# an exception: a third-party site can use a <script> tag to reference a JavaScript
-
# URL on your site. When your JavaScript response loads on their site, it executes.
-
# With carefully crafted JavaScript on their end, sensitive data in your JavaScript
-
# response may be extracted. To prevent this, only XmlHttpRequest (known as XHR or
-
# Ajax) requests are allowed to make GET requests for JavaScript responses.
-
#
-
# It's important to remember that XML or JSON requests are also affected and if
-
# you're building an API you'll need something like:
-
#
-
# class ApplicationController < ActionController::Base
-
# protect_from_forgery
-
# skip_before_action :verify_authenticity_token, if: :json_request?
-
#
-
# protected
-
#
-
# def json_request?
-
# request.format.json?
-
# end
-
# end
-
#
-
# CSRF protection is turned on with the <tt>protect_from_forgery</tt> method,
-
# which checks the token and resets the session if it doesn't match what was expected.
-
# A call to this method is generated for new \Rails applications by default.
-
#
-
# The token parameter is named <tt>authenticity_token</tt> by default. The name and
-
# value of this token must be added to every layout that renders forms by including
-
# <tt>csrf_meta_tags</tt> in the html +head+.
-
#
-
# Learn more about CSRF attacks and securing your application in the
-
# {Ruby on Rails Security Guide}[http://guides.rubyonrails.org/security.html].
-
1
module RequestForgeryProtection
-
1
extend ActiveSupport::Concern
-
-
1
include AbstractController::Helpers
-
1
include AbstractController::Callbacks
-
-
1
included do
-
# Sets the token parameter name for RequestForgery. Calling +protect_from_forgery+
-
# sets it to <tt>:authenticity_token</tt> by default.
-
1
config_accessor :request_forgery_protection_token
-
1
self.request_forgery_protection_token ||= :authenticity_token
-
-
# Holds the class which implements the request forgery protection.
-
1
config_accessor :forgery_protection_strategy
-
1
self.forgery_protection_strategy = nil
-
-
# Controls whether request forgery protection is turned on or not. Turned off by default only in test mode.
-
1
config_accessor :allow_forgery_protection
-
1
self.allow_forgery_protection = true if allow_forgery_protection.nil?
-
-
1
helper_method :form_authenticity_token
-
1
helper_method :protect_against_forgery?
-
end
-
-
1
module ClassMethods
-
# Turn on request forgery protection. Bear in mind that only non-GET, HTML/JavaScript requests are checked.
-
#
-
# class ApplicationController < ActionController::Base
-
# protect_from_forgery
-
# end
-
#
-
# class FooController < ApplicationController
-
# protect_from_forgery except: :index
-
#
-
# You can disable CSRF protection on controller by skipping the verification before_action:
-
# skip_before_action :verify_authenticity_token
-
#
-
# Valid Options:
-
#
-
# * <tt>:only/:except</tt> - Passed to the <tt>before_action</tt> call. Set which actions are verified.
-
# * <tt>:with</tt> - Set the method to handle unverified request.
-
#
-
# Valid unverified request handling methods are:
-
# * <tt>:exception</tt> - Raises ActionController::InvalidAuthenticityToken exception.
-
# * <tt>:reset_session</tt> - Resets the session.
-
# * <tt>:null_session</tt> - Provides an empty session during request but doesn't reset it completely. Used as default if <tt>:with</tt> option is not specified.
-
1
def protect_from_forgery(options = {})
-
self.forgery_protection_strategy = protection_method_class(options[:with] || :null_session)
-
self.request_forgery_protection_token ||= :authenticity_token
-
prepend_before_action :verify_authenticity_token, options
-
append_after_action :verify_same_origin_request
-
end
-
-
1
private
-
-
1
def protection_method_class(name)
-
ActionController::RequestForgeryProtection::ProtectionMethods.const_get(name.to_s.classify)
-
rescue NameError
-
raise ArgumentError, 'Invalid request forgery protection method, use :null_session, :exception, or :reset_session'
-
end
-
end
-
-
1
module ProtectionMethods
-
1
class NullSession
-
1
def initialize(controller)
-
@controller = controller
-
end
-
-
# This is the method that defines the application behavior when a request is found to be unverified.
-
1
def handle_unverified_request
-
request = @controller.request
-
request.session = NullSessionHash.new(request.env)
-
request.env['action_dispatch.request.flash_hash'] = nil
-
request.env['rack.session.options'] = { skip: true }
-
request.env['action_dispatch.cookies'] = NullCookieJar.build(request)
-
end
-
-
1
protected
-
-
1
class NullSessionHash < Rack::Session::Abstract::SessionHash #:nodoc:
-
1
def initialize(env)
-
super(nil, env)
-
@data = {}
-
@loaded = true
-
end
-
-
# no-op
-
1
def destroy; end
-
-
1
def exists?
-
true
-
end
-
end
-
-
1
class NullCookieJar < ActionDispatch::Cookies::CookieJar #:nodoc:
-
1
def self.build(request)
-
key_generator = request.env[ActionDispatch::Cookies::GENERATOR_KEY]
-
host = request.host
-
secure = request.ssl?
-
-
new(key_generator, host, secure, options_for_env({}))
-
end
-
-
1
def write(*)
-
# nothing
-
end
-
end
-
end
-
-
1
class ResetSession
-
1
def initialize(controller)
-
@controller = controller
-
end
-
-
1
def handle_unverified_request
-
@controller.reset_session
-
end
-
end
-
-
1
class Exception
-
1
def initialize(controller)
-
@controller = controller
-
end
-
-
1
def handle_unverified_request
-
raise ActionController::InvalidAuthenticityToken
-
end
-
end
-
end
-
-
1
protected
-
# The actual before_action that is used to verify the CSRF token.
-
# Don't override this directly. Provide your own forgery protection
-
# strategy instead. If you override, you'll disable same-origin
-
# `<script>` verification.
-
#
-
# Lean on the protect_from_forgery declaration to mark which actions are
-
# due for same-origin request verification. If protect_from_forgery is
-
# enabled on an action, this before_action flags its after_action to
-
# verify that JavaScript responses are for XHR requests, ensuring they
-
# follow the browser's same-origin policy.
-
1
def verify_authenticity_token
-
mark_for_same_origin_verification!
-
-
if !verified_request?
-
logger.warn "Can't verify CSRF token authenticity" if logger
-
handle_unverified_request
-
end
-
end
-
-
1
def handle_unverified_request
-
forgery_protection_strategy.new(self).handle_unverified_request
-
end
-
-
1
CROSS_ORIGIN_JAVASCRIPT_WARNING = "Security warning: an embedded " \
-
"<script> tag on another site requested protected JavaScript. " \
-
"If you know what you're doing, go ahead and disable forgery " \
-
"protection on this action to permit cross-origin JavaScript embedding."
-
1
private_constant :CROSS_ORIGIN_JAVASCRIPT_WARNING
-
-
# If `verify_authenticity_token` was run (indicating that we have
-
# forgery protection enabled for this request) then also verify that
-
# we aren't serving an unauthorized cross-origin response.
-
1
def verify_same_origin_request
-
if marked_for_same_origin_verification? && non_xhr_javascript_response?
-
logger.warn CROSS_ORIGIN_JAVASCRIPT_WARNING if logger
-
raise ActionController::InvalidCrossOriginRequest, CROSS_ORIGIN_JAVASCRIPT_WARNING
-
end
-
end
-
-
# GET requests are checked for cross-origin JavaScript after rendering.
-
1
def mark_for_same_origin_verification!
-
@marked_for_same_origin_verification = request.get?
-
end
-
-
# If the `verify_authenticity_token` before_action ran, verify that
-
# JavaScript responses are only served to same-origin GET requests.
-
1
def marked_for_same_origin_verification?
-
@marked_for_same_origin_verification ||= false
-
end
-
-
# Check for cross-origin JavaScript responses.
-
1
def non_xhr_javascript_response?
-
content_type =~ %r(\Atext/javascript) && !request.xhr?
-
end
-
-
# Returns true or false if a request is verified. Checks:
-
#
-
# * is it a GET or HEAD request? Gets should be safe and idempotent
-
# * Does the form_authenticity_token match the given token value from the params?
-
# * Does the X-CSRF-Token header match the form_authenticity_token
-
1
def verified_request?
-
!protect_against_forgery? || request.get? || request.head? ||
-
form_authenticity_token == params[request_forgery_protection_token] ||
-
form_authenticity_token == request.headers['X-CSRF-Token']
-
end
-
-
# Sets the token value for the current session.
-
1
def form_authenticity_token
-
session[:_csrf_token] ||= SecureRandom.base64(32)
-
end
-
-
# The form's authenticity parameter. Override to provide your own.
-
1
def form_authenticity_param
-
params[request_forgery_protection_token]
-
end
-
-
# Checks if the controller allows forgery protection.
-
1
def protect_against_forgery?
-
allow_forgery_protection
-
end
-
end
-
end
-
1
module ActionController #:nodoc:
-
# This module is responsible to provide `rescue_from` helpers
-
# to controllers and configure when detailed exceptions must be
-
# shown.
-
1
module Rescue
-
1
extend ActiveSupport::Concern
-
1
include ActiveSupport::Rescuable
-
-
1
def rescue_with_handler(exception)
-
if (exception.respond_to?(:original_exception) &&
-
(orig_exception = exception.original_exception) &&
-
handler_for_rescue(orig_exception))
-
exception = orig_exception
-
end
-
super(exception)
-
end
-
-
# Override this method if you want to customize when detailed
-
# exceptions must be shown. This method is only called when
-
# consider_all_requests_local is false. By default, it returns
-
# false, but someone may set it to `request.local?` so local
-
# requests in production still shows the detailed exception pages.
-
1
def show_detailed_exceptions?
-
false
-
end
-
-
1
private
-
1
def process_action(*args)
-
super
-
rescue Exception => exception
-
request.env['action_dispatch.show_detailed_exceptions'] ||= show_detailed_exceptions?
-
rescue_with_handler(exception) || raise(exception)
-
end
-
end
-
end
-
1
require 'active_support/json'
-
-
1
module ActionController #:nodoc:
-
# Responsible for exposing a resource to different mime requests,
-
# usually depending on the HTTP verb. The responder is triggered when
-
# <code>respond_with</code> is called. The simplest case to study is a GET request:
-
#
-
# class PeopleController < ApplicationController
-
# respond_to :html, :xml, :json
-
#
-
# def index
-
# @people = Person.all
-
# respond_with(@people)
-
# end
-
# end
-
#
-
# When a request comes in, for example for an XML response, three steps happen:
-
#
-
# 1) the responder searches for a template at people/index.xml;
-
#
-
# 2) if the template is not available, it will invoke <code>#to_xml</code> on the given resource;
-
#
-
# 3) if the responder does not <code>respond_to :to_xml</code>, call <code>#to_format</code> on it.
-
#
-
# === Builtin HTTP verb semantics
-
#
-
# The default \Rails responder holds semantics for each HTTP verb. Depending on the
-
# content type, verb and the resource status, it will behave differently.
-
#
-
# Using \Rails default responder, a POST request for creating an object could
-
# be written as:
-
#
-
# def create
-
# @user = User.new(params[:user])
-
# flash[:notice] = 'User was successfully created.' if @user.save
-
# respond_with(@user)
-
# end
-
#
-
# Which is exactly the same as:
-
#
-
# def create
-
# @user = User.new(params[:user])
-
#
-
# respond_to do |format|
-
# if @user.save
-
# flash[:notice] = 'User was successfully created.'
-
# format.html { redirect_to(@user) }
-
# format.xml { render xml: @user, status: :created, location: @user }
-
# else
-
# format.html { render action: "new" }
-
# format.xml { render xml: @user.errors, status: :unprocessable_entity }
-
# end
-
# end
-
# end
-
#
-
# The same happens for PATCH/PUT and DELETE requests.
-
#
-
# === Nested resources
-
#
-
# You can supply nested resources as you do in <code>form_for</code> and <code>polymorphic_url</code>.
-
# Consider the project has many tasks example. The create action for
-
# TasksController would be like:
-
#
-
# def create
-
# @project = Project.find(params[:project_id])
-
# @task = @project.tasks.build(params[:task])
-
# flash[:notice] = 'Task was successfully created.' if @task.save
-
# respond_with(@project, @task)
-
# end
-
#
-
# Giving several resources ensures that the responder will redirect to
-
# <code>project_task_url</code> instead of <code>task_url</code>.
-
#
-
# Namespaced and singleton resources require a symbol to be given, as in
-
# polymorphic urls. If a project has one manager which has many tasks, it
-
# should be invoked as:
-
#
-
# respond_with(@project, :manager, @task)
-
#
-
# Note that if you give an array, it will be treated as a collection,
-
# so the following is not equivalent:
-
#
-
# respond_with [@project, :manager, @task]
-
#
-
# === Custom options
-
#
-
# <code>respond_with</code> also allows you to pass options that are forwarded
-
# to the underlying render call. Those options are only applied for success
-
# scenarios. For instance, you can do the following in the create method above:
-
#
-
# def create
-
# @project = Project.find(params[:project_id])
-
# @task = @project.tasks.build(params[:task])
-
# flash[:notice] = 'Task was successfully created.' if @task.save
-
# respond_with(@project, @task, status: 201)
-
# end
-
#
-
# This will return status 201 if the task was saved successfully. If not,
-
# it will simply ignore the given options and return status 422 and the
-
# resource errors. You can also override the location to redirect to:
-
#
-
# respond_with(@project, location: root_path)
-
#
-
# To customize the failure scenario, you can pass a block to
-
# <code>respond_with</code>:
-
#
-
# def create
-
# @project = Project.find(params[:project_id])
-
# @task = @project.tasks.build(params[:task])
-
# respond_with(@project, @task, status: 201) do |format|
-
# if @task.save
-
# flash[:notice] = 'Task was successfully created.'
-
# else
-
# format.html { render "some_special_template" }
-
# end
-
# end
-
# end
-
#
-
# Using <code>respond_with</code> with a block follows the same syntax as <code>respond_to</code>.
-
1
class Responder
-
1
attr_reader :controller, :request, :format, :resource, :resources, :options
-
-
1
DEFAULT_ACTIONS_FOR_VERBS = {
-
:post => :new,
-
:patch => :edit,
-
:put => :edit
-
}
-
-
1
def initialize(controller, resources, options={})
-
@controller = controller
-
@request = @controller.request
-
@format = @controller.formats.first
-
@resource = resources.last
-
@resources = resources
-
@options = options
-
@action = options.delete(:action)
-
@default_response = options.delete(:default_response)
-
end
-
-
1
delegate :head, :render, :redirect_to, :to => :controller
-
1
delegate :get?, :post?, :patch?, :put?, :delete?, :to => :request
-
-
# Undefine :to_json and :to_yaml since it's defined on Object
-
1
undef_method(:to_json) if method_defined?(:to_json)
-
1
undef_method(:to_yaml) if method_defined?(:to_yaml)
-
-
# Initializes a new responder and invokes the proper format. If the format is
-
# not defined, call to_format.
-
#
-
1
def self.call(*args)
-
new(*args).respond
-
end
-
-
# Main entry point for responder responsible to dispatch to the proper format.
-
#
-
1
def respond
-
method = "to_#{format}"
-
respond_to?(method) ? send(method) : to_format
-
end
-
-
# HTML format does not render the resource, it always attempt to render a
-
# template.
-
#
-
1
def to_html
-
default_render
-
rescue ActionView::MissingTemplate => e
-
navigation_behavior(e)
-
end
-
-
# to_js simply tries to render a template. If no template is found, raises the error.
-
1
def to_js
-
default_render
-
end
-
-
# All other formats follow the procedure below. First we try to render a
-
# template, if the template is not available, we verify if the resource
-
# responds to :to_format and display it.
-
#
-
1
def to_format
-
if get? || !has_errors? || response_overridden?
-
default_render
-
else
-
display_errors
-
end
-
rescue ActionView::MissingTemplate => e
-
api_behavior(e)
-
end
-
-
1
protected
-
-
# This is the common behavior for formats associated with browsing, like :html, :iphone and so forth.
-
1
def navigation_behavior(error)
-
if get?
-
raise error
-
elsif has_errors? && default_action
-
render :action => default_action
-
else
-
redirect_to navigation_location
-
end
-
end
-
-
# This is the common behavior for formats associated with APIs, such as :xml and :json.
-
1
def api_behavior(error)
-
raise error unless resourceful?
-
raise MissingRenderer.new(format) unless has_renderer?
-
-
if get?
-
display resource
-
elsif post?
-
display resource, :status => :created, :location => api_location
-
else
-
head :no_content
-
end
-
end
-
-
# Checks whether the resource responds to the current format or not.
-
#
-
1
def resourceful?
-
resource.respond_to?("to_#{format}")
-
end
-
-
# Returns the resource location by retrieving it from the options or
-
# returning the resources array.
-
#
-
1
def resource_location
-
options[:location] || resources
-
end
-
1
alias :navigation_location :resource_location
-
1
alias :api_location :resource_location
-
-
# If a response block was given, use it, otherwise call render on
-
# controller.
-
#
-
1
def default_render
-
if @default_response
-
@default_response.call(options)
-
else
-
controller.default_render(options)
-
end
-
end
-
-
# Display is just a shortcut to render a resource with the current format.
-
#
-
# display @user, status: :ok
-
#
-
# For XML requests it's equivalent to:
-
#
-
# render xml: @user, status: :ok
-
#
-
# Options sent by the user are also used:
-
#
-
# respond_with(@user, status: :created)
-
# display(@user, status: :ok)
-
#
-
# Results in:
-
#
-
# render xml: @user, status: :created
-
#
-
1
def display(resource, given_options={})
-
controller.render given_options.merge!(options).merge!(format => resource)
-
end
-
-
1
def display_errors
-
controller.render format => resource_errors, :status => :unprocessable_entity
-
end
-
-
# Check whether the resource has errors.
-
#
-
1
def has_errors?
-
resource.respond_to?(:errors) && !resource.errors.empty?
-
end
-
-
# Check whether the necessary Renderer is available
-
1
def has_renderer?
-
Renderers::RENDERERS.include?(format)
-
end
-
-
# By default, render the <code>:edit</code> action for HTML requests with errors, unless
-
# the verb was POST.
-
#
-
1
def default_action
-
@action ||= DEFAULT_ACTIONS_FOR_VERBS[request.request_method_symbol]
-
end
-
-
1
def resource_errors
-
respond_to?("#{format}_resource_errors", true) ? send("#{format}_resource_errors") : resource.errors
-
end
-
-
1
def json_resource_errors
-
{:errors => resource.errors}
-
end
-
-
1
def response_overridden?
-
@default_response.present?
-
end
-
end
-
end
-
1
require 'rack/chunked'
-
-
1
module ActionController #:nodoc:
-
# Allows views to be streamed back to the client as they are rendered.
-
#
-
# The default way Rails renders views is by first rendering the template
-
# and then the layout. The response is sent to the client after the whole
-
# template is rendered, all queries are made, and the layout is processed.
-
#
-
# Streaming inverts the rendering flow by rendering the layout first and
-
# streaming each part of the layout as they are processed. This allows the
-
# header of the HTML (which is usually in the layout) to be streamed back
-
# to client very quickly, allowing JavaScripts and stylesheets to be loaded
-
# earlier than usual.
-
#
-
# This approach was introduced in Rails 3.1 and is still improving. Several
-
# Rack middlewares may not work and you need to be careful when streaming.
-
# Those points are going to be addressed soon.
-
#
-
# In order to use streaming, you will need to use a Ruby version that
-
# supports fibers (fibers are supported since version 1.9.2 of the main
-
# Ruby implementation).
-
#
-
# Streaming can be added to a given template easily, all you need to do is
-
# to pass the :stream option.
-
#
-
# class PostsController
-
# def index
-
# @posts = Post.all
-
# render stream: true
-
# end
-
# end
-
#
-
# == When to use streaming
-
#
-
# Streaming may be considered to be overkill for lightweight actions like
-
# +new+ or +edit+. The real benefit of streaming is on expensive actions
-
# that, for example, do a lot of queries on the database.
-
#
-
# In such actions, you want to delay queries execution as much as you can.
-
# For example, imagine the following +dashboard+ action:
-
#
-
# def dashboard
-
# @posts = Post.all
-
# @pages = Page.all
-
# @articles = Article.all
-
# end
-
#
-
# Most of the queries here are happening in the controller. In order to benefit
-
# from streaming you would want to rewrite it as:
-
#
-
# def dashboard
-
# # Allow lazy execution of the queries
-
# @posts = Post.all
-
# @pages = Page.all
-
# @articles = Article.all
-
# render stream: true
-
# end
-
#
-
# Notice that :stream only works with templates. Rendering :json
-
# or :xml with :stream won't work.
-
#
-
# == Communication between layout and template
-
#
-
# When streaming, rendering happens top-down instead of inside-out.
-
# Rails starts with the layout, and the template is rendered later,
-
# when its +yield+ is reached.
-
#
-
# This means that, if your application currently relies on instance
-
# variables set in the template to be used in the layout, they won't
-
# work once you move to streaming. The proper way to communicate
-
# between layout and template, regardless of whether you use streaming
-
# or not, is by using +content_for+, +provide+ and +yield+.
-
#
-
# Take a simple example where the layout expects the template to tell
-
# which title to use:
-
#
-
# <html>
-
# <head><title><%= yield :title %></title></head>
-
# <body><%= yield %></body>
-
# </html>
-
#
-
# You would use +content_for+ in your template to specify the title:
-
#
-
# <%= content_for :title, "Main" %>
-
# Hello
-
#
-
# And the final result would be:
-
#
-
# <html>
-
# <head><title>Main</title></head>
-
# <body>Hello</body>
-
# </html>
-
#
-
# However, if +content_for+ is called several times, the final result
-
# would have all calls concatenated. For instance, if we have the following
-
# template:
-
#
-
# <%= content_for :title, "Main" %>
-
# Hello
-
# <%= content_for :title, " page" %>
-
#
-
# The final result would be:
-
#
-
# <html>
-
# <head><title>Main page</title></head>
-
# <body>Hello</body>
-
# </html>
-
#
-
# This means that, if you have <code>yield :title</code> in your layout
-
# and you want to use streaming, you would have to render the whole template
-
# (and eventually trigger all queries) before streaming the title and all
-
# assets, which kills the purpose of streaming. For this reason Rails 3.1
-
# introduces a new helper called +provide+ that does the same as +content_for+
-
# but tells the layout to stop searching for other entries and continue rendering.
-
#
-
# For instance, the template above using +provide+ would be:
-
#
-
# <%= provide :title, "Main" %>
-
# Hello
-
# <%= content_for :title, " page" %>
-
#
-
# Giving:
-
#
-
# <html>
-
# <head><title>Main</title></head>
-
# <body>Hello</body>
-
# </html>
-
#
-
# That said, when streaming, you need to properly check your templates
-
# and choose when to use +provide+ and +content_for+.
-
#
-
# == Headers, cookies, session and flash
-
#
-
# When streaming, the HTTP headers are sent to the client right before
-
# it renders the first line. This means that, modifying headers, cookies,
-
# session or flash after the template starts rendering will not propagate
-
# to the client.
-
#
-
# == Middlewares
-
#
-
# Middlewares that need to manipulate the body won't work with streaming.
-
# You should disable those middlewares whenever streaming in development
-
# or production. For instance, <tt>Rack::Bug</tt> won't work when streaming as it
-
# needs to inject contents in the HTML body.
-
#
-
# Also <tt>Rack::Cache</tt> won't work with streaming as it does not support
-
# streaming bodies yet. Whenever streaming Cache-Control is automatically
-
# set to "no-cache".
-
#
-
# == Errors
-
#
-
# When it comes to streaming, exceptions get a bit more complicated. This
-
# happens because part of the template was already rendered and streamed to
-
# the client, making it impossible to render a whole exception page.
-
#
-
# Currently, when an exception happens in development or production, Rails
-
# will automatically stream to the client:
-
#
-
# "><script>window.location = "/500.html"</script></html>
-
#
-
# The first two characters (">) are required in case the exception happens
-
# while rendering attributes for a given tag. You can check the real cause
-
# for the exception in your logger.
-
#
-
# == Web server support
-
#
-
# Not all web servers support streaming out-of-the-box. You need to check
-
# the instructions for each of them.
-
#
-
# ==== Unicorn
-
#
-
# Unicorn supports streaming but it needs to be configured. For this, you
-
# need to create a config file as follow:
-
#
-
# # unicorn.config.rb
-
# listen 3000, tcp_nopush: false
-
#
-
# And use it on initialization:
-
#
-
# unicorn_rails --config-file unicorn.config.rb
-
#
-
# You may also want to configure other parameters like <tt>:tcp_nodelay</tt>.
-
# Please check its documentation for more information: http://unicorn.bogomips.org/Unicorn/Configurator.html#method-i-listen
-
#
-
# If you are using Unicorn with Nginx, you may need to tweak Nginx.
-
# Streaming should work out of the box on Rainbows.
-
#
-
# ==== Passenger
-
#
-
# To be described.
-
#
-
1
module Streaming
-
1
extend ActiveSupport::Concern
-
-
1
protected
-
-
# Set proper cache control and transfer encoding when streaming
-
1
def _process_options(options) #:nodoc:
-
super
-
if options[:stream]
-
if env["HTTP_VERSION"] == "HTTP/1.0"
-
options.delete(:stream)
-
else
-
headers["Cache-Control"] ||= "no-cache"
-
headers["Transfer-Encoding"] = "chunked"
-
headers.delete("Content-Length")
-
end
-
end
-
end
-
-
# Call render_body if we are streaming instead of usual +render+.
-
1
def _render_template(options) #:nodoc:
-
if options.delete(:stream)
-
Rack::Chunked::Body.new view_renderer.render_body(view_context, options)
-
else
-
super
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/indifferent_access'
-
1
require 'active_support/core_ext/array/wrap'
-
1
require 'active_support/rescuable'
-
1
require 'action_dispatch/http/upload'
-
1
require 'stringio'
-
1
require 'set'
-
-
1
module ActionController
-
# Raised when a required parameter is missing.
-
#
-
# params = ActionController::Parameters.new(a: {})
-
# params.fetch(:b)
-
# # => ActionController::ParameterMissing: param not found: b
-
# params.require(:a)
-
# # => ActionController::ParameterMissing: param not found: a
-
1
class ParameterMissing < KeyError
-
1
attr_reader :param # :nodoc:
-
-
1
def initialize(param) # :nodoc:
-
@param = param
-
super("param is missing or the value is empty: #{param}")
-
end
-
end
-
-
# Raised when a supplied parameter is not expected.
-
#
-
# params = ActionController::Parameters.new(a: "123", b: "456")
-
# params.permit(:c)
-
# # => ActionController::UnpermittedParameters: found unexpected keys: a, b
-
1
class UnpermittedParameters < IndexError
-
1
attr_reader :params # :nodoc:
-
-
1
def initialize(params) # :nodoc:
-
@params = params
-
super("found unpermitted parameters: #{params.join(", ")}")
-
end
-
end
-
-
# == Action Controller \Parameters
-
#
-
# Allows to choose which attributes should be whitelisted for mass updating
-
# and thus prevent accidentally exposing that which shouldn’t be exposed.
-
# Provides two methods for this purpose: #require and #permit. The former is
-
# used to mark parameters as required. The latter is used to set the parameter
-
# as permitted and limit which attributes should be allowed for mass updating.
-
#
-
# params = ActionController::Parameters.new({
-
# person: {
-
# name: 'Francesco',
-
# age: 22,
-
# role: 'admin'
-
# }
-
# })
-
#
-
# permitted = params.require(:person).permit(:name, :age)
-
# permitted # => {"name"=>"Francesco", "age"=>22}
-
# permitted.class # => ActionController::Parameters
-
# permitted.permitted? # => true
-
#
-
# Person.first.update!(permitted)
-
# # => #<Person id: 1, name: "Francesco", age: 22, role: "user">
-
#
-
# It provides two options that controls the top-level behavior of new instances:
-
#
-
# * +permit_all_parameters+ - If it's +true+, all the parameters will be
-
# permitted by default. The default is +false+.
-
# * +action_on_unpermitted_parameters+ - Allow to control the behavior when parameters
-
# that are not explicitly permitted are found. The values can be <tt>:log</tt> to
-
# write a message on the logger or <tt>:raise</tt> to raise
-
# ActionController::UnpermittedParameters exception. The default value is <tt>:log</tt>
-
# in test and development environments, +false+ otherwise.
-
#
-
# Examples:
-
#
-
# params = ActionController::Parameters.new
-
# params.permitted? # => false
-
#
-
# ActionController::Parameters.permit_all_parameters = true
-
#
-
# params = ActionController::Parameters.new
-
# params.permitted? # => true
-
#
-
# params = ActionController::Parameters.new(a: "123", b: "456")
-
# params.permit(:c)
-
# # => {}
-
#
-
# ActionController::Parameters.action_on_unpermitted_parameters = :raise
-
#
-
# params = ActionController::Parameters.new(a: "123", b: "456")
-
# params.permit(:c)
-
# # => ActionController::UnpermittedParameters: found unpermitted keys: a, b
-
#
-
# <tt>ActionController::Parameters</tt> is inherited from
-
# <tt>ActiveSupport::HashWithIndifferentAccess</tt>, this means
-
# that you can fetch values using either <tt>:key</tt> or <tt>"key"</tt>.
-
#
-
# params = ActionController::Parameters.new(key: 'value')
-
# params[:key] # => "value"
-
# params["key"] # => "value"
-
1
class Parameters < ActiveSupport::HashWithIndifferentAccess
-
1
cattr_accessor :permit_all_parameters, instance_accessor: false
-
1
cattr_accessor :action_on_unpermitted_parameters, instance_accessor: false
-
-
# Never raise an UnpermittedParameters exception because of these params
-
# are present. They are added by Rails and it's of no concern.
-
1
NEVER_UNPERMITTED_PARAMS = %w( controller action )
-
-
# Returns a new instance of <tt>ActionController::Parameters</tt>.
-
# Also, sets the +permitted+ attribute to the default value of
-
# <tt>ActionController::Parameters.permit_all_parameters</tt>.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# params = ActionController::Parameters.new(name: 'Francesco')
-
# params.permitted? # => false
-
# Person.new(params) # => ActiveModel::ForbiddenAttributesError
-
#
-
# ActionController::Parameters.permit_all_parameters = true
-
#
-
# params = ActionController::Parameters.new(name: 'Francesco')
-
# params.permitted? # => true
-
# Person.new(params) # => #<Person id: nil, name: "Francesco">
-
1
def initialize(attributes = nil)
-
super(attributes)
-
@permitted = self.class.permit_all_parameters
-
end
-
-
# Attribute that keeps track of converted arrays, if any, to avoid double
-
# looping in the common use case permit + mass-assignment. Defined in a
-
# method to instantiate it only if needed.
-
1
def converted_arrays
-
@converted_arrays ||= Set.new
-
end
-
-
# Returns +true+ if the parameter is permitted, +false+ otherwise.
-
#
-
# params = ActionController::Parameters.new
-
# params.permitted? # => false
-
# params.permit!
-
# params.permitted? # => true
-
1
def permitted?
-
@permitted
-
end
-
-
# Sets the +permitted+ attribute to +true+. This can be used to pass
-
# mass assignment. Returns +self+.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# params = ActionController::Parameters.new(name: 'Francesco')
-
# params.permitted? # => false
-
# Person.new(params) # => ActiveModel::ForbiddenAttributesError
-
# params.permit!
-
# params.permitted? # => true
-
# Person.new(params) # => #<Person id: nil, name: "Francesco">
-
1
def permit!
-
each_pair do |key, value|
-
value = convert_hashes_to_parameters(key, value)
-
Array.wrap(value).each do |_|
-
_.permit! if _.respond_to? :permit!
-
end
-
end
-
-
@permitted = true
-
self
-
end
-
-
# Ensures that a parameter is present. If it's present, returns
-
# the parameter at the given +key+, otherwise raises an
-
# <tt>ActionController::ParameterMissing</tt> error.
-
#
-
# ActionController::Parameters.new(person: { name: 'Francesco' }).require(:person)
-
# # => {"name"=>"Francesco"}
-
#
-
# ActionController::Parameters.new(person: nil).require(:person)
-
# # => ActionController::ParameterMissing: param not found: person
-
#
-
# ActionController::Parameters.new(person: {}).require(:person)
-
# # => ActionController::ParameterMissing: param not found: person
-
1
def require(key)
-
self[key].presence || raise(ParameterMissing.new(key))
-
end
-
-
# Alias of #require.
-
1
alias :required :require
-
-
# Returns a new <tt>ActionController::Parameters</tt> instance that
-
# includes only the given +filters+ and sets the +permitted+ attribute
-
# for the object to +true+. This is useful for limiting which attributes
-
# should be allowed for mass updating.
-
#
-
# params = ActionController::Parameters.new(user: { name: 'Francesco', age: 22, role: 'admin' })
-
# permitted = params.require(:user).permit(:name, :age)
-
# permitted.permitted? # => true
-
# permitted.has_key?(:name) # => true
-
# permitted.has_key?(:age) # => true
-
# permitted.has_key?(:role) # => false
-
#
-
# Only permitted scalars pass the filter. For example, given
-
#
-
# params.permit(:name)
-
#
-
# +:name+ passes it is a key of +params+ whose associated value is of type
-
# +String+, +Symbol+, +NilClass+, +Numeric+, +TrueClass+, +FalseClass+,
-
# +Date+, +Time+, +DateTime+, +StringIO+, +IO+,
-
# +ActionDispatch::Http::UploadedFile+ or +Rack::Test::UploadedFile+.
-
# Otherwise, the key +:name+ is filtered out.
-
#
-
# You may declare that the parameter should be an array of permitted scalars
-
# by mapping it to an empty array:
-
#
-
# params = ActionController::Parameters.new(tags: ['rails', 'parameters'])
-
# params.permit(tags: [])
-
#
-
# You can also use +permit+ on nested parameters, like:
-
#
-
# params = ActionController::Parameters.new({
-
# person: {
-
# name: 'Francesco',
-
# age: 22,
-
# pets: [{
-
# name: 'Purplish',
-
# category: 'dogs'
-
# }]
-
# }
-
# })
-
#
-
# permitted = params.permit(person: [ :name, { pets: :name } ])
-
# permitted.permitted? # => true
-
# permitted[:person][:name] # => "Francesco"
-
# permitted[:person][:age] # => nil
-
# permitted[:person][:pets][0][:name] # => "Purplish"
-
# permitted[:person][:pets][0][:category] # => nil
-
#
-
# Note that if you use +permit+ in a key that points to a hash,
-
# it won't allow all the hash. You also need to specify which
-
# attributes inside the hash should be whitelisted.
-
#
-
# params = ActionController::Parameters.new({
-
# person: {
-
# contact: {
-
# email: 'none@test.com',
-
# phone: '555-1234'
-
# }
-
# }
-
# })
-
#
-
# params.require(:person).permit(:contact)
-
# # => {}
-
#
-
# params.require(:person).permit(contact: :phone)
-
# # => {"contact"=>{"phone"=>"555-1234"}}
-
#
-
# params.require(:person).permit(contact: [ :email, :phone ])
-
# # => {"contact"=>{"email"=>"none@test.com", "phone"=>"555-1234"}}
-
1
def permit(*filters)
-
params = self.class.new
-
-
filters.flatten.each do |filter|
-
case filter
-
when Symbol, String
-
permitted_scalar_filter(params, filter)
-
when Hash then
-
hash_filter(params, filter)
-
end
-
end
-
-
unpermitted_parameters!(params) if self.class.action_on_unpermitted_parameters
-
-
params.permit!
-
end
-
-
# Returns a parameter for the given +key+. If not found,
-
# returns +nil+.
-
#
-
# params = ActionController::Parameters.new(person: { name: 'Francesco' })
-
# params[:person] # => {"name"=>"Francesco"}
-
# params[:none] # => nil
-
1
def [](key)
-
convert_hashes_to_parameters(key, super)
-
end
-
-
# Returns a parameter for the given +key+. If the +key+
-
# can't be found, there are several options: With no other arguments,
-
# it will raise an <tt>ActionController::ParameterMissing</tt> error;
-
# if more arguments are given, then that will be returned; if a block
-
# is given, then that will be run and its result returned.
-
#
-
# params = ActionController::Parameters.new(person: { name: 'Francesco' })
-
# params.fetch(:person) # => {"name"=>"Francesco"}
-
# params.fetch(:none) # => ActionController::ParameterMissing: param not found: none
-
# params.fetch(:none, 'Francesco') # => "Francesco"
-
# params.fetch(:none) { 'Francesco' } # => "Francesco"
-
1
def fetch(key, *args)
-
convert_hashes_to_parameters(key, super, false)
-
rescue KeyError
-
raise ActionController::ParameterMissing.new(key)
-
end
-
-
# Returns a new <tt>ActionController::Parameters</tt> instance that
-
# includes only the given +keys+. If the given +keys+
-
# don't exist, returns an empty hash.
-
#
-
# params = ActionController::Parameters.new(a: 1, b: 2, c: 3)
-
# params.slice(:a, :b) # => {"a"=>1, "b"=>2}
-
# params.slice(:d) # => {}
-
1
def slice(*keys)
-
self.class.new(super).tap do |new_instance|
-
new_instance.permitted = @permitted
-
end
-
end
-
-
# Returns an exact copy of the <tt>ActionController::Parameters</tt>
-
# instance. +permitted+ state is kept on the duped object.
-
#
-
# params = ActionController::Parameters.new(a: 1)
-
# params.permit!
-
# params.permitted? # => true
-
# copy_params = params.dup # => {"a"=>1}
-
# copy_params.permitted? # => true
-
1
def dup
-
super.tap do |duplicate|
-
duplicate.permitted = @permitted
-
end
-
end
-
-
1
protected
-
1
def permitted=(new_permitted)
-
@permitted = new_permitted
-
end
-
-
1
private
-
1
def convert_hashes_to_parameters(key, value, assign_if_converted=true)
-
converted = convert_value_to_parameters(value)
-
self[key] = converted if assign_if_converted && !converted.equal?(value)
-
converted
-
end
-
-
1
def convert_value_to_parameters(value)
-
if value.is_a?(Array) && !converted_arrays.member?(value)
-
converted = value.map { |_| convert_value_to_parameters(_) }
-
converted_arrays << converted
-
converted
-
elsif value.is_a?(Parameters) || !value.is_a?(Hash)
-
value
-
else
-
self.class.new(value)
-
end
-
end
-
-
1
def each_element(object)
-
if object.is_a?(Array)
-
object.map { |el| yield el }.compact
-
elsif fields_for_style?(object)
-
hash = object.class.new
-
object.each { |k,v| hash[k] = yield v }
-
hash
-
else
-
yield object
-
end
-
end
-
-
1
def fields_for_style?(object)
-
object.is_a?(Hash) && object.all? { |k, v| k =~ /\A-?\d+\z/ && v.is_a?(Hash) }
-
end
-
-
1
def unpermitted_parameters!(params)
-
unpermitted_keys = unpermitted_keys(params)
-
if unpermitted_keys.any?
-
case self.class.action_on_unpermitted_parameters
-
when :log
-
name = "unpermitted_parameters.action_controller"
-
ActiveSupport::Notifications.instrument(name, keys: unpermitted_keys)
-
when :raise
-
raise ActionController::UnpermittedParameters.new(unpermitted_keys)
-
end
-
end
-
end
-
-
1
def unpermitted_keys(params)
-
self.keys - params.keys - NEVER_UNPERMITTED_PARAMS
-
end
-
-
#
-
# --- Filtering ----------------------------------------------------------
-
#
-
-
# This is a white list of permitted scalar types that includes the ones
-
# supported in XML and JSON requests.
-
#
-
# This list is in particular used to filter ordinary requests, String goes
-
# as first element to quickly short-circuit the common case.
-
#
-
# If you modify this collection please update the API of +permit+ above.
-
1
PERMITTED_SCALAR_TYPES = [
-
String,
-
Symbol,
-
NilClass,
-
Numeric,
-
TrueClass,
-
FalseClass,
-
Date,
-
Time,
-
# DateTimes are Dates, we document the type but avoid the redundant check.
-
StringIO,
-
IO,
-
ActionDispatch::Http::UploadedFile,
-
Rack::Test::UploadedFile,
-
]
-
-
1
def permitted_scalar?(value)
-
PERMITTED_SCALAR_TYPES.any? {|type| value.is_a?(type)}
-
end
-
-
1
def permitted_scalar_filter(params, key)
-
if has_key?(key) && permitted_scalar?(self[key])
-
params[key] = self[key]
-
end
-
-
keys.grep(/\A#{Regexp.escape(key)}\(\d+[if]?\)\z/) do |k|
-
if permitted_scalar?(self[k])
-
params[k] = self[k]
-
end
-
end
-
end
-
-
1
def array_of_permitted_scalars?(value)
-
if value.is_a?(Array)
-
value.all? {|element| permitted_scalar?(element)}
-
end
-
end
-
-
1
def array_of_permitted_scalars_filter(params, key)
-
if has_key?(key) && array_of_permitted_scalars?(self[key])
-
params[key] = self[key]
-
end
-
end
-
-
1
EMPTY_ARRAY = []
-
1
def hash_filter(params, filter)
-
filter = filter.with_indifferent_access
-
-
# Slicing filters out non-declared keys.
-
slice(*filter.keys).each do |key, value|
-
next unless value
-
-
if filter[key] == EMPTY_ARRAY
-
# Declaration { comment_ids: [] }.
-
array_of_permitted_scalars_filter(params, key)
-
else
-
# Declaration { user: :name } or { user: [:name, :age, { address: ... }] }.
-
params[key] = each_element(value) do |element|
-
if element.is_a?(Hash)
-
element = self.class.new(element) unless element.respond_to?(:permit)
-
element.permit(*Array.wrap(filter[key]))
-
end
-
end
-
end
-
end
-
end
-
end
-
-
# == Strong \Parameters
-
#
-
# It provides an interface for protecting attributes from end-user
-
# assignment. This makes Action Controller parameters forbidden
-
# to be used in Active Model mass assignment until they have been
-
# whitelisted.
-
#
-
# In addition, parameters can be marked as required and flow through a
-
# predefined raise/rescue flow to end up as a 400 Bad Request with no
-
# effort.
-
#
-
# class PeopleController < ActionController::Base
-
# # Using "Person.create(params[:person])" would raise an
-
# # ActiveModel::ForbiddenAttributes exception because it'd
-
# # be using mass assignment without an explicit permit step.
-
# # This is the recommended form:
-
# def create
-
# Person.create(person_params)
-
# end
-
#
-
# # This will pass with flying colors as long as there's a person key in the
-
# # parameters, otherwise it'll raise an ActionController::MissingParameter
-
# # exception, which will get caught by ActionController::Base and turned
-
# # into a 400 Bad Request reply.
-
# def update
-
# redirect_to current_account.people.find(params[:id]).tap { |person|
-
# person.update!(person_params)
-
# }
-
# end
-
#
-
# private
-
# # Using a private method to encapsulate the permissible parameters is
-
# # just a good pattern since you'll be able to reuse the same permit
-
# # list between create and update. Also, you can specialize this method
-
# # with per-user checking of permissible attributes.
-
# def person_params
-
# params.require(:person).permit(:name, :age)
-
# end
-
# end
-
#
-
# In order to use <tt>accepts_nested_attribute_for</tt> with Strong \Parameters, you
-
# will need to specify which nested attributes should be whitelisted.
-
#
-
# class Person
-
# has_many :pets
-
# accepts_nested_attributes_for :pets
-
# end
-
#
-
# class PeopleController < ActionController::Base
-
# def create
-
# Person.create(person_params)
-
# end
-
#
-
# ...
-
#
-
# private
-
#
-
# def person_params
-
# # It's mandatory to specify the nested attributes that should be whitelisted.
-
# # If you use `permit` with just the key that points to the nested attributes hash,
-
# # it will return an empty hash.
-
# params.require(:person).permit(:name, :age, pets_attributes: [ :name, :category ])
-
# end
-
# end
-
#
-
# See ActionController::Parameters.require and ActionController::Parameters.permit
-
# for more information.
-
1
module StrongParameters
-
1
extend ActiveSupport::Concern
-
1
include ActiveSupport::Rescuable
-
-
# Returns a new ActionController::Parameters object that
-
# has been instantiated with the <tt>request.parameters</tt>.
-
1
def params
-
@_params ||= Parameters.new(request.parameters)
-
end
-
-
# Assigns the given +value+ to the +params+ hash. If +value+
-
# is a Hash, this will create an ActionController::Parameters
-
# object that has been instantiated with the given +value+ hash.
-
1
def params=(value)
-
@_params = value.is_a?(Hash) ? Parameters.new(value) : value
-
end
-
end
-
end
-
1
module ActionController
-
# Includes +url_for+ into the host class. The class has to provide a +RouteSet+ by implementing
-
# the <tt>_routes</tt> method. Otherwise, an exception will be raised.
-
#
-
# In addition to <tt>AbstractController::UrlFor</tt>, this module accesses the HTTP layer to define
-
# url options like the +host+. In order to do so, this module requires the host class
-
# to implement +env+ and +request+, which need to be a Rack-compatible.
-
#
-
# class RootUrl
-
# include ActionController::UrlFor
-
# include Rails.application.routes.url_helpers
-
#
-
# delegate :env, :request, to: :controller
-
#
-
# def initialize(controller)
-
# @controller = controller
-
# @url = root_path # named route from the application.
-
# end
-
# end
-
1
module UrlFor
-
1
extend ActiveSupport::Concern
-
-
1
include AbstractController::UrlFor
-
-
1
def url_options
-
@_url_options ||= super.reverse_merge(
-
:host => request.host,
-
:port => request.optional_port,
-
:protocol => request.protocol,
-
:_recall => request.symbolized_path_parameters
-
).freeze
-
-
if (same_origin = _routes.equal?(env["action_dispatch.routes"])) ||
-
(script_name = env["ROUTES_#{_routes.object_id}_SCRIPT_NAME"]) ||
-
(original_script_name = env['ORIGINAL_SCRIPT_NAME'])
-
-
@_url_options.dup.tap do |options|
-
if original_script_name
-
options[:original_script_name] = original_script_name
-
else
-
options[:script_name] = same_origin ? request.script_name.dup : script_name
-
end
-
options.freeze
-
end
-
else
-
@_url_options
-
end
-
end
-
end
-
end
-
1
module ActionController
-
1
module ModelNaming
-
# Converts the given object to an ActiveModel compliant one.
-
1
def convert_to_model(object)
-
object.respond_to?(:to_model) ? object.to_model : object
-
end
-
-
1
def model_name_from_record_or_class(record_or_class)
-
(record_or_class.is_a?(Class) ? record_or_class : convert_to_model(record_or_class).class).model_name
-
end
-
end
-
end
-
1
require "rails"
-
1
require "action_controller"
-
1
require "action_dispatch/railtie"
-
1
require "abstract_controller/railties/routes_helpers"
-
1
require "action_controller/railties/helpers"
-
1
require "action_view/railtie"
-
-
1
module ActionController
-
1
class Railtie < Rails::Railtie #:nodoc:
-
1
config.action_controller = ActiveSupport::OrderedOptions.new
-
-
1
config.eager_load_namespaces << ActionController
-
-
1
initializer "action_controller.assets_config", :group => :all do |app|
-
1
app.config.action_controller.assets_dir ||= app.config.paths["public"].first
-
end
-
-
1
initializer "action_controller.set_helpers_path" do |app|
-
1
ActionController::Helpers.helpers_path = app.helpers_paths
-
end
-
-
1
initializer "action_controller.parameters_config" do |app|
-
1
options = app.config.action_controller
-
-
2
ActionController::Parameters.permit_all_parameters = options.delete(:permit_all_parameters) { false }
-
1
ActionController::Parameters.action_on_unpermitted_parameters = options.delete(:action_on_unpermitted_parameters) do
-
1
(Rails.env.test? || Rails.env.development?) ? :log : false
-
end
-
end
-
-
1
initializer "action_controller.set_configs" do |app|
-
1
paths = app.config.paths
-
1
options = app.config.action_controller
-
-
1
options.logger ||= Rails.logger
-
1
options.cache_store ||= Rails.cache
-
-
1
options.javascripts_dir ||= paths["public/javascripts"].first
-
1
options.stylesheets_dir ||= paths["public/stylesheets"].first
-
-
# Ensure readers methods get compiled
-
1
options.asset_host ||= app.config.asset_host
-
1
options.relative_url_root ||= app.config.relative_url_root
-
-
1
ActiveSupport.on_load(:action_controller) do
-
1
include app.routes.mounted_helpers
-
1
extend ::AbstractController::Railties::RoutesHelpers.with(app.routes)
-
1
extend ::ActionController::Railties::Helpers
-
-
1
options.each do |k,v|
-
9
k = "#{k}="
-
9
if respond_to?(k)
-
9
send(k, v)
-
elsif !Base.respond_to?(k)
-
raise "Invalid option key: #{k}"
-
end
-
end
-
end
-
end
-
-
1
initializer "action_controller.compile_config_methods" do
-
1
ActiveSupport.on_load(:action_controller) do
-
1
config.compile_methods! if config.respond_to?(:compile_methods!)
-
end
-
end
-
end
-
end
-
1
module ActionController
-
1
module Railties
-
1
module Helpers
-
1
def inherited(klass)
-
1
super
-
1
return unless klass.respond_to?(:helpers_path=)
-
-
4
if namespace = klass.parents.detect { |m| m.respond_to?(:railtie_helpers_paths) }
-
paths = namespace.railtie_helpers_paths
-
else
-
1
paths = ActionController::Helpers.helpers_path
-
end
-
-
1
klass.helpers_path = paths
-
-
1
if klass.superclass == ActionController::Base && ActionController::Base.include_all_helpers
-
1
klass.helper :all
-
end
-
end
-
end
-
end
-
end
-
1
require 'rack/session/abstract/id'
-
1
require 'active_support/core_ext/object/to_query'
-
1
require 'active_support/core_ext/module/anonymous'
-
1
require 'active_support/core_ext/hash/keys'
-
-
1
module ActionController
-
1
module TemplateAssertions
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
3
setup :setup_subscriptions
-
3
teardown :teardown_subscriptions
-
end
-
-
1
def setup_subscriptions
-
@_partials = Hash.new(0)
-
@_templates = Hash.new(0)
-
@_layouts = Hash.new(0)
-
@_files = Hash.new(0)
-
-
ActiveSupport::Notifications.subscribe("render_template.action_view") do |_name, _start, _finish, _id, payload|
-
path = payload[:layout]
-
if path
-
@_layouts[path] += 1
-
if path =~ /^layouts\/(.*)/
-
@_layouts[$1] += 1
-
end
-
end
-
end
-
-
ActiveSupport::Notifications.subscribe("!render_template.action_view") do |_name, _start, _finish, _id, payload|
-
path = payload[:virtual_path]
-
next unless path
-
partial = path =~ /^.*\/_[^\/]*$/
-
-
if partial
-
@_partials[path] += 1
-
@_partials[path.split("/").last] += 1
-
end
-
-
@_templates[path] += 1
-
end
-
-
ActiveSupport::Notifications.subscribe("!render_template.action_view") do |_name, _start, _finish, _id, payload|
-
next if payload[:virtual_path] # files don't have virtual path
-
-
path = payload[:identifier]
-
if path
-
@_files[path] += 1
-
@_files[path.split("/").last] += 1
-
end
-
end
-
end
-
-
1
def teardown_subscriptions
-
ActiveSupport::Notifications.unsubscribe("render_template.action_view")
-
ActiveSupport::Notifications.unsubscribe("!render_template.action_view")
-
end
-
-
1
def process(*args)
-
@_partials = Hash.new(0)
-
@_templates = Hash.new(0)
-
@_layouts = Hash.new(0)
-
super
-
end
-
-
# Asserts that the request was rendered with the appropriate template file or partials.
-
#
-
# # assert that the "new" view template was rendered
-
# assert_template "new"
-
#
-
# # assert that the exact template "admin/posts/new" was rendered
-
# assert_template %r{\Aadmin/posts/new\Z}
-
#
-
# # assert that the layout 'admin' was rendered
-
# assert_template layout: 'admin'
-
# assert_template layout: 'layouts/admin'
-
# assert_template layout: :admin
-
#
-
# # assert that no layout was rendered
-
# assert_template layout: nil
-
# assert_template layout: false
-
#
-
# # assert that the "_customer" partial was rendered twice
-
# assert_template partial: '_customer', count: 2
-
#
-
# # assert that no partials were rendered
-
# assert_template partial: false
-
#
-
# In a view test case, you can also assert that specific locals are passed
-
# to partials:
-
#
-
# # assert that the "_customer" partial was rendered with a specific object
-
# assert_template partial: '_customer', locals: { customer: @customer }
-
1
def assert_template(options = {}, message = nil)
-
# Force body to be read in case the template is being streamed.
-
response.body
-
-
case options
-
when NilClass, Regexp, String, Symbol
-
options = options.to_s if Symbol === options
-
rendered = @_templates
-
msg = message || sprintf("expecting <%s> but rendering with <%s>",
-
options.inspect, rendered.keys)
-
matches_template =
-
case options
-
when String
-
!options.empty? && rendered.any? do |t, num|
-
options_splited = options.split(File::SEPARATOR)
-
t_splited = t.split(File::SEPARATOR)
-
t_splited.last(options_splited.size) == options_splited
-
end
-
when Regexp
-
rendered.any? { |t,num| t.match(options) }
-
when NilClass
-
rendered.blank?
-
end
-
assert matches_template, msg
-
when Hash
-
options.assert_valid_keys(:layout, :partial, :locals, :count, :file)
-
-
if options.key?(:layout)
-
expected_layout = options[:layout]
-
msg = message || sprintf("expecting layout <%s> but action rendered <%s>",
-
expected_layout, @_layouts.keys)
-
-
case expected_layout
-
when String, Symbol
-
assert_includes @_layouts.keys, expected_layout.to_s, msg
-
when Regexp
-
assert(@_layouts.keys.any? {|l| l =~ expected_layout }, msg)
-
when nil, false
-
assert(@_layouts.empty?, msg)
-
end
-
end
-
-
if options[:file]
-
assert_includes @_files.keys, options[:file]
-
end
-
-
if expected_partial = options[:partial]
-
if expected_locals = options[:locals]
-
if defined?(@_rendered_views)
-
view = expected_partial.to_s.sub(/^_/, '').sub(/\/_(?=[^\/]+\z)/, '/')
-
-
partial_was_not_rendered_msg = "expected %s to be rendered but it was not." % view
-
assert_includes @_rendered_views.rendered_views, view, partial_was_not_rendered_msg
-
-
msg = 'expecting %s to be rendered with %s but was with %s' % [expected_partial,
-
expected_locals,
-
@_rendered_views.locals_for(view)]
-
assert(@_rendered_views.view_rendered?(view, options[:locals]), msg)
-
else
-
warn "the :locals option to #assert_template is only supported in a ActionView::TestCase"
-
end
-
elsif expected_count = options[:count]
-
actual_count = @_partials[expected_partial]
-
msg = message || sprintf("expecting %s to be rendered %s time(s) but rendered %s time(s)",
-
expected_partial, expected_count, actual_count)
-
assert(actual_count == expected_count.to_i, msg)
-
else
-
msg = message || sprintf("expecting partial <%s> but action rendered <%s>",
-
options[:partial], @_partials.keys)
-
assert_includes @_partials, expected_partial, msg
-
end
-
elsif options.key?(:partial)
-
assert @_partials.empty?,
-
"Expected no partials to be rendered"
-
end
-
else
-
raise ArgumentError, "assert_template only accepts a String, Symbol, Hash, Regexp, or nil"
-
end
-
end
-
end
-
-
1
class TestRequest < ActionDispatch::TestRequest #:nodoc:
-
1
DEFAULT_ENV = ActionDispatch::TestRequest::DEFAULT_ENV.dup
-
1
DEFAULT_ENV.delete 'PATH_INFO'
-
-
1
def initialize(env = {})
-
super
-
-
self.session = TestSession.new
-
self.session_options = TestSession::DEFAULT_OPTIONS.merge(:id => SecureRandom.hex(16))
-
end
-
-
1
def assign_parameters(routes, controller_path, action, parameters = {})
-
parameters = parameters.symbolize_keys.merge(:controller => controller_path, :action => action)
-
extra_keys = routes.extra_keys(parameters)
-
non_path_parameters = get? ? query_parameters : request_parameters
-
parameters.each do |key, value|
-
if value.is_a?(Array) && (value.frozen? || value.any?(&:frozen?))
-
value = value.map{ |v| v.duplicable? ? v.dup : v }
-
elsif value.is_a?(Hash) && (value.frozen? || value.any?{ |k,v| v.frozen? })
-
value = Hash[value.map{ |k,v| [k, v.duplicable? ? v.dup : v] }]
-
elsif value.frozen? && value.duplicable?
-
value = value.dup
-
end
-
-
if extra_keys.include?(key.to_sym)
-
non_path_parameters[key] = value
-
else
-
if value.is_a?(Array)
-
value = value.map(&:to_param)
-
else
-
value = value.to_param
-
end
-
-
path_parameters[key.to_s] = value
-
end
-
end
-
-
# Clear the combined params hash in case it was already referenced.
-
@env.delete("action_dispatch.request.parameters")
-
-
# Clear the filter cache variables so they're not stale
-
@filtered_parameters = @filtered_env = @filtered_path = nil
-
-
params = self.request_parameters.dup
-
%w(controller action only_path).each do |k|
-
params.delete(k)
-
params.delete(k.to_sym)
-
end
-
data = params.to_query
-
-
@env['CONTENT_LENGTH'] = data.length.to_s
-
@env['rack.input'] = StringIO.new(data)
-
end
-
-
1
def recycle!
-
@formats = nil
-
@env.delete_if { |k, v| k =~ /^(action_dispatch|rack)\.request/ }
-
@env.delete_if { |k, v| k =~ /^action_dispatch\.rescue/ }
-
@symbolized_path_params = nil
-
@method = @request_method = nil
-
@fullpath = @ip = @remote_ip = @protocol = nil
-
@env['action_dispatch.request.query_parameters'] = {}
-
@set_cookies ||= {}
-
@set_cookies.update(Hash[cookie_jar.instance_variable_get("@set_cookies").map{ |k,o| [k,o[:value]] }])
-
deleted_cookies = cookie_jar.instance_variable_get("@delete_cookies")
-
@set_cookies.reject!{ |k,v| deleted_cookies.include?(k) }
-
cookie_jar.update(rack_cookies)
-
cookie_jar.update(cookies)
-
cookie_jar.update(@set_cookies)
-
cookie_jar.recycle!
-
end
-
-
1
private
-
-
1
def default_env
-
DEFAULT_ENV
-
end
-
end
-
-
1
class TestResponse < ActionDispatch::TestResponse
-
1
def recycle!
-
initialize
-
end
-
end
-
-
1
class LiveTestResponse < Live::Response
-
1
def recycle!
-
@body = nil
-
initialize
-
end
-
-
1
def body
-
@body ||= super
-
end
-
-
# Was the response successful?
-
1
alias_method :success?, :successful?
-
-
# Was the URL not found?
-
1
alias_method :missing?, :not_found?
-
-
# Were we redirected?
-
1
alias_method :redirect?, :redirection?
-
-
# Was there a server-side error?
-
1
alias_method :error?, :server_error?
-
end
-
-
# Methods #destroy and #load! are overridden to avoid calling methods on the
-
# @store object, which does not exist for the TestSession class.
-
1
class TestSession < Rack::Session::Abstract::SessionHash #:nodoc:
-
1
DEFAULT_OPTIONS = Rack::Session::Abstract::ID::DEFAULT_OPTIONS
-
-
1
def initialize(session = {})
-
super(nil, nil)
-
@id = SecureRandom.hex(16)
-
@data = stringify_keys(session)
-
@loaded = true
-
end
-
-
1
def exists?
-
true
-
end
-
-
1
def keys
-
@data.keys
-
end
-
-
1
def values
-
@data.values
-
end
-
-
1
def destroy
-
clear
-
end
-
-
1
private
-
-
1
def load!
-
@id
-
end
-
end
-
-
# Superclass for ActionController functional tests. Functional tests allow you to
-
# test a single controller action per test method. This should not be confused with
-
# integration tests (see ActionDispatch::IntegrationTest), which are more like
-
# "stories" that can involve multiple controllers and multiple actions (i.e. multiple
-
# different HTTP requests).
-
#
-
# == Basic example
-
#
-
# Functional tests are written as follows:
-
# 1. First, one uses the +get+, +post+, +patch+, +put+, +delete+ or +head+ method to simulate
-
# an HTTP request.
-
# 2. Then, one asserts whether the current state is as expected. "State" can be anything:
-
# the controller's HTTP response, the database contents, etc.
-
#
-
# For example:
-
#
-
# class BooksControllerTest < ActionController::TestCase
-
# def test_create
-
# # Simulate a POST response with the given HTTP parameters.
-
# post(:create, book: { title: "Love Hina" })
-
#
-
# # Assert that the controller tried to redirect us to
-
# # the created book's URI.
-
# assert_response :found
-
#
-
# # Assert that the controller really put the book in the database.
-
# assert_not_nil Book.find_by(title: "Love Hina")
-
# end
-
# end
-
#
-
# You can also send a real document in the simulated HTTP request.
-
#
-
# def test_create
-
# json = {book: { title: "Love Hina" }}.to_json
-
# post :create, json
-
# end
-
#
-
# == Special instance variables
-
#
-
# ActionController::TestCase will also automatically provide the following instance
-
# variables for use in the tests:
-
#
-
# <b>@controller</b>::
-
# The controller instance that will be tested.
-
# <b>@request</b>::
-
# An ActionController::TestRequest, representing the current HTTP
-
# request. You can modify this object before sending the HTTP request. For example,
-
# you might want to set some session properties before sending a GET request.
-
# <b>@response</b>::
-
# An ActionController::TestResponse object, representing the response
-
# of the last HTTP response. In the above example, <tt>@response</tt> becomes valid
-
# after calling +post+. If the various assert methods are not sufficient, then you
-
# may use this object to inspect the HTTP response in detail.
-
#
-
# (Earlier versions of \Rails required each functional test to subclass
-
# Test::Unit::TestCase and define @controller, @request, @response in +setup+.)
-
#
-
# == Controller is automatically inferred
-
#
-
# ActionController::TestCase will automatically infer the controller under test
-
# from the test class name. If the controller cannot be inferred from the test
-
# class name, you can explicitly set it with +tests+.
-
#
-
# class SpecialEdgeCaseWidgetsControllerTest < ActionController::TestCase
-
# tests WidgetController
-
# end
-
#
-
# == \Testing controller internals
-
#
-
# In addition to these specific assertions, you also have easy access to various collections that the regular test/unit assertions
-
# can be used against. These collections are:
-
#
-
# * assigns: Instance variables assigned in the action that are available for the view.
-
# * session: Objects being saved in the session.
-
# * flash: The flash objects currently in the session.
-
# * cookies: \Cookies being sent to the user on this request.
-
#
-
# These collections can be used just like any other hash:
-
#
-
# assert_not_nil assigns(:person) # makes sure that a @person instance variable was set
-
# assert_equal "Dave", cookies[:name] # makes sure that a cookie called :name was set as "Dave"
-
# assert flash.empty? # makes sure that there's nothing in the flash
-
#
-
# For historic reasons, the assigns hash uses string-based keys. So <tt>assigns[:person]</tt> won't work, but <tt>assigns["person"]</tt> will. To
-
# appease our yearning for symbols, though, an alternative accessor has been devised using a method call instead of index referencing.
-
# So <tt>assigns(:person)</tt> will work just like <tt>assigns["person"]</tt>, but again, <tt>assigns[:person]</tt> will not work.
-
#
-
# On top of the collections, you have the complete url that a given action redirected to available in <tt>redirect_to_url</tt>.
-
#
-
# For redirects within the same controller, you can even call follow_redirect and the redirect will be followed, triggering another
-
# action call which can then be asserted against.
-
#
-
# == Manipulating session and cookie variables
-
#
-
# Sometimes you need to set up the session and cookie variables for a test.
-
# To do this just assign a value to the session or cookie collection:
-
#
-
# session[:key] = "value"
-
# cookies[:key] = "value"
-
#
-
# To clear the cookies for a test just clear the cookie collection:
-
#
-
# cookies.clear
-
#
-
# == \Testing named routes
-
#
-
# If you're using named routes, they can be easily tested using the original named routes' methods straight in the test case.
-
#
-
# assert_redirected_to page_url(title: 'foo')
-
1
class TestCase < ActiveSupport::TestCase
-
1
module Behavior
-
1
extend ActiveSupport::Concern
-
1
include ActionDispatch::TestProcess
-
1
include ActiveSupport::Testing::ConstantLookup
-
-
1
attr_reader :response, :request
-
-
1
module ClassMethods
-
-
# Sets the controller class name. Useful if the name can't be inferred from test class.
-
# Normalizes +controller_class+ before using.
-
#
-
# tests WidgetController
-
# tests :widget
-
# tests 'widget'
-
1
def tests(controller_class)
-
case controller_class
-
when String, Symbol
-
self.controller_class = "#{controller_class.to_s.camelize}Controller".constantize
-
when Class
-
self.controller_class = controller_class
-
else
-
raise ArgumentError, "controller class must be a String, Symbol, or Class"
-
end
-
end
-
-
1
def controller_class=(new_class)
-
prepare_controller_class(new_class) if new_class
-
self._controller_class = new_class
-
end
-
-
1
def controller_class
-
if current_controller_class = self._controller_class
-
current_controller_class
-
else
-
self.controller_class = determine_default_controller_class(name)
-
end
-
end
-
-
1
def determine_default_controller_class(name)
-
determine_constant_from_test_name(name) do |constant|
-
Class === constant && constant < ActionController::Metal
-
end
-
end
-
-
1
def prepare_controller_class(new_class)
-
new_class.send :include, ActionController::TestCase::RaiseActionExceptions
-
end
-
-
end
-
-
# Simulate a GET request with the given parameters.
-
#
-
# - +action+: The controller action to call.
-
# - +parameters+: The HTTP parameters that you want to pass. This may
-
# be +nil+, a hash, or a string that is appropriately encoded
-
# (<tt>application/x-www-form-urlencoded</tt> or <tt>multipart/form-data</tt>).
-
# - +session+: A hash of parameters to store in the session. This may be +nil+.
-
# - +flash+: A hash of parameters to store in the flash. This may be +nil+.
-
#
-
# You can also simulate POST, PATCH, PUT, DELETE, HEAD, and OPTIONS requests with
-
# +post+, +patch+, +put+, +delete+, +head+, and +options+.
-
#
-
# Note that the request method is not verified. The different methods are
-
# available to make the tests more expressive.
-
1
def get(action, *args)
-
process(action, "GET", *args)
-
end
-
-
# Simulate a POST request with the given parameters and set/volley the response.
-
# See +get+ for more details.
-
1
def post(action, *args)
-
process(action, "POST", *args)
-
end
-
-
# Simulate a PATCH request with the given parameters and set/volley the response.
-
# See +get+ for more details.
-
1
def patch(action, *args)
-
process(action, "PATCH", *args)
-
end
-
-
# Simulate a PUT request with the given parameters and set/volley the response.
-
# See +get+ for more details.
-
1
def put(action, *args)
-
process(action, "PUT", *args)
-
end
-
-
# Simulate a DELETE request with the given parameters and set/volley the response.
-
# See +get+ for more details.
-
1
def delete(action, *args)
-
process(action, "DELETE", *args)
-
end
-
-
# Simulate a HEAD request with the given parameters and set/volley the response.
-
# See +get+ for more details.
-
1
def head(action, *args)
-
process(action, "HEAD", *args)
-
end
-
-
1
def xml_http_request(request_method, action, parameters = nil, session = nil, flash = nil)
-
@request.env['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
-
@request.env['HTTP_ACCEPT'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
-
__send__(request_method, action, parameters, session, flash).tap do
-
@request.env.delete 'HTTP_X_REQUESTED_WITH'
-
@request.env.delete 'HTTP_ACCEPT'
-
end
-
end
-
1
alias xhr :xml_http_request
-
-
1
def paramify_values(hash_or_array_or_value)
-
case hash_or_array_or_value
-
when Hash
-
Hash[hash_or_array_or_value.map{|key, value| [key, paramify_values(value)] }]
-
when Array
-
hash_or_array_or_value.map {|i| paramify_values(i)}
-
when Rack::Test::UploadedFile, ActionDispatch::Http::UploadedFile
-
hash_or_array_or_value
-
else
-
hash_or_array_or_value.to_param
-
end
-
end
-
-
1
def process(action, http_method = 'GET', *args)
-
check_required_ivars
-
-
if args.first.is_a?(String) && http_method != 'HEAD'
-
@request.env['RAW_POST_DATA'] = args.shift
-
end
-
-
parameters, session, flash = args
-
-
# Ensure that numbers and symbols passed as params are converted to
-
# proper params, as is the case when engaging rack.
-
parameters = paramify_values(parameters) if html_format?(parameters)
-
-
@html_document = nil
-
-
unless @controller.respond_to?(:recycle!)
-
@controller.extend(Testing::Functional)
-
@controller.class.class_eval { include Testing }
-
end
-
-
@request.recycle!
-
@response.recycle!
-
@controller.recycle!
-
-
@request.env['REQUEST_METHOD'] = http_method
-
-
parameters ||= {}
-
controller_class_name = @controller.class.anonymous? ?
-
"anonymous" :
-
@controller.class.controller_path
-
-
@request.assign_parameters(@routes, controller_class_name, action.to_s, parameters)
-
-
@request.session.update(session) if session
-
@request.flash.update(flash || {})
-
-
@controller.request = @request
-
@controller.response = @response
-
-
build_request_uri(action, parameters)
-
-
name = @request.parameters[:action]
-
-
@controller.recycle!
-
@controller.process(name)
-
-
if cookies = @request.env['action_dispatch.cookies']
-
unless @response.committed?
-
cookies.write(@response)
-
end
-
end
-
@response.prepare!
-
-
@assigns = @controller.respond_to?(:view_assigns) ? @controller.view_assigns : {}
-
@request.session['flash'] = @request.flash.to_session_value
-
@request.session.delete('flash') if @request.session['flash'].blank?
-
@response
-
end
-
-
1
def setup_controller_request_and_response
-
@controller = nil unless defined? @controller
-
-
response_klass = TestResponse
-
-
if klass = self.class.controller_class
-
if klass < ActionController::Live
-
response_klass = LiveTestResponse
-
end
-
unless @controller
-
begin
-
@controller = klass.new
-
rescue
-
warn "could not construct controller #{klass}" if $VERBOSE
-
end
-
end
-
end
-
-
@request = build_request
-
@response = build_response response_klass
-
@response.request = @request
-
-
if @controller
-
@controller.request = @request
-
@controller.params = {}
-
end
-
end
-
-
1
def build_request
-
TestRequest.new
-
end
-
-
1
def build_response(klass)
-
klass.new
-
end
-
-
1
included do
-
1
include ActionController::TemplateAssertions
-
1
include ActionDispatch::Assertions
-
1
class_attribute :_controller_class
-
1
setup :setup_controller_request_and_response
-
end
-
-
1
private
-
1
def check_required_ivars
-
# Sanity check for required instance variables so we can give an
-
# understandable error message.
-
[:@routes, :@controller, :@request, :@response].each do |iv_name|
-
if !instance_variable_defined?(iv_name) || instance_variable_get(iv_name).nil?
-
raise "#{iv_name} is nil: make sure you set it in your test's setup method."
-
end
-
end
-
end
-
-
1
def build_request_uri(action, parameters)
-
unless @request.env["PATH_INFO"]
-
options = @controller.respond_to?(:url_options) ? @controller.__send__(:url_options).merge(parameters) : parameters
-
options.update(
-
:only_path => true,
-
:action => action,
-
:relative_url_root => nil,
-
:_recall => @request.symbolized_path_parameters)
-
-
url, query_string = @routes.url_for(options).split("?", 2)
-
-
@request.env["SCRIPT_NAME"] = @controller.config.relative_url_root
-
@request.env["PATH_INFO"] = url
-
@request.env["QUERY_STRING"] = query_string || ""
-
end
-
end
-
-
1
def html_format?(parameters)
-
return true unless parameters.is_a?(Hash)
-
Mime.fetch(parameters[:format]) { Mime['html'] }.html?
-
end
-
end
-
-
# When the request.remote_addr remains the default for testing, which is 0.0.0.0, the exception is simply raised inline
-
# (skipping the regular exception handling from rescue_action). If the request.remote_addr is anything else, the regular
-
# rescue_action process takes place. This means you can test your rescue_action code by setting remote_addr to something else
-
# than 0.0.0.0.
-
#
-
# The exception is stored in the exception accessor for further inspection.
-
1
module RaiseActionExceptions
-
1
def self.included(base) #:nodoc:
-
unless base.method_defined?(:exception) && base.method_defined?(:exception=)
-
base.class_eval do
-
attr_accessor :exception
-
protected :exception, :exception=
-
end
-
end
-
end
-
-
1
protected
-
1
def rescue_action_without_handler(e)
-
self.exception = e
-
-
if request.remote_addr == "0.0.0.0"
-
raise(e)
-
else
-
super(e)
-
end
-
end
-
end
-
-
1
include Behavior
-
end
-
end
-
#--
-
# Copyright (c) 2004-2014 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
1
require 'active_support'
-
1
require 'active_support/rails'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
-
1
require 'action_pack'
-
1
require 'rack'
-
-
1
module Rack
-
1
autoload :Test, 'rack/test'
-
end
-
-
1
module ActionDispatch
-
1
extend ActiveSupport::Autoload
-
-
1
class IllegalStateError < StandardError
-
end
-
-
1
eager_autoload do
-
1
autoload_under 'http' do
-
1
autoload :Request
-
1
autoload :Response
-
end
-
end
-
-
1
autoload_under 'middleware' do
-
1
autoload :RequestId
-
1
autoload :Callbacks
-
1
autoload :Cookies
-
1
autoload :DebugExceptions
-
1
autoload :ExceptionWrapper
-
1
autoload :Flash
-
1
autoload :ParamsParser
-
1
autoload :PublicExceptions
-
1
autoload :Reloader
-
1
autoload :RemoteIp
-
1
autoload :ShowExceptions
-
1
autoload :SSL
-
1
autoload :Static
-
end
-
-
1
autoload :Journey
-
1
autoload :MiddlewareStack, 'action_dispatch/middleware/stack'
-
1
autoload :Routing
-
-
1
module Http
-
1
extend ActiveSupport::Autoload
-
-
1
autoload :Cache
-
1
autoload :Headers
-
1
autoload :MimeNegotiation
-
1
autoload :Parameters
-
1
autoload :ParameterFilter
-
1
autoload :Upload
-
1
autoload :UploadedFile, 'action_dispatch/http/upload'
-
1
autoload :URL
-
end
-
-
1
module Session
-
1
autoload :AbstractStore, 'action_dispatch/middleware/session/abstract_store'
-
1
autoload :CookieStore, 'action_dispatch/middleware/session/cookie_store'
-
1
autoload :MemCacheStore, 'action_dispatch/middleware/session/mem_cache_store'
-
1
autoload :CacheStore, 'action_dispatch/middleware/session/cache_store'
-
end
-
-
1
mattr_accessor :test_app
-
-
1
autoload_under 'testing' do
-
1
autoload :Assertions
-
1
autoload :Integration
-
1
autoload :IntegrationTest, 'action_dispatch/testing/integration'
-
1
autoload :TestProcess
-
1
autoload :TestRequest
-
1
autoload :TestResponse
-
end
-
end
-
-
1
autoload :Mime, 'action_dispatch/http/mime_type'
-
-
1
ActiveSupport.on_load(:action_view) do
-
1
ActionView::Base.default_formats ||= Mime::SET.symbols
-
1
ActionView::Template::Types.delegate_to Mime
-
end
-
-
1
module ActionDispatch
-
1
module Http
-
1
module Cache
-
1
module Request
-
-
1
HTTP_IF_MODIFIED_SINCE = 'HTTP_IF_MODIFIED_SINCE'.freeze
-
1
HTTP_IF_NONE_MATCH = 'HTTP_IF_NONE_MATCH'.freeze
-
-
1
def if_modified_since
-
if since = env[HTTP_IF_MODIFIED_SINCE]
-
Time.rfc2822(since) rescue nil
-
end
-
end
-
-
1
def if_none_match
-
env[HTTP_IF_NONE_MATCH]
-
end
-
-
1
def if_none_match_etags
-
(if_none_match ? if_none_match.split(/\s*,\s*/) : []).collect do |etag|
-
etag.gsub(/^\"|\"$/, "")
-
end
-
end
-
-
1
def not_modified?(modified_at)
-
if_modified_since && modified_at && if_modified_since >= modified_at
-
end
-
-
1
def etag_matches?(etag)
-
if etag
-
etag = etag.gsub(/^\"|\"$/, "")
-
if_none_match_etags.include?(etag)
-
end
-
end
-
-
# Check response freshness (Last-Modified and ETag) against request
-
# If-Modified-Since and If-None-Match conditions. If both headers are
-
# supplied, both must match, or the request is not considered fresh.
-
1
def fresh?(response)
-
last_modified = if_modified_since
-
etag = if_none_match
-
-
return false unless last_modified || etag
-
-
success = true
-
success &&= not_modified?(response.last_modified) if last_modified
-
success &&= etag_matches?(response.etag) if etag
-
success
-
end
-
end
-
-
1
module Response
-
1
attr_reader :cache_control, :etag
-
1
alias :etag? :etag
-
-
1
def last_modified
-
if last = headers[LAST_MODIFIED]
-
Time.httpdate(last)
-
end
-
end
-
-
1
def last_modified?
-
headers.include?(LAST_MODIFIED)
-
end
-
-
1
def last_modified=(utc_time)
-
headers[LAST_MODIFIED] = utc_time.httpdate
-
end
-
-
1
def date
-
if date_header = headers['Date']
-
Time.httpdate(date_header)
-
end
-
end
-
-
1
def date?
-
headers.include?('Date')
-
end
-
-
1
def date=(utc_time)
-
headers['Date'] = utc_time.httpdate
-
end
-
-
1
def etag=(etag)
-
key = ActiveSupport::Cache.expand_cache_key(etag)
-
@etag = self[ETAG] = %("#{Digest::MD5.hexdigest(key)}")
-
end
-
-
1
private
-
-
1
LAST_MODIFIED = "Last-Modified".freeze
-
1
ETAG = "ETag".freeze
-
1
CACHE_CONTROL = "Cache-Control".freeze
-
1
SPECIAL_KEYS = %w[extras no-cache max-age public must-revalidate]
-
-
1
def cache_control_segments
-
if cache_control = self[CACHE_CONTROL]
-
cache_control.delete(' ').split(',')
-
else
-
[]
-
end
-
end
-
-
1
def cache_control_headers
-
cache_control = {}
-
-
cache_control_segments.each do |segment|
-
directive, argument = segment.split('=', 2)
-
-
if SPECIAL_KEYS.include? directive
-
key = directive.tr('-', '_')
-
cache_control[key.to_sym] = argument || true
-
else
-
cache_control[:extras] ||= []
-
cache_control[:extras] << segment
-
end
-
end
-
-
cache_control
-
end
-
-
1
def prepare_cache_control!
-
@cache_control = cache_control_headers
-
@etag = self[ETAG]
-
end
-
-
1
def handle_conditional_get!
-
if etag? || last_modified? || !@cache_control.empty?
-
set_conditional_cache_control!
-
end
-
end
-
-
1
DEFAULT_CACHE_CONTROL = "max-age=0, private, must-revalidate".freeze
-
1
NO_CACHE = "no-cache".freeze
-
1
PUBLIC = "public".freeze
-
1
PRIVATE = "private".freeze
-
1
MUST_REVALIDATE = "must-revalidate".freeze
-
-
1
def set_conditional_cache_control!
-
control = {}
-
cc_headers = cache_control_headers
-
if extras = cc_headers.delete(:extras)
-
@cache_control[:extras] ||= []
-
@cache_control[:extras] += extras
-
@cache_control[:extras].uniq!
-
end
-
-
control.merge! cc_headers
-
control.merge! @cache_control
-
-
if control.empty?
-
headers[CACHE_CONTROL] = DEFAULT_CACHE_CONTROL
-
elsif control[:no_cache]
-
headers[CACHE_CONTROL] = NO_CACHE
-
if control[:extras]
-
headers[CACHE_CONTROL] += ", #{control[:extras].join(', ')}"
-
end
-
else
-
extras = control[:extras]
-
max_age = control[:max_age]
-
-
options = []
-
options << "max-age=#{max_age.to_i}" if max_age
-
options << (control[:public] ? PUBLIC : PRIVATE)
-
options << MUST_REVALIDATE if control[:must_revalidate]
-
options.concat(extras) if extras
-
-
headers[CACHE_CONTROL] = options.join(", ")
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/keys'
-
1
require 'active_support/core_ext/object/duplicable'
-
1
require 'action_dispatch/http/parameter_filter'
-
-
1
module ActionDispatch
-
1
module Http
-
# Allows you to specify sensitive parameters which will be replaced from
-
# the request log by looking in the query string of the request and all
-
# subhashes of the params hash to filter. If a block is given, each key and
-
# value of the params hash and all subhashes is passed to it, the value
-
# or key can be replaced using String#replace or similar method.
-
#
-
# env["action_dispatch.parameter_filter"] = [:password]
-
# => replaces the value to all keys matching /password/i with "[FILTERED]"
-
#
-
# env["action_dispatch.parameter_filter"] = [:foo, "bar"]
-
# => replaces the value to all keys matching /foo|bar/i with "[FILTERED]"
-
#
-
# env["action_dispatch.parameter_filter"] = lambda do |k,v|
-
# v.reverse! if k =~ /secret/i
-
# end
-
# => reverses the value to all keys matching /secret/i
-
1
module FilterParameters
-
1
ENV_MATCH = [/RAW_POST_DATA/, "rack.request.form_vars"] # :nodoc:
-
1
NULL_PARAM_FILTER = ParameterFilter.new # :nodoc:
-
1
NULL_ENV_FILTER = ParameterFilter.new ENV_MATCH # :nodoc:
-
-
1
def initialize(env)
-
super
-
@filtered_parameters = nil
-
@filtered_env = nil
-
@filtered_path = nil
-
end
-
-
# Return a hash of parameters with all sensitive data replaced.
-
1
def filtered_parameters
-
@filtered_parameters ||= parameter_filter.filter(parameters)
-
end
-
-
# Return a hash of request.env with all sensitive data replaced.
-
1
def filtered_env
-
@filtered_env ||= env_filter.filter(@env)
-
end
-
-
# Reconstructed a path with all sensitive GET parameters replaced.
-
1
def filtered_path
-
@filtered_path ||= query_string.empty? ? path : "#{path}?#{filtered_query_string}"
-
end
-
-
1
protected
-
-
1
def parameter_filter
-
parameter_filter_for @env.fetch("action_dispatch.parameter_filter") {
-
return NULL_PARAM_FILTER
-
}
-
end
-
-
1
def env_filter
-
user_key = @env.fetch("action_dispatch.parameter_filter") {
-
return NULL_ENV_FILTER
-
}
-
parameter_filter_for(Array(user_key) + ENV_MATCH)
-
end
-
-
1
def parameter_filter_for(filters)
-
ParameterFilter.new(filters)
-
end
-
-
1
KV_RE = '[^&;=]+'
-
1
PAIR_RE = %r{(#{KV_RE})=(#{KV_RE})}
-
1
def filtered_query_string
-
query_string.gsub(PAIR_RE) do |_|
-
parameter_filter.filter([[$1, $2]]).first.join("=")
-
end
-
end
-
end
-
end
-
end
-
1
module ActionDispatch
-
1
module Http
-
1
module FilterRedirect
-
-
1
FILTERED = '[FILTERED]'.freeze # :nodoc:
-
-
1
def filtered_location
-
filters = location_filter
-
if !filters.empty? && location_filter_match?(filters)
-
FILTERED
-
else
-
location
-
end
-
end
-
-
1
private
-
-
1
def location_filter
-
if request
-
request.env['action_dispatch.redirect_filter'] || []
-
else
-
[]
-
end
-
end
-
-
1
def location_filter_match?(filters)
-
filters.any? do |filter|
-
if String === filter
-
location.include?(filter)
-
elsif Regexp === filter
-
location.match(filter)
-
end
-
end
-
end
-
-
end
-
end
-
end
-
1
module ActionDispatch
-
1
module Http
-
1
class Headers
-
1
CGI_VARIABLES = %w(
-
CONTENT_TYPE CONTENT_LENGTH
-
HTTPS AUTH_TYPE GATEWAY_INTERFACE
-
PATH_INFO PATH_TRANSLATED QUERY_STRING
-
REMOTE_ADDR REMOTE_HOST REMOTE_IDENT REMOTE_USER
-
REQUEST_METHOD SCRIPT_NAME
-
SERVER_NAME SERVER_PORT SERVER_PROTOCOL SERVER_SOFTWARE
-
)
-
1
HTTP_HEADER = /\A[A-Za-z0-9-]+\z/
-
-
1
include Enumerable
-
1
attr_reader :env
-
-
1
def initialize(env = {})
-
@env = env
-
end
-
-
1
def [](key)
-
@env[env_name(key)]
-
end
-
-
1
def []=(key, value)
-
@env[env_name(key)] = value
-
end
-
-
1
def key?(key); @env.key? key; end
-
1
alias :include? :key?
-
-
1
def fetch(key, *args, &block)
-
@env.fetch env_name(key), *args, &block
-
end
-
-
1
def each(&block)
-
@env.each(&block)
-
end
-
-
1
def merge(headers_or_env)
-
headers = Http::Headers.new(env.dup)
-
headers.merge!(headers_or_env)
-
headers
-
end
-
-
1
def merge!(headers_or_env)
-
headers_or_env.each do |key, value|
-
self[env_name(key)] = value
-
end
-
end
-
-
1
private
-
1
def env_name(key)
-
key = key.to_s
-
if key =~ HTTP_HEADER
-
key = key.upcase.tr('-', '_')
-
key = "HTTP_" + key unless CGI_VARIABLES.include?(key)
-
end
-
key
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
-
1
module ActionDispatch
-
1
module Http
-
1
module MimeNegotiation
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
mattr_accessor :ignore_accept_header
-
1
self.ignore_accept_header = false
-
end
-
-
1
attr_reader :variant
-
-
# The MIME type of the HTTP request, such as Mime::XML.
-
#
-
# For backward compatibility, the post \format is extracted from the
-
# X-Post-Data-Format HTTP header if present.
-
1
def content_mime_type
-
@env["action_dispatch.request.content_type"] ||= begin
-
if @env['CONTENT_TYPE'] =~ /^([^,\;]*)/
-
Mime::Type.lookup($1.strip.downcase)
-
else
-
nil
-
end
-
end
-
end
-
-
1
def content_type
-
content_mime_type && content_mime_type.to_s
-
end
-
-
# Returns the accepted MIME type for the request.
-
1
def accepts
-
@env["action_dispatch.request.accepts"] ||= begin
-
header = @env['HTTP_ACCEPT'].to_s.strip
-
-
if header.empty?
-
[content_mime_type]
-
else
-
Mime::Type.parse(header)
-
end
-
end
-
end
-
-
# Returns the MIME type for the \format used in the request.
-
#
-
# GET /posts/5.xml | request.format => Mime::XML
-
# GET /posts/5.xhtml | request.format => Mime::HTML
-
# GET /posts/5 | request.format => Mime::HTML or MIME::JS, or request.accepts.first
-
#
-
1
def format(view_path = [])
-
formats.first || Mime::NullType.instance
-
end
-
-
1
def formats
-
@env["action_dispatch.request.formats"] ||=
-
if parameters[:format]
-
Array(Mime[parameters[:format]])
-
elsif use_accept_header && valid_accept_header
-
accepts
-
elsif xhr?
-
[Mime::JS]
-
else
-
[Mime::HTML]
-
end
-
end
-
-
# Sets the \variant for template.
-
1
def variant=(variant)
-
if variant.is_a?(Symbol)
-
@variant = [variant]
-
elsif variant.is_a?(Array) && variant.any? && variant.all?{ |v| v.is_a?(Symbol) }
-
@variant = variant
-
else
-
raise ArgumentError, "request.variant must be set to a Symbol or an Array of Symbols, not a #{variant.class}. " \
-
"For security reasons, never directly set the variant to a user-provided value, " \
-
"like params[:variant].to_sym. Check user-provided value against a whitelist first, " \
-
"then set the variant: request.variant = :tablet if params[:variant] == 'tablet'"
-
end
-
end
-
-
# Sets the \format by string extension, which can be used to force custom formats
-
# that are not controlled by the extension.
-
#
-
# class ApplicationController < ActionController::Base
-
# before_action :adjust_format_for_iphone
-
#
-
# private
-
# def adjust_format_for_iphone
-
# request.format = :iphone if request.env["HTTP_USER_AGENT"][/iPhone/]
-
# end
-
# end
-
1
def format=(extension)
-
parameters[:format] = extension.to_s
-
@env["action_dispatch.request.formats"] = [Mime::Type.lookup_by_extension(parameters[:format])]
-
end
-
-
# Sets the \formats by string extensions. This differs from #format= by allowing you
-
# to set multiple, ordered formats, which is useful when you want to have a fallback.
-
#
-
# In this example, the :iphone format will be used if it's available, otherwise it'll fallback
-
# to the :html format.
-
#
-
# class ApplicationController < ActionController::Base
-
# before_action :adjust_format_for_iphone_with_html_fallback
-
#
-
# private
-
# def adjust_format_for_iphone_with_html_fallback
-
# request.formats = [ :iphone, :html ] if request.env["HTTP_USER_AGENT"][/iPhone/]
-
# end
-
# end
-
1
def formats=(extensions)
-
parameters[:format] = extensions.first.to_s
-
@env["action_dispatch.request.formats"] = extensions.collect do |extension|
-
Mime::Type.lookup_by_extension(extension)
-
end
-
end
-
-
# Receives an array of mimes and return the first user sent mime that
-
# matches the order array.
-
#
-
1
def negotiate_mime(order)
-
formats.each do |priority|
-
if priority == Mime::ALL
-
return order.first
-
elsif order.include?(priority)
-
return priority
-
end
-
end
-
-
order.include?(Mime::ALL) ? formats.first : nil
-
end
-
-
1
protected
-
-
1
BROWSER_LIKE_ACCEPTS = /,\s*\*\/\*|\*\/\*\s*,/
-
-
1
def valid_accept_header
-
(xhr? && (accept.present? || content_mime_type)) ||
-
(accept.present? && accept !~ BROWSER_LIKE_ACCEPTS)
-
end
-
-
1
def use_accept_header
-
!self.class.ignore_accept_header
-
end
-
end
-
end
-
end
-
1
require 'set'
-
1
require 'singleton'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/string/starts_ends_with'
-
-
1
module Mime
-
1
class Mimes < Array
-
1
def symbols
-
23
@symbols ||= map { |m| m.to_sym }
-
end
-
-
%w(<< concat shift unshift push pop []= clear compact! collect!
-
delete delete_at delete_if flatten! map! insert reject! reverse!
-
1
replace slice! sort! uniq!).each do |method|
-
22
module_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{method}(*)
-
@symbols = nil
-
super
-
end
-
CODE
-
end
-
end
-
-
1
SET = Mimes.new
-
1
EXTENSION_LOOKUP = {}
-
1
LOOKUP = Hash.new { |h, k| h[k] = Type.new(k) unless k.blank? }
-
-
1
class << self
-
1
def [](type)
-
return type if type.is_a?(Type)
-
Type.lookup_by_extension(type)
-
end
-
-
1
def fetch(type)
-
return type if type.is_a?(Type)
-
EXTENSION_LOOKUP.fetch(type.to_s) { |k| yield k }
-
end
-
end
-
-
# Encapsulates the notion of a mime type. Can be used at render time, for example, with:
-
#
-
# class PostsController < ActionController::Base
-
# def show
-
# @post = Post.find(params[:id])
-
#
-
# respond_to do |format|
-
# format.html
-
# format.ics { render text: post.to_ics, mime_type: Mime::Type["text/calendar"] }
-
# format.xml { render xml: @people }
-
# end
-
# end
-
# end
-
1
class Type
-
1
@@html_types = Set.new [:html, :all]
-
1
cattr_reader :html_types
-
-
1
attr_reader :symbol
-
-
1
@register_callbacks = []
-
-
# A simple helper class used in parsing the accept header
-
1
class AcceptItem #:nodoc:
-
1
attr_accessor :index, :name, :q
-
1
alias :to_s :name
-
-
1
def initialize(index, name, q = nil)
-
@index = index
-
@name = name
-
q ||= 0.0 if @name == Mime::ALL.to_s # default wildcard match to end of list
-
@q = ((q || 1.0).to_f * 100).to_i
-
end
-
-
1
def <=>(item)
-
result = item.q <=> @q
-
result = @index <=> item.index if result == 0
-
result
-
end
-
-
1
def ==(item)
-
@name == item.to_s
-
end
-
end
-
-
1
class AcceptList < Array #:nodoc:
-
1
def assort!
-
sort!
-
-
# Take care of the broken text/xml entry by renaming or deleting it
-
if text_xml_idx && app_xml_idx
-
app_xml.q = [text_xml.q, app_xml.q].max # set the q value to the max of the two
-
exchange_xml_items if app_xml_idx > text_xml_idx # make sure app_xml is ahead of text_xml in the list
-
delete_at(text_xml_idx) # delete text_xml from the list
-
elsif text_xml_idx
-
text_xml.name = Mime::XML.to_s
-
end
-
-
# Look for more specific XML-based types and sort them ahead of app/xml
-
if app_xml_idx
-
idx = app_xml_idx
-
-
while idx < length
-
type = self[idx]
-
break if type.q < app_xml.q
-
-
if type.name.ends_with? '+xml'
-
self[app_xml_idx], self[idx] = self[idx], app_xml
-
@app_xml_idx = idx
-
end
-
idx += 1
-
end
-
end
-
-
map! { |i| Mime::Type.lookup(i.name) }.uniq!
-
to_a
-
end
-
-
1
private
-
1
def text_xml_idx
-
@text_xml_idx ||= index('text/xml')
-
end
-
-
1
def app_xml_idx
-
@app_xml_idx ||= index(Mime::XML.to_s)
-
end
-
-
1
def text_xml
-
self[text_xml_idx]
-
end
-
-
1
def app_xml
-
self[app_xml_idx]
-
end
-
-
1
def exchange_xml_items
-
self[app_xml_idx], self[text_xml_idx] = text_xml, app_xml
-
@app_xml_idx, @text_xml_idx = text_xml_idx, app_xml_idx
-
end
-
end
-
-
1
class << self
-
1
TRAILING_STAR_REGEXP = /(text|application)\/\*/
-
1
PARAMETER_SEPARATOR_REGEXP = /;\s*\w+="?\w+"?/
-
-
1
def register_callback(&block)
-
1
@register_callbacks << block
-
end
-
-
1
def lookup(string)
-
LOOKUP[string]
-
end
-
-
1
def lookup_by_extension(extension)
-
EXTENSION_LOOKUP[extension.to_s]
-
end
-
-
# Registers an alias that's not used on mime type lookup, but can be referenced directly. Especially useful for
-
# rendering different HTML versions depending on the user agent, like an iPhone.
-
1
def register_alias(string, symbol, extension_synonyms = [])
-
register(string, symbol, [], extension_synonyms, true)
-
end
-
-
1
def register(string, symbol, mime_type_synonyms = [], extension_synonyms = [], skip_lookup = false)
-
22
Mime.const_set(symbol.upcase, Type.new(string, symbol, mime_type_synonyms))
-
-
22
new_mime = Mime.const_get(symbol.upcase)
-
22
SET << new_mime
-
-
52
([string] + mime_type_synonyms).each { |str| LOOKUP[str] = SET.last } unless skip_lookup
-
60
([symbol] + extension_synonyms).each { |ext| EXTENSION_LOOKUP[ext.to_s] = SET.last }
-
-
22
@register_callbacks.each do |callback|
-
callback.call(new_mime)
-
end
-
end
-
-
1
def parse(accept_header)
-
if accept_header !~ /,/
-
accept_header = accept_header.split(PARAMETER_SEPARATOR_REGEXP).first
-
parse_trailing_star(accept_header) || [Mime::Type.lookup(accept_header)].compact
-
else
-
list, index = AcceptList.new, 0
-
accept_header.split(',').each do |header|
-
params, q = header.split(PARAMETER_SEPARATOR_REGEXP)
-
if params.present?
-
params.strip!
-
-
params = parse_trailing_star(params) || [params]
-
-
params.each do |m|
-
list << AcceptItem.new(index, m.to_s, q)
-
index += 1
-
end
-
end
-
end
-
list.assort!
-
end
-
end
-
-
1
def parse_trailing_star(accept_header)
-
parse_data_with_trailing_star($1) if accept_header =~ TRAILING_STAR_REGEXP
-
end
-
-
# For an input of <tt>'text'</tt>, returns <tt>[Mime::JSON, Mime::XML, Mime::ICS,
-
# Mime::HTML, Mime::CSS, Mime::CSV, Mime::JS, Mime::YAML, Mime::TEXT]</tt>.
-
#
-
# For an input of <tt>'application'</tt>, returns <tt>[Mime::HTML, Mime::JS,
-
# Mime::XML, Mime::YAML, Mime::ATOM, Mime::JSON, Mime::RSS, Mime::URL_ENCODED_FORM]</tt>.
-
1
def parse_data_with_trailing_star(input)
-
Mime::SET.select { |m| m =~ input }
-
end
-
-
# This method is opposite of register method.
-
#
-
# Usage:
-
#
-
# Mime::Type.unregister(:mobile)
-
1
def unregister(symbol)
-
symbol = symbol.upcase
-
mime = Mime.const_get(symbol)
-
Mime.instance_eval { remove_const(symbol) }
-
-
SET.delete_if { |v| v.eql?(mime) }
-
LOOKUP.delete_if { |_,v| v.eql?(mime) }
-
EXTENSION_LOOKUP.delete_if { |_,v| v.eql?(mime) }
-
end
-
end
-
-
1
def initialize(string, symbol = nil, synonyms = [])
-
23
@symbol, @synonyms = symbol, synonyms
-
23
@string = string
-
end
-
-
1
def to_s
-
@string
-
end
-
-
1
def to_str
-
to_s
-
end
-
-
1
def to_sym
-
44
@symbol
-
end
-
-
1
def ref
-
to_sym || to_s
-
end
-
-
1
def ===(list)
-
if list.is_a?(Array)
-
(@synonyms + [ self ]).any? { |synonym| list.include?(synonym) }
-
else
-
super
-
end
-
end
-
-
1
def ==(mime_type)
-
return false if mime_type.blank?
-
(@synonyms + [ self ]).any? do |synonym|
-
synonym.to_s == mime_type.to_s || synonym.to_sym == mime_type.to_sym
-
end
-
end
-
-
1
def =~(mime_type)
-
return false if mime_type.blank?
-
regexp = Regexp.new(Regexp.quote(mime_type.to_s))
-
(@synonyms + [ self ]).any? do |synonym|
-
synonym.to_s =~ regexp
-
end
-
end
-
-
1
def html?
-
@@html_types.include?(to_sym) || @string =~ /html/
-
end
-
-
-
1
private
-
-
1
def to_ary; end
-
1
def to_a; end
-
-
1
def method_missing(method, *args)
-
if method.to_s.ends_with? '?'
-
method[0..-2].downcase.to_sym == to_sym
-
else
-
super
-
end
-
end
-
-
1
def respond_to_missing?(method, include_private = false) #:nodoc:
-
method.to_s.ends_with? '?'
-
end
-
end
-
-
1
class NullType
-
1
include Singleton
-
-
1
def nil?
-
true
-
end
-
-
1
def ref; end
-
-
1
def respond_to_missing?(method, include_private = false)
-
method.to_s.ends_with? '?'
-
end
-
-
1
private
-
1
def method_missing(method, *args)
-
false if method.to_s.ends_with? '?'
-
end
-
end
-
end
-
-
1
require 'action_dispatch/http/mime_types'
-
# Build list of Mime types for HTTP responses
-
# http://www.iana.org/assignments/media-types/
-
-
1
Mime::Type.register "text/html", :html, %w( application/xhtml+xml ), %w( xhtml )
-
1
Mime::Type.register "text/plain", :text, [], %w(txt)
-
1
Mime::Type.register "text/javascript", :js, %w( application/javascript application/x-javascript )
-
1
Mime::Type.register "text/css", :css
-
1
Mime::Type.register "text/calendar", :ics
-
1
Mime::Type.register "text/csv", :csv
-
1
Mime::Type.register "text/vcard", :vcf
-
-
1
Mime::Type.register "image/png", :png, [], %w(png)
-
1
Mime::Type.register "image/jpeg", :jpeg, [], %w(jpg jpeg jpe pjpeg)
-
1
Mime::Type.register "image/gif", :gif, [], %w(gif)
-
1
Mime::Type.register "image/bmp", :bmp, [], %w(bmp)
-
1
Mime::Type.register "image/tiff", :tiff, [], %w(tif tiff)
-
-
1
Mime::Type.register "video/mpeg", :mpeg, [], %w(mpg mpeg mpe)
-
-
1
Mime::Type.register "application/xml", :xml, %w( text/xml application/x-xml )
-
1
Mime::Type.register "application/rss+xml", :rss
-
1
Mime::Type.register "application/atom+xml", :atom
-
1
Mime::Type.register "application/x-yaml", :yaml, %w( text/yaml )
-
-
1
Mime::Type.register "multipart/form-data", :multipart_form
-
1
Mime::Type.register "application/x-www-form-urlencoded", :url_encoded_form
-
-
# http://www.ietf.org/rfc/rfc4627.txt
-
# http://www.json.org/JSONRequest.html
-
1
Mime::Type.register "application/json", :json, %w( text/x-json application/jsonrequest )
-
-
1
Mime::Type.register "application/pdf", :pdf, [], %w(pdf)
-
1
Mime::Type.register "application/zip", :zip, [], %w(zip)
-
-
# Create Mime::ALL but do not add it to the SET.
-
1
Mime::ALL = Mime::Type.new("*/*", :all, [])
-
1
module ActionDispatch
-
1
module Http
-
1
class ParameterFilter
-
1
FILTERED = '[FILTERED]'.freeze # :nodoc:
-
-
1
def initialize(filters = [])
-
2
@filters = filters
-
end
-
-
1
def filter(params)
-
compiled_filter.call(params)
-
end
-
-
1
private
-
-
1
def compiled_filter
-
@compiled_filter ||= CompiledFilter.compile(@filters)
-
end
-
-
1
class CompiledFilter # :nodoc:
-
1
def self.compile(filters)
-
return lambda { |params| params.dup } if filters.empty?
-
-
strings, regexps, blocks = [], [], []
-
-
filters.each do |item|
-
case item
-
when Proc
-
blocks << item
-
when Regexp
-
regexps << item
-
else
-
strings << item.to_s
-
end
-
end
-
-
regexps << Regexp.new(strings.join('|'), true) unless strings.empty?
-
new regexps, blocks
-
end
-
-
1
attr_reader :regexps, :blocks
-
-
1
def initialize(regexps, blocks)
-
@regexps = regexps
-
@blocks = blocks
-
end
-
-
1
def call(original_params)
-
filtered_params = {}
-
-
original_params.each do |key, value|
-
if regexps.any? { |r| key =~ r }
-
value = FILTERED
-
elsif value.is_a?(Hash)
-
value = call(value)
-
elsif value.is_a?(Array)
-
value = value.map { |v| v.is_a?(Hash) ? call(v) : v }
-
elsif blocks.any?
-
key = key.dup
-
value = value.dup if value.duplicable?
-
blocks.each { |b| b.call(key, value) }
-
end
-
-
filtered_params[key] = value
-
end
-
-
filtered_params
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/keys'
-
1
require 'active_support/core_ext/hash/indifferent_access'
-
-
1
module ActionDispatch
-
1
module Http
-
1
module Parameters
-
1
def initialize(env)
-
super
-
@symbolized_path_params = nil
-
end
-
-
# Returns both GET and POST \parameters in a single hash.
-
1
def parameters
-
@env["action_dispatch.request.parameters"] ||= begin
-
params = begin
-
request_parameters.merge(query_parameters)
-
rescue EOFError
-
query_parameters.dup
-
end
-
params.merge!(path_parameters)
-
params.with_indifferent_access
-
end
-
end
-
1
alias :params :parameters
-
-
1
def path_parameters=(parameters) #:nodoc:
-
@symbolized_path_params = nil
-
@env.delete("action_dispatch.request.parameters")
-
@env["action_dispatch.request.path_parameters"] = parameters
-
end
-
-
# The same as <tt>path_parameters</tt> with explicitly symbolized keys.
-
1
def symbolized_path_parameters
-
@symbolized_path_params ||= path_parameters.symbolize_keys
-
end
-
-
# Returns a hash with the \parameters used to form the \path of the request.
-
# Returned hash keys are strings:
-
#
-
# {'action' => 'my_action', 'controller' => 'my_controller'}
-
#
-
# See <tt>symbolized_path_parameters</tt> for symbolized keys.
-
1
def path_parameters
-
@env["action_dispatch.request.path_parameters"] ||= {}
-
end
-
-
1
def reset_parameters #:nodoc:
-
@env.delete("action_dispatch.request.parameters")
-
end
-
-
1
private
-
-
# Convert nested Hash to HashWithIndifferentAccess
-
# and UTF-8 encode both keys and values in nested Hash.
-
#
-
# TODO: Validate that the characters are UTF-8. If they aren't,
-
# you'll get a weird error down the road, but our form handling
-
# should really prevent that from happening
-
1
def normalize_encode_params(params)
-
case params
-
when String
-
params.force_encoding(Encoding::UTF_8).encode!
-
when Hash
-
if params.has_key?(:tempfile)
-
UploadedFile.new(params)
-
else
-
params.each_with_object({}) do |(key, val), new_hash|
-
new_key = key.is_a?(String) ? key.dup.force_encoding(Encoding::UTF_8).encode! : key
-
new_hash[new_key] = if val.is_a?(Array)
-
val.map! { |el| normalize_encode_params(el) }
-
else
-
normalize_encode_params(val)
-
end
-
end.with_indifferent_access
-
end
-
else
-
params
-
end
-
end
-
end
-
end
-
end
-
1
require 'stringio'
-
-
1
require 'active_support/inflector'
-
1
require 'action_dispatch/http/headers'
-
1
require 'action_controller/metal/exceptions'
-
1
require 'rack/request'
-
1
require 'action_dispatch/http/cache'
-
1
require 'action_dispatch/http/mime_negotiation'
-
1
require 'action_dispatch/http/parameters'
-
1
require 'action_dispatch/http/filter_parameters'
-
1
require 'action_dispatch/http/upload'
-
1
require 'action_dispatch/http/url'
-
1
require 'active_support/core_ext/array/conversions'
-
-
1
module ActionDispatch
-
1
class Request < Rack::Request
-
1
include ActionDispatch::Http::Cache::Request
-
1
include ActionDispatch::Http::MimeNegotiation
-
1
include ActionDispatch::Http::Parameters
-
1
include ActionDispatch::Http::FilterParameters
-
1
include ActionDispatch::Http::URL
-
-
1
autoload :Session, 'action_dispatch/request/session'
-
1
autoload :Utils, 'action_dispatch/request/utils'
-
-
1
LOCALHOST = Regexp.union [/^127\.0\.0\.\d{1,3}$/, /^::1$/, /^0:0:0:0:0:0:0:1(%.*)?$/]
-
-
1
ENV_METHODS = %w[ AUTH_TYPE GATEWAY_INTERFACE
-
PATH_TRANSLATED REMOTE_HOST
-
REMOTE_IDENT REMOTE_USER REMOTE_ADDR
-
SERVER_NAME SERVER_PROTOCOL
-
-
HTTP_ACCEPT HTTP_ACCEPT_CHARSET HTTP_ACCEPT_ENCODING
-
HTTP_ACCEPT_LANGUAGE HTTP_CACHE_CONTROL HTTP_FROM
-
HTTP_NEGOTIATE HTTP_PRAGMA ].freeze
-
-
1
ENV_METHODS.each do |env|
-
17
class_eval <<-METHOD, __FILE__, __LINE__ + 1
-
def #{env.sub(/^HTTP_/n, '').downcase} # def accept_charset
-
@env["#{env}"] # @env["HTTP_ACCEPT_CHARSET"]
-
end # end
-
METHOD
-
end
-
-
1
def initialize(env)
-
super
-
@method = nil
-
@request_method = nil
-
@remote_ip = nil
-
@original_fullpath = nil
-
@fullpath = nil
-
@ip = nil
-
@uuid = nil
-
end
-
-
1
def key?(key)
-
@env.key?(key)
-
end
-
-
# List of HTTP request methods from the following RFCs:
-
# Hypertext Transfer Protocol -- HTTP/1.1 (http://www.ietf.org/rfc/rfc2616.txt)
-
# HTTP Extensions for Distributed Authoring -- WEBDAV (http://www.ietf.org/rfc/rfc2518.txt)
-
# Versioning Extensions to WebDAV (http://www.ietf.org/rfc/rfc3253.txt)
-
# Ordered Collections Protocol (WebDAV) (http://www.ietf.org/rfc/rfc3648.txt)
-
# Web Distributed Authoring and Versioning (WebDAV) Access Control Protocol (http://www.ietf.org/rfc/rfc3744.txt)
-
# Web Distributed Authoring and Versioning (WebDAV) SEARCH (http://www.ietf.org/rfc/rfc5323.txt)
-
# PATCH Method for HTTP (http://www.ietf.org/rfc/rfc5789.txt)
-
1
RFC2616 = %w(OPTIONS GET HEAD POST PUT DELETE TRACE CONNECT)
-
1
RFC2518 = %w(PROPFIND PROPPATCH MKCOL COPY MOVE LOCK UNLOCK)
-
1
RFC3253 = %w(VERSION-CONTROL REPORT CHECKOUT CHECKIN UNCHECKOUT MKWORKSPACE UPDATE LABEL MERGE BASELINE-CONTROL MKACTIVITY)
-
1
RFC3648 = %w(ORDERPATCH)
-
1
RFC3744 = %w(ACL)
-
1
RFC5323 = %w(SEARCH)
-
1
RFC5789 = %w(PATCH)
-
-
1
HTTP_METHODS = RFC2616 + RFC2518 + RFC3253 + RFC3648 + RFC3744 + RFC5323 + RFC5789
-
-
1
HTTP_METHOD_LOOKUP = {}
-
-
# Populate the HTTP method lookup cache
-
1
HTTP_METHODS.each { |method|
-
30
HTTP_METHOD_LOOKUP[method] = method.underscore.to_sym
-
}
-
-
# Returns the HTTP \method that the application should see.
-
# In the case where the \method was overridden by a middleware
-
# (for instance, if a HEAD request was converted to a GET,
-
# or if a _method parameter was used to determine the \method
-
# the application should use), this \method returns the overridden
-
# value, not the original.
-
1
def request_method
-
@request_method ||= check_method(env["REQUEST_METHOD"])
-
end
-
-
# Returns a symbol form of the #request_method
-
1
def request_method_symbol
-
HTTP_METHOD_LOOKUP[request_method]
-
end
-
-
# Returns the original value of the environment's REQUEST_METHOD,
-
# even if it was overridden by middleware. See #request_method for
-
# more information.
-
1
def method
-
@method ||= check_method(env["rack.methodoverride.original_method"] || env['REQUEST_METHOD'])
-
end
-
-
# Returns a symbol form of the #method
-
1
def method_symbol
-
HTTP_METHOD_LOOKUP[method]
-
end
-
-
# Is this a GET (or HEAD) request?
-
# Equivalent to <tt>request.request_method_symbol == :get</tt>.
-
1
def get?
-
HTTP_METHOD_LOOKUP[request_method] == :get
-
end
-
-
# Is this a POST request?
-
# Equivalent to <tt>request.request_method_symbol == :post</tt>.
-
1
def post?
-
HTTP_METHOD_LOOKUP[request_method] == :post
-
end
-
-
# Is this a PATCH request?
-
# Equivalent to <tt>request.request_method == :patch</tt>.
-
1
def patch?
-
HTTP_METHOD_LOOKUP[request_method] == :patch
-
end
-
-
# Is this a PUT request?
-
# Equivalent to <tt>request.request_method_symbol == :put</tt>.
-
1
def put?
-
HTTP_METHOD_LOOKUP[request_method] == :put
-
end
-
-
# Is this a DELETE request?
-
# Equivalent to <tt>request.request_method_symbol == :delete</tt>.
-
1
def delete?
-
HTTP_METHOD_LOOKUP[request_method] == :delete
-
end
-
-
# Is this a HEAD request?
-
# Equivalent to <tt>request.request_method_symbol == :head</tt>.
-
1
def head?
-
HTTP_METHOD_LOOKUP[request_method] == :head
-
end
-
-
# Provides access to the request's HTTP headers, for example:
-
#
-
# request.headers["Content-Type"] # => "text/plain"
-
1
def headers
-
Http::Headers.new(@env)
-
end
-
-
1
def original_fullpath
-
@original_fullpath ||= (env["ORIGINAL_FULLPATH"] || fullpath)
-
end
-
-
# Returns the +String+ full path including params of the last URL requested.
-
#
-
# # get "/articles"
-
# request.fullpath # => "/articles"
-
#
-
# # get "/articles?page=2"
-
# request.fullpath # => "/articles?page=2"
-
1
def fullpath
-
@fullpath ||= super
-
end
-
-
# Returns the original request URL as a +String+.
-
#
-
# # get "/articles?page=2"
-
# request.original_url # => "http://www.example.com/articles?page=2"
-
1
def original_url
-
base_url + original_fullpath
-
end
-
-
# The +String+ MIME type of the request.
-
#
-
# # get "/articles"
-
# request.media_type # => "application/x-www-form-urlencoded"
-
1
def media_type
-
content_mime_type.to_s
-
end
-
-
# Returns the content length of the request as an integer.
-
1
def content_length
-
super.to_i
-
end
-
-
# Returns true if the "X-Requested-With" header contains "XMLHttpRequest"
-
# (case-insensitive). All major JavaScript libraries send this header with
-
# every Ajax request.
-
1
def xml_http_request?
-
@env['HTTP_X_REQUESTED_WITH'] =~ /XMLHttpRequest/i
-
end
-
1
alias :xhr? :xml_http_request?
-
-
1
def ip
-
@ip ||= super
-
end
-
-
# Originating IP address, usually set by the RemoteIp middleware.
-
1
def remote_ip
-
@remote_ip ||= (@env["action_dispatch.remote_ip"] || ip).to_s
-
end
-
-
# Returns the unique request id, which is based off either the X-Request-Id header that can
-
# be generated by a firewall, load balancer, or web server or by the RequestId middleware
-
# (which sets the action_dispatch.request_id environment variable).
-
#
-
# This unique ID is useful for tracing a request from end-to-end as part of logging or debugging.
-
# This relies on the rack variable set by the ActionDispatch::RequestId middleware.
-
1
def uuid
-
@uuid ||= env["action_dispatch.request_id"]
-
end
-
-
# Returns the lowercase name of the HTTP server software.
-
1
def server_software
-
(@env['SERVER_SOFTWARE'] && /^([a-zA-Z]+)/ =~ @env['SERVER_SOFTWARE']) ? $1.downcase : nil
-
end
-
-
# Read the request \body. This is useful for web services that need to
-
# work with raw requests directly.
-
1
def raw_post
-
unless @env.include? 'RAW_POST_DATA'
-
raw_post_body = body
-
@env['RAW_POST_DATA'] = raw_post_body.read(content_length)
-
raw_post_body.rewind if raw_post_body.respond_to?(:rewind)
-
end
-
@env['RAW_POST_DATA']
-
end
-
-
# The request body is an IO input stream. If the RAW_POST_DATA environment
-
# variable is already set, wrap it in a StringIO.
-
1
def body
-
if raw_post = @env['RAW_POST_DATA']
-
raw_post.force_encoding(Encoding::BINARY)
-
StringIO.new(raw_post)
-
else
-
@env['rack.input']
-
end
-
end
-
-
1
def form_data?
-
FORM_DATA_MEDIA_TYPES.include?(content_mime_type.to_s)
-
end
-
-
1
def body_stream #:nodoc:
-
@env['rack.input']
-
end
-
-
# TODO This should be broken apart into AD::Request::Session and probably
-
# be included by the session middleware.
-
1
def reset_session
-
if session && session.respond_to?(:destroy)
-
session.destroy
-
else
-
self.session = {}
-
end
-
@env['action_dispatch.request.flash_hash'] = nil
-
end
-
-
1
def session=(session) #:nodoc:
-
Session.set @env, session
-
end
-
-
1
def session_options=(options)
-
Session::Options.set @env, options
-
end
-
-
# Override Rack's GET method to support indifferent access
-
1
def GET
-
@env["action_dispatch.request.query_parameters"] ||= Utils.deep_munge((normalize_encode_params(super) || {}))
-
rescue TypeError => e
-
raise ActionController::BadRequest.new(:query, e)
-
end
-
1
alias :query_parameters :GET
-
-
# Override Rack's POST method to support indifferent access
-
1
def POST
-
@env["action_dispatch.request.request_parameters"] ||= Utils.deep_munge((normalize_encode_params(super) || {}))
-
rescue TypeError => e
-
raise ActionController::BadRequest.new(:request, e)
-
end
-
1
alias :request_parameters :POST
-
-
# Returns the authorization header regardless of whether it was specified directly or through one of the
-
# proxy alternatives.
-
1
def authorization
-
@env['HTTP_AUTHORIZATION'] ||
-
@env['X-HTTP_AUTHORIZATION'] ||
-
@env['X_HTTP_AUTHORIZATION'] ||
-
@env['REDIRECT_X_HTTP_AUTHORIZATION']
-
end
-
-
# True if the request came from localhost, 127.0.0.1.
-
1
def local?
-
LOCALHOST =~ remote_addr && LOCALHOST =~ remote_ip
-
end
-
-
# Extracted into ActionDispatch::Request::Utils.deep_munge, but kept here for backwards compatibility.
-
1
def deep_munge(hash)
-
ActiveSupport::Deprecation.warn(
-
"This method has been extracted into ActionDispatch::Request::Utils.deep_munge. Please start using that instead."
-
)
-
-
Utils.deep_munge(hash)
-
end
-
-
1
protected
-
1
def parse_query(qs)
-
Utils.deep_munge(super)
-
end
-
-
1
private
-
1
def check_method(name)
-
HTTP_METHOD_LOOKUP[name] || raise(ActionController::UnknownHttpMethod, "#{name}, accepted HTTP methods are #{HTTP_METHODS.to_sentence(:locale => :en)}")
-
name
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'action_dispatch/http/filter_redirect'
-
1
require 'monitor'
-
-
1
module ActionDispatch # :nodoc:
-
# Represents an HTTP response generated by a controller action. Use it to
-
# retrieve the current state of the response, or customize the response. It can
-
# either represent a real HTTP response (i.e. one that is meant to be sent
-
# back to the web browser) or a TestResponse (i.e. one that is generated
-
# from integration tests).
-
#
-
# \Response is mostly a Ruby on \Rails framework implementation detail, and
-
# should never be used directly in controllers. Controllers should use the
-
# methods defined in ActionController::Base instead. For example, if you want
-
# to set the HTTP response's content MIME type, then use
-
# ActionControllerBase#headers instead of Response#headers.
-
#
-
# Nevertheless, integration tests may want to inspect controller responses in
-
# more detail, and that's when \Response can be useful for application
-
# developers. Integration test methods such as
-
# ActionDispatch::Integration::Session#get and
-
# ActionDispatch::Integration::Session#post return objects of type
-
# TestResponse (which are of course also of type \Response).
-
#
-
# For example, the following demo integration test prints the body of the
-
# controller response to the console:
-
#
-
# class DemoControllerTest < ActionDispatch::IntegrationTest
-
# def test_print_root_path_to_console
-
# get('/')
-
# puts response.body
-
# end
-
# end
-
1
class Response
-
# The request that the response is responding to.
-
1
attr_accessor :request
-
-
# The HTTP status code.
-
1
attr_reader :status
-
-
1
attr_writer :sending_file
-
-
# Get and set headers for this response.
-
1
attr_accessor :header
-
-
1
alias_method :headers=, :header=
-
1
alias_method :headers, :header
-
-
1
delegate :[], :[]=, :to => :@header
-
1
delegate :each, :to => :@stream
-
-
# Sets the HTTP response's content MIME type. For example, in the controller
-
# you could write this:
-
#
-
# response.content_type = "text/plain"
-
#
-
# If a character set has been defined for this response (see charset=) then
-
# the character set information will also be included in the content type
-
# information.
-
1
attr_reader :content_type
-
-
# The charset of the response. HTML wants to know the encoding of the
-
# content you're giving them, so we need to send that along.
-
1
attr_accessor :charset
-
-
1
CONTENT_TYPE = "Content-Type".freeze
-
1
SET_COOKIE = "Set-Cookie".freeze
-
1
LOCATION = "Location".freeze
-
1
NO_CONTENT_CODES = [204, 304]
-
-
3
cattr_accessor(:default_charset) { "utf-8" }
-
1
cattr_accessor(:default_headers)
-
-
1
include Rack::Response::Helpers
-
1
include ActionDispatch::Http::FilterRedirect
-
1
include ActionDispatch::Http::Cache::Response
-
1
include MonitorMixin
-
-
1
class Buffer # :nodoc:
-
1
def initialize(response, buf)
-
@response = response
-
@buf = buf
-
@closed = false
-
end
-
-
1
def write(string)
-
raise IOError, "closed stream" if closed?
-
-
@response.commit!
-
@buf.push string
-
end
-
-
1
def each(&block)
-
@response.sending!
-
x = @buf.each(&block)
-
@response.sent!
-
x
-
end
-
-
1
def close
-
@response.commit!
-
@closed = true
-
end
-
-
1
def closed?
-
@closed
-
end
-
end
-
-
# The underlying body, as a streamable object.
-
1
attr_reader :stream
-
-
1
def initialize(status = 200, header = {}, body = [])
-
super()
-
-
header = merge_default_headers(header, self.class.default_headers)
-
-
self.body, self.header, self.status = body, header, status
-
-
@sending_file = false
-
@blank = false
-
@cv = new_cond
-
@committed = false
-
@sending = false
-
@sent = false
-
@content_type = nil
-
@charset = nil
-
-
if content_type = self[CONTENT_TYPE]
-
type, charset = content_type.split(/;\s*charset=/)
-
@content_type = Mime::Type.lookup(type)
-
@charset = charset || self.class.default_charset
-
end
-
-
prepare_cache_control!
-
-
yield self if block_given?
-
end
-
-
1
def await_commit
-
synchronize do
-
@cv.wait_until { @committed }
-
end
-
end
-
-
1
def await_sent
-
synchronize { @cv.wait_until { @sent } }
-
end
-
-
1
def commit!
-
synchronize do
-
before_committed
-
@committed = true
-
@cv.broadcast
-
end
-
end
-
-
1
def sending!
-
synchronize do
-
before_sending
-
@sending = true
-
@cv.broadcast
-
end
-
end
-
-
1
def sent!
-
synchronize do
-
@sent = true
-
@cv.broadcast
-
end
-
end
-
-
1
def sending?; synchronize { @sending }; end
-
1
def committed?; synchronize { @committed }; end
-
1
def sent?; synchronize { @sent }; end
-
-
# Sets the HTTP status code.
-
1
def status=(status)
-
@status = Rack::Utils.status_code(status)
-
end
-
-
# Sets the HTTP content type.
-
1
def content_type=(content_type)
-
@content_type = content_type.to_s
-
end
-
-
# The response code of the request.
-
1
def response_code
-
@status
-
end
-
-
# Returns a string to ensure compatibility with <tt>Net::HTTPResponse</tt>.
-
1
def code
-
@status.to_s
-
end
-
-
# Returns the corresponding message for the current HTTP status code:
-
#
-
# response.status = 200
-
# response.message # => "OK"
-
#
-
# response.status = 404
-
# response.message # => "Not Found"
-
#
-
1
def message
-
Rack::Utils::HTTP_STATUS_CODES[@status]
-
end
-
1
alias_method :status_message, :message
-
-
1
def respond_to?(method, include_private = false)
-
if method.to_s == 'to_path'
-
stream.respond_to?(method)
-
else
-
super
-
end
-
end
-
-
1
def to_path
-
stream.to_path
-
end
-
-
# Returns the content of the response as a string. This contains the contents
-
# of any calls to <tt>render</tt>.
-
1
def body
-
strings = []
-
each { |part| strings << part.to_s }
-
strings.join
-
end
-
-
1
EMPTY = " "
-
-
# Allows you to manually set or override the response body.
-
1
def body=(body)
-
@blank = true if body == EMPTY
-
-
if body.respond_to?(:to_path)
-
@stream = body
-
else
-
synchronize do
-
@stream = build_buffer self, munge_body_object(body)
-
end
-
end
-
end
-
-
1
def body_parts
-
parts = []
-
@stream.each { |x| parts << x }
-
parts
-
end
-
-
1
def set_cookie(key, value)
-
::Rack::Utils.set_cookie_header!(header, key, value)
-
end
-
-
1
def delete_cookie(key, value={})
-
::Rack::Utils.delete_cookie_header!(header, key, value)
-
end
-
-
# The location header we'll be responding with.
-
1
def location
-
headers[LOCATION]
-
end
-
1
alias_method :redirect_url, :location
-
-
# Sets the location header we'll be responding with.
-
1
def location=(url)
-
headers[LOCATION] = url
-
end
-
-
1
def close
-
stream.close if stream.respond_to?(:close)
-
end
-
-
# Turns the Response into a Rack-compatible array of the status, headers,
-
# and body.
-
1
def to_a
-
rack_response @status, @header.to_hash
-
end
-
1
alias prepare! to_a
-
1
alias to_ary to_a
-
-
# Returns the response cookies, converted to a Hash of (name => value) pairs
-
#
-
# assert_equal 'AuthorOfNewPage', r.cookies['author']
-
1
def cookies
-
cookies = {}
-
if header = self[SET_COOKIE]
-
header = header.split("\n") if header.respond_to?(:to_str)
-
header.each do |cookie|
-
if pair = cookie.split(';').first
-
key, value = pair.split("=").map { |v| Rack::Utils.unescape(v) }
-
cookies[key] = value
-
end
-
end
-
end
-
cookies
-
end
-
-
1
private
-
-
1
def before_committed
-
end
-
-
1
def before_sending
-
end
-
-
1
def merge_default_headers(original, default)
-
return original unless default.respond_to?(:merge)
-
-
default.merge(original)
-
end
-
-
1
def build_buffer(response, body)
-
Buffer.new response, body
-
end
-
-
1
def munge_body_object(body)
-
body.respond_to?(:each) ? body : [body]
-
end
-
-
1
def assign_default_content_type_and_charset!(headers)
-
return if headers[CONTENT_TYPE].present?
-
-
@content_type ||= Mime::HTML
-
@charset ||= self.class.default_charset unless @charset == false
-
-
type = @content_type.to_s.dup
-
type << "; charset=#{@charset}" if append_charset?
-
-
headers[CONTENT_TYPE] = type
-
end
-
-
1
def append_charset?
-
!@sending_file && @charset != false
-
end
-
-
1
def rack_response(status, header)
-
assign_default_content_type_and_charset!(header)
-
handle_conditional_get!
-
-
header[SET_COOKIE] = header[SET_COOKIE].join("\n") if header[SET_COOKIE].respond_to?(:join)
-
-
if NO_CONTENT_CODES.include?(@status)
-
header.delete CONTENT_TYPE
-
[status, header, []]
-
else
-
[status, header, Rack::BodyProxy.new(self){}]
-
end
-
end
-
end
-
end
-
1
module ActionDispatch
-
1
module Http
-
# Models uploaded files.
-
#
-
# The actual file is accessible via the +tempfile+ accessor, though some
-
# of its interface is available directly for convenience.
-
#
-
# Uploaded files are temporary files whose lifespan is one request. When
-
# the object is finalized Ruby unlinks the file, so there is no need to
-
# clean them with a separate maintenance task.
-
1
class UploadedFile
-
# The basename of the file in the client.
-
1
attr_accessor :original_filename
-
-
# A string with the MIME type of the file.
-
1
attr_accessor :content_type
-
-
# A +Tempfile+ object with the actual uploaded file. Note that some of
-
# its interface is available directly.
-
1
attr_accessor :tempfile
-
-
# A string with the headers of the multipart request.
-
1
attr_accessor :headers
-
-
1
def initialize(hash) # :nodoc:
-
@tempfile = hash[:tempfile]
-
raise(ArgumentError, ':tempfile is required') unless @tempfile
-
-
@original_filename = encode_filename(hash[:filename])
-
@content_type = hash[:type]
-
@headers = hash[:head]
-
end
-
-
# Shortcut for +tempfile.read+.
-
1
def read(length=nil, buffer=nil)
-
@tempfile.read(length, buffer)
-
end
-
-
# Shortcut for +tempfile.open+.
-
1
def open
-
@tempfile.open
-
end
-
-
# Shortcut for +tempfile.close+.
-
1
def close(unlink_now=false)
-
@tempfile.close(unlink_now)
-
end
-
-
# Shortcut for +tempfile.path+.
-
1
def path
-
@tempfile.path
-
end
-
-
# Shortcut for +tempfile.rewind+.
-
1
def rewind
-
@tempfile.rewind
-
end
-
-
# Shortcut for +tempfile.size+.
-
1
def size
-
@tempfile.size
-
end
-
-
# Shortcut for +tempfile.eof?+.
-
1
def eof?
-
@tempfile.eof?
-
end
-
-
1
private
-
-
1
def encode_filename(filename)
-
# Encode the filename in the utf8 encoding, unless it is nil
-
filename.force_encoding(Encoding::UTF_8).encode! if filename
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/hash/slice'
-
-
1
module ActionDispatch
-
1
module Http
-
1
module URL
-
1
IP_HOST_REGEXP = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/
-
1
HOST_REGEXP = /(^.*:\/\/)?([^:]+)(?::(\d+$))?/
-
1
PROTOCOL_REGEXP = /^([^:]+)(:)?(\/\/)?$/
-
-
1
mattr_accessor :tld_length
-
1
self.tld_length = 1
-
-
1
class << self
-
1
def extract_domain(host, tld_length = @@tld_length)
-
host.split('.').last(1 + tld_length).join('.') if named_host?(host)
-
end
-
-
1
def extract_subdomains(host, tld_length = @@tld_length)
-
if named_host?(host)
-
parts = host.split('.')
-
parts[0..-(tld_length + 2)]
-
else
-
[]
-
end
-
end
-
-
1
def extract_subdomain(host, tld_length = @@tld_length)
-
extract_subdomains(host, tld_length).join('.')
-
end
-
-
1
def url_for(options = {})
-
options = options.dup
-
path = options.delete(:script_name).to_s.chomp("/")
-
path << options.delete(:path).to_s
-
-
params = options[:params].is_a?(Hash) ? options[:params] : options.slice(:params)
-
params.reject! { |_,v| v.to_param.nil? }
-
-
result = build_host_url(options)
-
if options[:trailing_slash]
-
if path.include?('?')
-
result << path.sub(/\?/, '/\&')
-
else
-
result << path.sub(/[^\/]\z|\A\z/, '\&/')
-
end
-
else
-
result << path
-
end
-
result << "?#{params.to_query}" unless params.empty?
-
result << "##{Journey::Router::Utils.escape_fragment(options[:anchor].to_param.to_s)}" if options[:anchor]
-
result
-
end
-
-
1
private
-
-
1
def build_host_url(options)
-
if options[:host].blank? && options[:only_path].blank?
-
raise ArgumentError, 'Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true'
-
end
-
-
result = ""
-
-
unless options[:only_path]
-
if match = options[:host].match(HOST_REGEXP)
-
options[:protocol] ||= match[1] unless options[:protocol] == false
-
options[:host] = match[2]
-
options[:port] = match[3] unless options.key?(:port)
-
end
-
-
options[:protocol] = normalize_protocol(options)
-
options[:host] = normalize_host(options)
-
options[:port] = normalize_port(options)
-
-
result << options[:protocol]
-
result << rewrite_authentication(options)
-
result << options[:host]
-
result << ":#{options[:port]}" if options[:port]
-
end
-
result
-
end
-
-
1
def named_host?(host)
-
host && IP_HOST_REGEXP !~ host
-
end
-
-
1
def same_host?(options)
-
(options[:subdomain] == true || !options.key?(:subdomain)) && options[:domain].nil?
-
end
-
-
1
def rewrite_authentication(options)
-
if options[:user] && options[:password]
-
"#{Rack::Utils.escape(options[:user])}:#{Rack::Utils.escape(options[:password])}@"
-
else
-
""
-
end
-
end
-
-
1
def normalize_protocol(options)
-
case options[:protocol]
-
when nil
-
"http://"
-
when false, "//"
-
"//"
-
when PROTOCOL_REGEXP
-
"#{$1}://"
-
else
-
raise ArgumentError, "Invalid :protocol option: #{options[:protocol].inspect}"
-
end
-
end
-
-
1
def normalize_host(options)
-
return options[:host] if !named_host?(options[:host]) || same_host?(options)
-
-
tld_length = options[:tld_length] || @@tld_length
-
-
host = ""
-
if options[:subdomain] == true || !options.key?(:subdomain)
-
host << extract_subdomain(options[:host], tld_length).to_param
-
elsif options[:subdomain].present?
-
host << options[:subdomain].to_param
-
end
-
host << "." unless host.empty?
-
host << (options[:domain] || extract_domain(options[:host], tld_length))
-
host
-
end
-
-
1
def normalize_port(options)
-
return nil if options[:port].nil? || options[:port] == false
-
-
case options[:protocol]
-
when "//"
-
nil
-
when "https://"
-
options[:port].to_i == 443 ? nil : options[:port]
-
else
-
options[:port].to_i == 80 ? nil : options[:port]
-
end
-
end
-
end
-
-
1
def initialize(env)
-
super
-
@protocol = nil
-
@port = nil
-
end
-
-
# Returns the complete URL used for this request.
-
1
def url
-
protocol + host_with_port + fullpath
-
end
-
-
# Returns 'https://' if this is an SSL request and 'http://' otherwise.
-
1
def protocol
-
@protocol ||= ssl? ? 'https://' : 'http://'
-
end
-
-
# Returns the \host for this request, such as "example.com".
-
1
def raw_host_with_port
-
if forwarded = env["HTTP_X_FORWARDED_HOST"]
-
forwarded.split(/,\s?/).last
-
else
-
env['HTTP_HOST'] || "#{env['SERVER_NAME'] || env['SERVER_ADDR']}:#{env['SERVER_PORT']}"
-
end
-
end
-
-
# Returns the host for this request, such as example.com.
-
1
def host
-
raw_host_with_port.sub(/:\d+$/, '')
-
end
-
-
# Returns a \host:\port string for this request, such as "example.com" or
-
# "example.com:8080".
-
1
def host_with_port
-
"#{host}#{port_string}"
-
end
-
-
# Returns the port number of this request as an integer.
-
1
def port
-
@port ||= begin
-
if raw_host_with_port =~ /:(\d+)$/
-
$1.to_i
-
else
-
standard_port
-
end
-
end
-
end
-
-
# Returns the standard \port number for this request's protocol.
-
1
def standard_port
-
case protocol
-
when 'https://' then 443
-
else 80
-
end
-
end
-
-
# Returns whether this request is using the standard port
-
1
def standard_port?
-
port == standard_port
-
end
-
-
# Returns a number \port suffix like 8080 if the \port number of this request
-
# is not the default HTTP \port 80 or HTTPS \port 443.
-
1
def optional_port
-
standard_port? ? nil : port
-
end
-
-
# Returns a string \port suffix, including colon, like ":8080" if the \port
-
# number of this request is not the default HTTP \port 80 or HTTPS \port 443.
-
1
def port_string
-
standard_port? ? '' : ":#{port}"
-
end
-
-
1
def server_port
-
@env['SERVER_PORT'].to_i
-
end
-
-
# Returns the \domain part of a \host, such as "rubyonrails.org" in "www.rubyonrails.org". You can specify
-
# a different <tt>tld_length</tt>, such as 2 to catch rubyonrails.co.uk in "www.rubyonrails.co.uk".
-
1
def domain(tld_length = @@tld_length)
-
ActionDispatch::Http::URL.extract_domain(host, tld_length)
-
end
-
-
# Returns all the \subdomains as an array, so <tt>["dev", "www"]</tt> would be
-
# returned for "dev.www.rubyonrails.org". You can specify a different <tt>tld_length</tt>,
-
# such as 2 to catch <tt>["www"]</tt> instead of <tt>["www", "rubyonrails"]</tt>
-
# in "www.rubyonrails.co.uk".
-
1
def subdomains(tld_length = @@tld_length)
-
ActionDispatch::Http::URL.extract_subdomains(host, tld_length)
-
end
-
-
# Returns all the \subdomains as a string, so <tt>"dev.www"</tt> would be
-
# returned for "dev.www.rubyonrails.org". You can specify a different <tt>tld_length</tt>,
-
# such as 2 to catch <tt>"www"</tt> instead of <tt>"www.rubyonrails"</tt>
-
# in "www.rubyonrails.co.uk".
-
1
def subdomain(tld_length = @@tld_length)
-
ActionDispatch::Http::URL.extract_subdomain(host, tld_length)
-
end
-
end
-
end
-
end
-
1
require 'action_dispatch/journey/router'
-
1
require 'action_dispatch/journey/gtg/builder'
-
1
require 'action_dispatch/journey/gtg/simulator'
-
1
require 'action_dispatch/journey/nfa/builder'
-
1
require 'action_dispatch/journey/nfa/simulator'
-
1
require 'action_controller/metal/exceptions'
-
-
1
module ActionDispatch
-
1
module Journey
-
# The Formatter class is used for formatting URLs. For example, parameters
-
# passed to +url_for+ in Rails will eventually call Formatter#generate.
-
1
class Formatter # :nodoc:
-
1
attr_reader :routes
-
-
1
def initialize(routes)
-
2
@routes = routes
-
2
@cache = nil
-
end
-
-
1
def generate(type, name, options, recall = {}, parameterize = nil)
-
constraints = recall.merge(options)
-
missing_keys = []
-
-
match_route(name, constraints) do |route|
-
parameterized_parts = extract_parameterized_parts(route, options, recall, parameterize)
-
-
# Skip this route unless a name has been provided or it is a
-
# standard Rails route since we can't determine whether an options
-
# hash passed to url_for matches a Rack application or a redirect.
-
next unless name || route.dispatcher?
-
-
missing_keys = missing_keys(route, parameterized_parts)
-
next unless missing_keys.empty?
-
params = options.dup.delete_if do |key, _|
-
parameterized_parts.key?(key) || route.defaults.key?(key)
-
end
-
-
return [route.format(parameterized_parts), params]
-
end
-
-
message = "No route matches #{Hash[constraints.sort].inspect}"
-
message << " missing required keys: #{missing_keys.sort.inspect}" if name
-
-
raise ActionController::UrlGenerationError, message
-
end
-
-
1
def clear
-
2
@cache = nil
-
end
-
-
1
private
-
-
1
def extract_parameterized_parts(route, options, recall, parameterize = nil)
-
parameterized_parts = recall.merge(options)
-
-
keys_to_keep = route.parts.reverse.drop_while { |part|
-
!options.key?(part) || (options[part] || recall[part]).nil?
-
} | route.required_parts
-
-
(parameterized_parts.keys - keys_to_keep).each do |bad_key|
-
parameterized_parts.delete(bad_key)
-
end
-
-
if parameterize
-
parameterized_parts.each do |k, v|
-
parameterized_parts[k] = parameterize.call(k, v)
-
end
-
end
-
-
parameterized_parts.keep_if { |_, v| v }
-
parameterized_parts
-
end
-
-
1
def named_routes
-
routes.named_routes
-
end
-
-
1
def match_route(name, options)
-
if named_routes.key?(name)
-
yield named_routes[name]
-
else
-
routes = non_recursive(cache, options.to_a)
-
-
hash = routes.group_by { |_, r| r.score(options) }
-
-
hash.keys.sort.reverse_each do |score|
-
next if score < 0
-
-
hash[score].sort_by { |i, _| i }.each do |_, route|
-
yield route
-
end
-
end
-
end
-
end
-
-
1
def non_recursive(cache, options)
-
routes = []
-
stack = [cache]
-
-
while stack.any?
-
c = stack.shift
-
routes.concat(c[:___routes]) if c.key?(:___routes)
-
-
options.each do |pair|
-
stack << c[pair] if c.key?(pair)
-
end
-
end
-
-
routes
-
end
-
-
# Returns an array populated with missing keys if any are present.
-
1
def missing_keys(route, parts)
-
missing_keys = []
-
tests = route.path.requirements
-
route.required_parts.each { |key|
-
if tests.key?(key)
-
missing_keys << key unless /\A#{tests[key]}\Z/ === parts[key]
-
else
-
missing_keys << key unless parts[key]
-
end
-
}
-
missing_keys
-
end
-
-
1
def possibles(cache, options, depth = 0)
-
cache.fetch(:___routes) { [] } + options.find_all { |pair|
-
cache.key?(pair)
-
}.map { |pair|
-
possibles(cache[pair], options, depth + 1)
-
}.flatten(1)
-
end
-
-
# Returns +true+ if no missing keys are present, otherwise +false+.
-
1
def verify_required_parts!(route, parts)
-
missing_keys(route, parts).empty?
-
end
-
-
1
def build_cache
-
root = { ___routes: [] }
-
routes.each_with_index do |route, i|
-
leaf = route.required_defaults.inject(root) do |h, tuple|
-
h[tuple] ||= {}
-
end
-
(leaf[:___routes] ||= []) << [i, route]
-
end
-
root
-
end
-
-
1
def cache
-
@cache ||= build_cache
-
end
-
end
-
end
-
end
-
1
require 'action_dispatch/journey/gtg/transition_table'
-
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
1
module GTG # :nodoc:
-
1
class Builder # :nodoc:
-
1
DUMMY = Nodes::Dummy.new
-
-
1
attr_reader :root, :ast, :endpoints
-
-
1
def initialize(root)
-
73
@root = root
-
73
@ast = Nodes::Cat.new root, DUMMY
-
73
@followpos = nil
-
end
-
-
1
def transition_table
-
dtrans = TransitionTable.new
-
marked = {}
-
state_id = Hash.new { |h,k| h[k] = h.length }
-
-
start = firstpos(root)
-
dstates = [start]
-
until dstates.empty?
-
s = dstates.shift
-
next if marked[s]
-
marked[s] = true # mark s
-
-
s.group_by { |state| symbol(state) }.each do |sym, ps|
-
u = ps.map { |l| followpos(l) }.flatten
-
next if u.empty?
-
-
if u.uniq == [DUMMY]
-
from = state_id[s]
-
to = state_id[Object.new]
-
dtrans[from, to] = sym
-
-
dtrans.add_accepting(to)
-
ps.each { |state| dtrans.add_memo(to, state.memo) }
-
else
-
dtrans[state_id[s], state_id[u]] = sym
-
-
if u.include?(DUMMY)
-
to = state_id[u]
-
-
accepting = ps.find_all { |l| followpos(l).include?(DUMMY) }
-
-
accepting.each { |accepting_state|
-
dtrans.add_memo(to, accepting_state.memo)
-
}
-
-
dtrans.add_accepting(state_id[u])
-
end
-
end
-
-
dstates << u
-
end
-
end
-
-
dtrans
-
end
-
-
1
def nullable?(node)
-
1412
case node
-
when Nodes::Group
-
71
true
-
when Nodes::Star
-
true
-
when Nodes::Or
-
node.children.any? { |c| nullable?(c) }
-
when Nodes::Cat
-
nullable?(node.left) && nullable?(node.right)
-
when Nodes::Terminal
-
1341
!node.left
-
when Nodes::Unary
-
nullable?(node.left)
-
else
-
raise ArgumentError, 'unknown nullable: %s' % node.class.name
-
end
-
end
-
-
1
def firstpos(node)
-
613
case node
-
when Nodes::Star
-
firstpos(node.left)
-
when Nodes::Cat
-
71
if nullable?(node.left)
-
firstpos(node.left) | firstpos(node.right)
-
else
-
71
firstpos(node.left)
-
end
-
when Nodes::Or
-
node.children.map { |c| firstpos(c) }.flatten.uniq
-
when Nodes::Unary
-
71
firstpos(node.left)
-
when Nodes::Terminal
-
471
nullable?(node) ? [] : [node]
-
else
-
raise ArgumentError, 'unknown firstpos: %s' % node.class.name
-
end
-
end
-
-
1
def lastpos(node)
-
941
case node
-
when Nodes::Star
-
firstpos(node.left)
-
when Nodes::Or
-
node.children.map { |c| lastpos(c) }.flatten.uniq
-
when Nodes::Cat
-
399
if nullable?(node.right)
-
71
lastpos(node.left) | lastpos(node.right)
-
else
-
328
lastpos(node.right)
-
end
-
when Nodes::Terminal
-
471
nullable?(node) ? [] : [node]
-
when Nodes::Unary
-
71
lastpos(node.left)
-
else
-
raise ArgumentError, 'unknown lastpos: %s' % node.class.name
-
end
-
end
-
-
1
def followpos(node)
-
200
followpos_table[node]
-
end
-
-
1
private
-
-
1
def followpos_table
-
200
@followpos ||= build_followpos
-
end
-
-
1
def build_followpos
-
472
table = Hash.new { |h, k| h[k] = [] }
-
72
@ast.each do |n|
-
943
case n
-
when Nodes::Cat
-
400
lastpos(n.left).each do |i|
-
471
table[i] += firstpos(n.right)
-
end
-
when Nodes::Star
-
lastpos(n).each do |i|
-
table[i] += firstpos(n)
-
end
-
end
-
end
-
72
table
-
end
-
-
1
def symbol(edge)
-
case edge
-
when Journey::Nodes::Symbol
-
edge.regexp
-
else
-
edge.left
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'strscan'
-
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
1
module GTG # :nodoc:
-
1
class MatchData # :nodoc:
-
1
attr_reader :memos
-
-
1
def initialize(memos)
-
@memos = memos
-
end
-
end
-
-
1
class Simulator # :nodoc:
-
1
attr_reader :tt
-
-
1
def initialize(transition_table)
-
@tt = transition_table
-
end
-
-
1
def simulate(string)
-
input = StringScanner.new(string)
-
state = [0]
-
while sym = input.scan(%r([/.?]|[^/.?]+))
-
state = tt.move(state, sym)
-
end
-
-
acceptance_states = state.find_all { |s|
-
tt.accepting? s
-
}
-
-
return if acceptance_states.empty?
-
-
memos = acceptance_states.map { |x| tt.memo(x) }.flatten.compact
-
-
MatchData.new(memos)
-
end
-
-
1
alias :=~ :simulate
-
1
alias :match :simulate
-
end
-
end
-
end
-
end
-
1
require 'action_dispatch/journey/nfa/dot'
-
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
1
module GTG # :nodoc:
-
1
class TransitionTable # :nodoc:
-
1
include Journey::NFA::Dot
-
-
1
attr_reader :memos
-
-
1
def initialize
-
@regexp_states = {}
-
@string_states = {}
-
@accepting = {}
-
@memos = Hash.new { |h,k| h[k] = [] }
-
end
-
-
1
def add_accepting(state)
-
@accepting[state] = true
-
end
-
-
1
def accepting_states
-
@accepting.keys
-
end
-
-
1
def accepting?(state)
-
@accepting[state]
-
end
-
-
1
def add_memo(idx, memo)
-
@memos[idx] << memo
-
end
-
-
1
def memo(idx)
-
@memos[idx]
-
end
-
-
1
def eclosure(t)
-
Array(t)
-
end
-
-
1
def move(t, a)
-
move_string(t, a).concat(move_regexp(t, a))
-
end
-
-
1
def as_json(options = nil)
-
simple_regexp = Hash.new { |h,k| h[k] = {} }
-
-
@regexp_states.each do |from, hash|
-
hash.each do |re, to|
-
simple_regexp[from][re.source] = to
-
end
-
end
-
-
{
-
regexp_states: simple_regexp,
-
string_states: @string_states,
-
accepting: @accepting
-
}
-
end
-
-
1
def to_svg
-
svg = IO.popen('dot -Tsvg', 'w+') { |f|
-
f.write(to_dot)
-
f.close_write
-
f.readlines
-
}
-
3.times { svg.shift }
-
svg.join.sub(/width="[^"]*"/, '').sub(/height="[^"]*"/, '')
-
end
-
-
1
def visualizer(paths, title = 'FSM')
-
viz_dir = File.join File.dirname(__FILE__), '..', 'visualizer'
-
fsm_js = File.read File.join(viz_dir, 'fsm.js')
-
fsm_css = File.read File.join(viz_dir, 'fsm.css')
-
erb = File.read File.join(viz_dir, 'index.html.erb')
-
states = "function tt() { return #{to_json}; }"
-
-
fun_routes = paths.shuffle.first(3).map do |ast|
-
ast.map { |n|
-
case n
-
when Nodes::Symbol
-
case n.left
-
when ':id' then rand(100).to_s
-
when ':format' then %w{ xml json }.shuffle.first
-
else
-
'omg'
-
end
-
when Nodes::Terminal then n.symbol
-
else
-
nil
-
end
-
}.compact.join
-
end
-
-
stylesheets = [fsm_css]
-
svg = to_svg
-
javascripts = [states, fsm_js]
-
-
# Annoying hack for 1.9 warnings
-
fun_routes = fun_routes
-
stylesheets = stylesheets
-
svg = svg
-
javascripts = javascripts
-
-
require 'erb'
-
template = ERB.new erb
-
template.result(binding)
-
end
-
-
1
def []=(from, to, sym)
-
to_mappings = states_hash_for(sym)[from] ||= {}
-
to_mappings[sym] = to
-
end
-
-
1
def states
-
ss = @string_states.keys + @string_states.values.map(&:values).flatten
-
rs = @regexp_states.keys + @regexp_states.values.map(&:values).flatten
-
(ss + rs).uniq
-
end
-
-
1
def transitions
-
@string_states.map { |from, hash|
-
hash.map { |s, to| [from, s, to] }
-
}.flatten(1) + @regexp_states.map { |from, hash|
-
hash.map { |s, to| [from, s, to] }
-
}.flatten(1)
-
end
-
-
1
private
-
-
1
def states_hash_for(sym)
-
case sym
-
when String
-
@string_states
-
when Regexp
-
@regexp_states
-
else
-
raise ArgumentError, 'unknown symbol: %s' % sym.class
-
end
-
end
-
-
1
def move_regexp(t, a)
-
return [] if t.empty?
-
-
t.map { |s|
-
if states = @regexp_states[s]
-
states.map { |re, v| re === a ? v : nil }
-
end
-
}.flatten.compact.uniq
-
end
-
-
1
def move_string(t, a)
-
return [] if t.empty?
-
-
t.map do |s|
-
if states = @string_states[s]
-
states[a]
-
end
-
end.compact
-
end
-
end
-
end
-
end
-
end
-
1
require 'action_dispatch/journey/nfa/transition_table'
-
1
require 'action_dispatch/journey/gtg/transition_table'
-
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
1
module NFA # :nodoc:
-
1
class Visitor < Visitors::Visitor # :nodoc:
-
1
def initialize(tt)
-
@tt = tt
-
@i = -1
-
end
-
-
1
def visit_CAT(node)
-
left = visit(node.left)
-
right = visit(node.right)
-
-
@tt.merge(left.last, right.first)
-
-
[left.first, right.last]
-
end
-
-
1
def visit_GROUP(node)
-
from = @i += 1
-
left = visit(node.left)
-
to = @i += 1
-
-
@tt.accepting = to
-
-
@tt[from, left.first] = nil
-
@tt[left.last, to] = nil
-
@tt[from, to] = nil
-
-
[from, to]
-
end
-
-
1
def visit_OR(node)
-
from = @i += 1
-
children = node.children.map { |c| visit(c) }
-
to = @i += 1
-
-
children.each do |child|
-
@tt[from, child.first] = nil
-
@tt[child.last, to] = nil
-
end
-
-
@tt.accepting = to
-
-
[from, to]
-
end
-
-
1
def terminal(node)
-
from_i = @i += 1 # new state
-
to_i = @i += 1 # new state
-
-
@tt[from_i, to_i] = node
-
@tt.accepting = to_i
-
@tt.add_memo(to_i, node.memo)
-
-
[from_i, to_i]
-
end
-
end
-
-
1
class Builder # :nodoc:
-
1
def initialize(ast)
-
@ast = ast
-
end
-
-
1
def transition_table
-
tt = TransitionTable.new
-
Visitor.new(tt).accept(@ast)
-
tt
-
end
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
1
module NFA # :nodoc:
-
1
module Dot # :nodoc:
-
1
def to_dot
-
edges = transitions.map { |from, sym, to|
-
" #{from} -> #{to} [label=\"#{sym || 'ε'}\"];"
-
}
-
-
#memo_nodes = memos.values.flatten.map { |n|
-
# label = n
-
# if Journey::Route === n
-
# label = "#{n.verb.source} #{n.path.spec}"
-
# end
-
# " #{n.object_id} [label=\"#{label}\", shape=box];"
-
#}
-
#memo_edges = memos.map { |k, memos|
-
# (memos || []).map { |v| " #{k} -> #{v.object_id};" }
-
#}.flatten.uniq
-
-
<<-eodot
-
digraph nfa {
-
rankdir=LR;
-
node [shape = doublecircle];
-
#{accepting_states.join ' '};
-
node [shape = circle];
-
#{edges.join "\n"}
-
}
-
eodot
-
end
-
end
-
end
-
end
-
end
-
1
require 'strscan'
-
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
1
module NFA # :nodoc:
-
1
class MatchData # :nodoc:
-
1
attr_reader :memos
-
-
1
def initialize(memos)
-
@memos = memos
-
end
-
end
-
-
1
class Simulator # :nodoc:
-
1
attr_reader :tt
-
-
1
def initialize(transition_table)
-
@tt = transition_table
-
end
-
-
1
def simulate(string)
-
input = StringScanner.new(string)
-
state = tt.eclosure(0)
-
until input.eos?
-
sym = input.scan(%r([/.?]|[^/.?]+))
-
-
# FIXME: tt.eclosure is not needed for the GTG
-
state = tt.eclosure(tt.move(state, sym))
-
end
-
-
acceptance_states = state.find_all { |s|
-
tt.accepting?(tt.eclosure(s).sort.last)
-
}
-
-
return if acceptance_states.empty?
-
-
memos = acceptance_states.map { |x| tt.memo(x) }.flatten.compact
-
-
MatchData.new(memos)
-
end
-
-
1
alias :=~ :simulate
-
1
alias :match :simulate
-
end
-
end
-
end
-
end
-
1
require 'action_dispatch/journey/nfa/dot'
-
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
1
module NFA # :nodoc:
-
1
class TransitionTable # :nodoc:
-
1
include Journey::NFA::Dot
-
-
1
attr_accessor :accepting
-
1
attr_reader :memos
-
-
1
def initialize
-
@table = Hash.new { |h,f| h[f] = {} }
-
@memos = {}
-
@accepting = nil
-
@inverted = nil
-
end
-
-
1
def accepting?(state)
-
accepting == state
-
end
-
-
1
def accepting_states
-
[accepting]
-
end
-
-
1
def add_memo(idx, memo)
-
@memos[idx] = memo
-
end
-
-
1
def memo(idx)
-
@memos[idx]
-
end
-
-
1
def []=(i, f, s)
-
@table[f][i] = s
-
end
-
-
1
def merge(left, right)
-
@memos[right] = @memos.delete(left)
-
@table[right] = @table.delete(left)
-
end
-
-
1
def states
-
(@table.keys + @table.values.map(&:keys).flatten).uniq
-
end
-
-
# Returns a generalized transition graph with reduced states. The states
-
# are reduced like a DFA, but the table must be simulated like an NFA.
-
#
-
# Edges of the GTG are regular expressions.
-
1
def generalized_table
-
gt = GTG::TransitionTable.new
-
marked = {}
-
state_id = Hash.new { |h,k| h[k] = h.length }
-
alphabet = self.alphabet
-
-
stack = [eclosure(0)]
-
-
until stack.empty?
-
state = stack.pop
-
next if marked[state] || state.empty?
-
-
marked[state] = true
-
-
alphabet.each do |alpha|
-
next_state = eclosure(following_states(state, alpha))
-
next if next_state.empty?
-
-
gt[state_id[state], state_id[next_state]] = alpha
-
stack << next_state
-
end
-
end
-
-
final_groups = state_id.keys.find_all { |s|
-
s.sort.last == accepting
-
}
-
-
final_groups.each do |states|
-
id = state_id[states]
-
-
gt.add_accepting(id)
-
save = states.find { |s|
-
@memos.key?(s) && eclosure(s).sort.last == accepting
-
}
-
-
gt.add_memo(id, memo(save))
-
end
-
-
gt
-
end
-
-
# Returns set of NFA states to which there is a transition on ast symbol
-
# +a+ from some state +s+ in +t+.
-
1
def following_states(t, a)
-
Array(t).map { |s| inverted[s][a] }.flatten.uniq
-
end
-
-
# Returns set of NFA states to which there is a transition on ast symbol
-
# +a+ from some state +s+ in +t+.
-
1
def move(t, a)
-
Array(t).map { |s|
-
inverted[s].keys.compact.find_all { |sym|
-
sym === a
-
}.map { |sym| inverted[s][sym] }
-
}.flatten.uniq
-
end
-
-
1
def alphabet
-
inverted.values.map(&:keys).flatten.compact.uniq.sort_by { |x| x.to_s }
-
end
-
-
# Returns a set of NFA states reachable from some NFA state +s+ in set
-
# +t+ on nil-transitions alone.
-
1
def eclosure(t)
-
stack = Array(t)
-
seen = {}
-
children = []
-
-
until stack.empty?
-
s = stack.pop
-
next if seen[s]
-
-
seen[s] = true
-
children << s
-
-
stack.concat(inverted[s][nil])
-
end
-
-
children.uniq
-
end
-
-
1
def transitions
-
@table.map { |to, hash|
-
hash.map { |from, sym| [from, sym, to] }
-
}.flatten(1)
-
end
-
-
1
private
-
-
1
def inverted
-
return @inverted if @inverted
-
-
@inverted = Hash.new { |h, from|
-
h[from] = Hash.new { |j, s| j[s] = [] }
-
}
-
-
@table.each { |to, hash|
-
hash.each { |from, sym|
-
if sym
-
sym = Nodes::Symbol === sym ? sym.regexp : sym.left
-
end
-
-
@inverted[from][sym] << to
-
}
-
}
-
-
@inverted
-
end
-
end
-
end
-
end
-
end
-
#
-
# DO NOT MODIFY!!!!
-
# This file is automatically generated by Racc 1.4.9
-
# from Racc grammar file "".
-
#
-
-
1
require 'racc/parser.rb'
-
-
-
1
require 'action_dispatch/journey/parser_extras'
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
1
class Parser < Racc::Parser # :nodoc:
-
##### State transition tables begin ###
-
-
1
racc_action_table = [
-
17, 21, 13, 15, 14, 7, nil, 16, 8, 19,
-
13, 15, 14, 7, 23, 16, 8, 19, 13, 15,
-
14, 7, nil, 16, 8, 13, 15, 14, 7, nil,
-
16, 8, 13, 15, 14, 7, nil, 16, 8 ]
-
-
1
racc_action_check = [
-
1, 17, 1, 1, 1, 1, nil, 1, 1, 1,
-
20, 20, 20, 20, 20, 20, 20, 20, 7, 7,
-
7, 7, nil, 7, 7, 19, 19, 19, 19, nil,
-
19, 19, 0, 0, 0, 0, nil, 0, 0 ]
-
-
1
racc_action_pointer = [
-
30, 0, nil, nil, nil, nil, nil, 16, nil, nil,
-
nil, nil, nil, nil, nil, nil, nil, 1, nil, 23,
-
8, nil, nil, nil ]
-
-
1
racc_action_default = [
-
-18, -18, -2, -3, -4, -5, -6, -18, -9, -10,
-
-11, -12, -13, -14, -15, -16, -17, -18, -1, -18,
-
-18, 24, -8, -7 ]
-
-
1
racc_goto_table = [
-
18, 1, nil, nil, nil, nil, nil, nil, 20, nil,
-
nil, nil, nil, nil, nil, nil, nil, nil, 22, 18 ]
-
-
1
racc_goto_check = [
-
2, 1, nil, nil, nil, nil, nil, nil, 1, nil,
-
nil, nil, nil, nil, nil, nil, nil, nil, 2, 2 ]
-
-
1
racc_goto_pointer = [
-
nil, 1, -1, nil, nil, nil, nil, nil, nil, nil,
-
nil ]
-
-
1
racc_goto_default = [
-
nil, nil, 2, 3, 4, 5, 6, 9, 10, 11,
-
12 ]
-
-
1
racc_reduce_table = [
-
0, 0, :racc_error,
-
2, 11, :_reduce_1,
-
1, 11, :_reduce_2,
-
1, 11, :_reduce_none,
-
1, 12, :_reduce_none,
-
1, 12, :_reduce_none,
-
1, 12, :_reduce_none,
-
3, 15, :_reduce_7,
-
3, 13, :_reduce_8,
-
1, 16, :_reduce_9,
-
1, 14, :_reduce_none,
-
1, 14, :_reduce_none,
-
1, 14, :_reduce_none,
-
1, 14, :_reduce_none,
-
1, 19, :_reduce_14,
-
1, 17, :_reduce_15,
-
1, 18, :_reduce_16,
-
1, 20, :_reduce_17 ]
-
-
1
racc_reduce_n = 18
-
-
1
racc_shift_n = 24
-
-
1
racc_token_table = {
-
false => 0,
-
:error => 1,
-
:SLASH => 2,
-
:LITERAL => 3,
-
:SYMBOL => 4,
-
:LPAREN => 5,
-
:RPAREN => 6,
-
:DOT => 7,
-
:STAR => 8,
-
:OR => 9 }
-
-
1
racc_nt_base = 10
-
-
1
racc_use_result_var = true
-
-
1
Racc_arg = [
-
racc_action_table,
-
racc_action_check,
-
racc_action_default,
-
racc_action_pointer,
-
racc_goto_table,
-
racc_goto_check,
-
racc_goto_default,
-
racc_goto_pointer,
-
racc_nt_base,
-
racc_reduce_table,
-
racc_token_table,
-
racc_shift_n,
-
racc_reduce_n,
-
racc_use_result_var ]
-
-
1
Racc_token_to_s_table = [
-
"$end",
-
"error",
-
"SLASH",
-
"LITERAL",
-
"SYMBOL",
-
"LPAREN",
-
"RPAREN",
-
"DOT",
-
"STAR",
-
"OR",
-
"$start",
-
"expressions",
-
"expression",
-
"or",
-
"terminal",
-
"group",
-
"star",
-
"symbol",
-
"literal",
-
"slash",
-
"dot" ]
-
-
1
Racc_debug_parser = false
-
-
##### State transition tables end #####
-
-
# reduce 0 omitted
-
-
1
def _reduce_1(val, _values, result)
-
656
result = Cat.new(val.first, val.last)
-
656
result
-
end
-
-
1
def _reduce_2(val, _values, result)
-
288
result = val.first
-
288
result
-
end
-
-
# reduce 3 omitted
-
-
# reduce 4 omitted
-
-
# reduce 5 omitted
-
-
# reduce 6 omitted
-
-
1
def _reduce_7(val, _values, result)
-
142
result = Group.new(val[1])
-
142
result
-
end
-
-
1
def _reduce_8(val, _values, result)
-
result = Or.new([val.first, val.last])
-
result
-
end
-
-
1
def _reduce_9(val, _values, result)
-
result = Star.new(Symbol.new(val.last))
-
result
-
end
-
-
# reduce 10 omitted
-
-
# reduce 11 omitted
-
-
# reduce 12 omitted
-
-
# reduce 13 omitted
-
-
1
def _reduce_14(val, _values, result)
-
260
result = Slash.new('/')
-
260
result
-
end
-
-
1
def _reduce_15(val, _values, result)
-
202
result = Symbol.new(val.first)
-
202
result
-
end
-
-
1
def _reduce_16(val, _values, result)
-
198
result = Literal.new(val.first)
-
198
result
-
end
-
-
1
def _reduce_17(val, _values, result)
-
142
result = Dot.new(val.first)
-
142
result
-
end
-
-
1
def _reduce_none(val, _values, result)
-
val[0]
-
end
-
-
end # class Parser
-
end # module Journey
-
end # module ActionDispatch
-
1
require 'action_dispatch/journey/scanner'
-
1
require 'action_dispatch/journey/nodes/node'
-
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
1
class Parser < Racc::Parser # :nodoc:
-
1
include Journey::Nodes
-
-
1
def initialize
-
146
@scanner = Scanner.new
-
end
-
-
1
def parse(string)
-
146
@scanner.scan_setup(string)
-
146
do_parse
-
end
-
-
1
def next_token
-
1232
@scanner.next_token
-
end
-
end
-
end
-
end
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
1
module Path # :nodoc:
-
1
class Pattern # :nodoc:
-
1
attr_reader :spec, :requirements, :anchored
-
-
1
def initialize(strexp)
-
146
parser = Journey::Parser.new
-
-
146
@anchored = true
-
-
146
case strexp
-
when String
-
@spec = parser.parse(strexp)
-
@requirements = {}
-
@separators = "/.?"
-
when Router::Strexp
-
146
@spec = parser.parse(strexp.path)
-
146
@requirements = strexp.requirements
-
146
@separators = strexp.separators.join
-
146
@anchored = strexp.anchor
-
else
-
raise ArgumentError, "Bad expression: #{strexp}"
-
end
-
-
146
@names = nil
-
146
@optional_names = nil
-
146
@required_names = nil
-
146
@re = nil
-
146
@offsets = nil
-
end
-
-
1
def ast
-
@spec.grep(Nodes::Symbol).each do |node|
-
re = @requirements[node.to_sym]
-
node.regexp = re if re
-
end
-
-
@spec.grep(Nodes::Star).each do |node|
-
node = node.left
-
node.regexp = @requirements[node.to_sym] || /(.+)/
-
end
-
-
@spec
-
end
-
-
1
def names
-
424
@names ||= spec.grep(Nodes::Symbol).map { |n| n.name }
-
end
-
-
1
def required_names
-
38
@required_names ||= names - optional_names
-
end
-
-
1
def optional_names
-
@optional_names ||= spec.grep(Nodes::Group).map { |group|
-
37
group.grep(Nodes::Symbol)
-
75
}.flatten.map { |n| n.name }.uniq
-
end
-
-
1
class RegexpOffsets < Journey::Visitors::Visitor # :nodoc:
-
1
attr_reader :offsets
-
-
1
def initialize(matchers)
-
@matchers = matchers
-
@capture_count = [0]
-
end
-
-
1
def visit(node)
-
super
-
@capture_count
-
end
-
-
1
def visit_SYMBOL(node)
-
node = node.to_sym
-
-
if @matchers.key?(node)
-
re = /#{@matchers[node]}|/
-
@capture_count.push((re.match('').length - 1) + (@capture_count.last || 0))
-
else
-
@capture_count << (@capture_count.last || 0)
-
end
-
end
-
end
-
-
1
class AnchoredRegexp < Journey::Visitors::Visitor # :nodoc:
-
1
def initialize(separator, matchers)
-
@separator = separator
-
@matchers = matchers
-
@separator_re = "([^#{separator}]+)"
-
super()
-
end
-
-
1
def accept(node)
-
%r{\A#{visit node}\Z}
-
end
-
-
1
def visit_CAT(node)
-
[visit(node.left), visit(node.right)].join
-
end
-
-
1
def visit_SYMBOL(node)
-
node = node.to_sym
-
-
return @separator_re unless @matchers.key?(node)
-
-
re = @matchers[node]
-
"(#{re})"
-
end
-
-
1
def visit_GROUP(node)
-
"(?:#{visit node.left})?"
-
end
-
-
1
def visit_LITERAL(node)
-
Regexp.escape(node.left)
-
end
-
1
alias :visit_DOT :visit_LITERAL
-
-
1
def visit_SLASH(node)
-
node.left
-
end
-
-
1
def visit_STAR(node)
-
re = @matchers[node.left.to_sym] || '.+'
-
"(#{re})"
-
end
-
end
-
-
1
class UnanchoredRegexp < AnchoredRegexp # :nodoc:
-
1
def accept(node)
-
%r{\A#{visit node}}
-
end
-
end
-
-
1
class MatchData # :nodoc:
-
1
attr_reader :names
-
-
1
def initialize(names, offsets, match)
-
@names = names
-
@offsets = offsets
-
@match = match
-
end
-
-
1
def captures
-
(length - 1).times.map { |i| self[i + 1] }
-
end
-
-
1
def [](x)
-
idx = @offsets[x - 1] + x
-
@match[idx]
-
end
-
-
1
def length
-
@offsets.length
-
end
-
-
1
def post_match
-
@match.post_match
-
end
-
-
1
def to_s
-
@match.to_s
-
end
-
end
-
-
1
def match(other)
-
return unless match = to_regexp.match(other)
-
MatchData.new(names, offsets, match)
-
end
-
1
alias :=~ :match
-
-
1
def source
-
to_regexp.source
-
end
-
-
1
def to_regexp
-
@re ||= regexp_visitor.new(@separators, @requirements).accept spec
-
end
-
-
1
private
-
-
1
def regexp_visitor
-
@anchored ? AnchoredRegexp : UnanchoredRegexp
-
end
-
-
1
def offsets
-
return @offsets if @offsets
-
-
viz = RegexpOffsets.new(@requirements)
-
@offsets = viz.accept(spec)
-
end
-
end
-
end
-
end
-
end
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
1
class Route # :nodoc:
-
1
attr_reader :app, :path, :defaults, :name
-
-
1
attr_reader :constraints
-
1
alias :conditions :constraints
-
-
1
attr_accessor :precedence
-
-
##
-
# +path+ is a path constraint.
-
# +constraints+ is a hash of constraints to be applied to this route.
-
1
def initialize(name, app, path, constraints, defaults = {})
-
73
@name = name
-
73
@app = app
-
73
@path = path
-
-
# Unwrap any constraints so we can see what's inside for route generation.
-
# This allows the formatter to skip over any mounted applications or redirects
-
# that shouldn't be matched when using a url_for without a route name.
-
73
while app.is_a?(Routing::Mapper::Constraints) do
-
15
app = app.app
-
end
-
73
@dispatcher = app.is_a?(Routing::RouteSet::Dispatcher)
-
-
73
@constraints = constraints
-
73
@defaults = defaults
-
73
@required_defaults = nil
-
73
@required_parts = nil
-
73
@parts = nil
-
73
@decorated_ast = nil
-
73
@precedence = 0
-
end
-
-
1
def ast
-
@decorated_ast ||= begin
-
decorated_ast = path.ast
-
decorated_ast.grep(Nodes::Terminal).each { |n| n.memo = self }
-
decorated_ast
-
end
-
end
-
-
1
def requirements # :nodoc:
-
# needed for rails `rake routes`
-
76
path.requirements.merge(@defaults).delete_if { |_,v|
-
152
/.+?/ == v
-
}
-
end
-
-
1
def segments
-
38
path.names
-
end
-
-
1
def required_keys
-
required_parts + required_defaults.keys
-
end
-
-
1
def score(constraints)
-
required_keys = path.required_names
-
supplied_keys = constraints.map { |k,v| v && k.to_s }.compact
-
-
return -1 unless (required_keys - supplied_keys).empty?
-
-
score = (supplied_keys & path.names).length
-
score + (required_defaults.length * 2)
-
end
-
-
1
def parts
-
123
@parts ||= segments.map { |n| n.to_sym }
-
end
-
1
alias :segment_keys :parts
-
-
1
def format(path_options)
-
path_options.delete_if do |key, value|
-
value.to_s == defaults[key].to_s && !required_parts.include?(key)
-
end
-
-
Visitors::Formatter.new(path_options).accept(path.spec)
-
end
-
-
1
def optimized_path
-
76
Visitors::OptimizedPath.new.accept(path.spec)
-
end
-
-
1
def optional_parts
-
path.optional_names.map { |n| n.to_sym }
-
end
-
-
1
def required_parts
-
86
@required_parts ||= path.required_names.map { |n| n.to_sym }
-
end
-
-
1
def required_default?(key)
-
(constraints[:required_defaults] || []).include?(key)
-
end
-
-
1
def required_defaults
-
@required_defaults ||= @defaults.dup.delete_if do |k,_|
-
parts.include?(k) || !required_default?(k)
-
end
-
end
-
-
1
def dispatcher?
-
@dispatcher
-
end
-
-
1
def matches?(request)
-
constraints.all? do |method, value|
-
next true unless request.respond_to?(method)
-
-
case value
-
when Regexp, String
-
value === request.send(method).to_s
-
when Array
-
value.include?(request.send(method))
-
when TrueClass
-
request.send(method).present?
-
when FalseClass
-
request.send(method).blank?
-
else
-
value === request.send(method)
-
end
-
end
-
end
-
-
1
def ip
-
constraints[:ip] || //
-
end
-
-
1
def verb
-
constraints[:request_method] || //
-
end
-
end
-
end
-
end
-
1
require 'action_dispatch/journey/router/utils'
-
1
require 'action_dispatch/journey/router/strexp'
-
1
require 'action_dispatch/journey/routes'
-
1
require 'action_dispatch/journey/formatter'
-
-
1
before = $-w
-
1
$-w = false
-
1
require 'action_dispatch/journey/parser'
-
1
$-w = before
-
-
1
require 'action_dispatch/journey/route'
-
1
require 'action_dispatch/journey/path/pattern'
-
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
1
class Router # :nodoc:
-
1
class RoutingError < ::StandardError # :nodoc:
-
end
-
-
# :nodoc:
-
1
VERSION = '2.0.0'
-
-
1
class NullReq # :nodoc:
-
1
attr_reader :env
-
1
def initialize(env)
-
@env = env
-
end
-
-
1
def request_method
-
env['REQUEST_METHOD']
-
end
-
-
1
def path_info
-
env['PATH_INFO']
-
end
-
-
1
def ip
-
env['REMOTE_ADDR']
-
end
-
-
1
def [](k)
-
env[k]
-
end
-
end
-
-
1
attr_reader :request_class, :formatter
-
1
attr_accessor :routes
-
-
1
def initialize(routes, options)
-
2
@options = options
-
2
@params_key = options[:parameters_key]
-
2
@request_class = options[:request_class] || NullReq
-
2
@routes = routes
-
end
-
-
1
def call(env)
-
env['PATH_INFO'] = Utils.normalize_path(env['PATH_INFO'])
-
-
find_routes(env).each do |match, parameters, route|
-
script_name, path_info, set_params = env.values_at('SCRIPT_NAME',
-
'PATH_INFO',
-
@params_key)
-
-
unless route.path.anchored
-
env['SCRIPT_NAME'] = (script_name.to_s + match.to_s).chomp('/')
-
env['PATH_INFO'] = match.post_match
-
end
-
-
env[@params_key] = (set_params || {}).merge parameters
-
-
status, headers, body = route.app.call(env)
-
-
if 'pass' == headers['X-Cascade']
-
env['SCRIPT_NAME'] = script_name
-
env['PATH_INFO'] = path_info
-
env[@params_key] = set_params
-
next
-
end
-
-
return [status, headers, body]
-
end
-
-
return [404, {'X-Cascade' => 'pass'}, ['Not Found']]
-
end
-
-
1
def recognize(req)
-
find_routes(req.env).each do |match, parameters, route|
-
unless route.path.anchored
-
req.env['SCRIPT_NAME'] = match.to_s
-
req.env['PATH_INFO'] = match.post_match.sub(/^([^\/])/, '/\1')
-
end
-
-
yield(route, nil, parameters)
-
end
-
end
-
-
1
def visualizer
-
tt = GTG::Builder.new(ast).transition_table
-
groups = partitioned_routes.first.map(&:ast).group_by { |a| a.to_s }
-
asts = groups.values.map { |v| v.first }
-
tt.visualizer(asts)
-
end
-
-
1
private
-
-
1
def partitioned_routes
-
routes.partitioned_routes
-
end
-
-
1
def ast
-
routes.ast
-
end
-
-
1
def simulator
-
routes.simulator
-
end
-
-
1
def custom_routes
-
partitioned_routes.last
-
end
-
-
1
def filter_routes(path)
-
return [] unless ast
-
data = simulator.match(path)
-
data ? data.memos : []
-
end
-
-
1
def find_routes env
-
req = request_class.new(env)
-
-
routes = filter_routes(req.path_info).concat custom_routes.find_all { |r|
-
r.path.match(req.path_info)
-
}
-
routes.concat get_routes_as_head(routes)
-
-
routes.sort_by!(&:precedence).select! { |r| r.matches?(req) }
-
-
routes.map! { |r|
-
match_data = r.path.match(req.path_info)
-
match_names = match_data.names.map { |n| n.to_sym }
-
match_values = match_data.captures.map { |v| v && Utils.unescape_uri(v) }
-
info = Hash[match_names.zip(match_values).find_all { |_, y| y }]
-
-
[match_data, r.defaults.merge(info), r]
-
}
-
end
-
-
1
def get_routes_as_head(routes)
-
precedence = (routes.map(&:precedence).max || 0) + 1
-
routes = routes.select { |r|
-
r.verb === "GET" && !(r.verb === "HEAD")
-
}.map! { |r|
-
Route.new(r.name,
-
r.app,
-
r.path,
-
r.conditions.merge(request_method: "HEAD"),
-
r.defaults).tap do |route|
-
route.precedence = r.precedence + precedence
-
end
-
}
-
routes.flatten!
-
routes
-
end
-
end
-
end
-
end
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
1
class Router # :nodoc:
-
1
class Strexp # :nodoc:
-
1
class << self
-
1
alias :compile :new
-
end
-
-
1
attr_reader :path, :requirements, :separators, :anchor
-
-
1
def initialize(path, requirements, separators, anchor = true)
-
146
@path = path
-
146
@requirements = requirements
-
146
@separators = separators
-
146
@anchor = anchor
-
end
-
-
1
def names
-
@path.scan(/:\w+/).map { |s| s.tr(':', '') }
-
end
-
end
-
end
-
end
-
end
-
1
require 'uri'
-
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
1
class Router # :nodoc:
-
1
class Utils # :nodoc:
-
# Normalizes URI path.
-
#
-
# Strips off trailing slash and ensures there is a leading slash.
-
# Also converts downcase url encoded string to uppercase.
-
#
-
# normalize_path("/foo") # => "/foo"
-
# normalize_path("/foo/") # => "/foo"
-
# normalize_path("foo") # => "/foo"
-
# normalize_path("") # => "/"
-
# normalize_path("/%ab") # => "/%AB"
-
1
def self.normalize_path(path)
-
160
path = "/#{path}"
-
160
path.squeeze!('/')
-
160
path.sub!(%r{/+\Z}, '')
-
160
path.gsub!(/(%[a-f0-9]{2})/) { $1.upcase }
-
160
path = '/' if path == ''
-
160
path
-
end
-
-
# URI path and fragment escaping
-
# http://tools.ietf.org/html/rfc3986
-
1
module UriEscape # :nodoc:
-
# Symbol captures can generate multiple path segments, so include /.
-
1
reserved_segment = '/'
-
1
reserved_fragment = '/?'
-
1
reserved_pchar = ':@&=+$,;%'
-
-
1
safe_pchar = "#{URI::REGEXP::PATTERN::UNRESERVED}#{reserved_pchar}"
-
1
safe_segment = "#{safe_pchar}#{reserved_segment}"
-
1
safe_fragment = "#{safe_pchar}#{reserved_fragment}"
-
1
UNSAFE_SEGMENT = Regexp.new("[^#{safe_segment}]", false).freeze
-
1
UNSAFE_FRAGMENT = Regexp.new("[^#{safe_fragment}]", false).freeze
-
end
-
-
1
Parser = URI::Parser.new
-
-
1
def self.escape_path(path)
-
Parser.escape(path.to_s, UriEscape::UNSAFE_SEGMENT)
-
end
-
-
1
def self.escape_fragment(fragment)
-
Parser.escape(fragment.to_s, UriEscape::UNSAFE_FRAGMENT)
-
end
-
-
1
def self.unescape_uri(uri)
-
Parser.unescape(uri)
-
end
-
end
-
end
-
end
-
end
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
# The Routing table. Contains all routes for a system. Routes can be
-
# added to the table by calling Routes#add_route.
-
1
class Routes # :nodoc:
-
1
include Enumerable
-
-
1
attr_reader :routes, :named_routes
-
-
1
def initialize
-
2
@routes = []
-
2
@named_routes = {}
-
2
@ast = nil
-
2
@partitioned_routes = nil
-
2
@simulator = nil
-
end
-
-
1
def length
-
routes.length
-
end
-
1
alias :size :length
-
-
1
def last
-
routes.last
-
end
-
-
1
def each(&block)
-
69
routes.each(&block)
-
end
-
-
1
def clear
-
2
routes.clear
-
2
named_routes.clear
-
end
-
-
1
def partitioned_routes
-
@partitioned_routes ||= routes.partition do |r|
-
r.path.anchored && r.ast.grep(Nodes::Symbol).all?(&:default_regexp?)
-
end
-
end
-
-
1
def ast
-
@ast ||= begin
-
asts = partitioned_routes.first.map(&:ast)
-
Nodes::Or.new(asts) unless asts.empty?
-
end
-
end
-
-
1
def simulator
-
@simulator ||= begin
-
gtg = GTG::Builder.new(ast).transition_table
-
GTG::Simulator.new(gtg)
-
end
-
end
-
-
# Add a route to the routing table.
-
1
def add_route(app, path, conditions, defaults, name = nil)
-
73
route = Route.new(name, app, path, conditions, defaults)
-
-
73
route.precedence = routes.length
-
73
routes << route
-
73
named_routes[name] = route if name && !named_routes[name]
-
73
clear_cache!
-
73
route
-
end
-
-
1
private
-
-
1
def clear_cache!
-
73
@ast = nil
-
73
@partitioned_routes = nil
-
73
@simulator = nil
-
end
-
end
-
end
-
end
-
1
require 'strscan'
-
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
1
class Scanner # :nodoc:
-
1
def initialize
-
146
@ss = nil
-
end
-
-
1
def scan_setup(str)
-
146
@ss = StringScanner.new(str)
-
end
-
-
1
def eos?
-
@ss.eos?
-
end
-
-
1
def pos
-
@ss.pos
-
end
-
-
1
def pre_match
-
@ss.pre_match
-
end
-
-
1
def next_token
-
1232
return if @ss.eos?
-
-
1086
until token = scan || @ss.eos?; end
-
1086
token
-
end
-
-
1
private
-
-
1
def scan
-
case
-
# /
-
when text = @ss.scan(/\//)
-
260
[:SLASH, text]
-
when text = @ss.scan(/\*\w+/)
-
[:STAR, text]
-
when text = @ss.scan(/\(/)
-
142
[:LPAREN, text]
-
when text = @ss.scan(/\)/)
-
142
[:RPAREN, text]
-
when text = @ss.scan(/\|/)
-
[:OR, text]
-
when text = @ss.scan(/\./)
-
142
[:DOT, text]
-
when text = @ss.scan(/:\w+/)
-
202
[:SYMBOL, text]
-
when text = @ss.scan(/[\w%\-~]+/)
-
198
[:LITERAL, text]
-
# any char
-
when text = @ss.scan(/./)
-
[:LITERAL, text]
-
1086
end
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
-
1
require 'thread_safe'
-
-
1
module ActionDispatch
-
1
module Journey # :nodoc:
-
1
module Visitors # :nodoc:
-
1
class Visitor # :nodoc:
-
1
DISPATCH_CACHE = ThreadSafe::Cache.new { |h,k|
-
6
h[k] = :"visit_#{k}"
-
}
-
-
1
def accept(node)
-
439
visit(node)
-
end
-
-
1
private
-
-
1
def visit node
-
5356
send(DISPATCH_CACHE[node.type], node)
-
end
-
-
1
def binary(node)
-
1926
visit(node.left)
-
1926
visit(node.right)
-
end
-
1927
def visit_CAT(n); binary(n); end
-
-
1
def nary(node)
-
node.children.each { |c| visit(c) }
-
end
-
1
def visit_OR(n); nary(n); end
-
-
1
def unary(node)
-
429
visit(node.left)
-
end
-
430
def visit_GROUP(n); unary(n); end
-
1
def visit_STAR(n); unary(n); end
-
-
1
def terminal(node); end
-
1
%w{ LITERAL SYMBOL SLASH DOT }.each do |t|
-
4
class_eval %{ def visit_#{t}(n); terminal(n); end }, __FILE__, __LINE__
-
end
-
end
-
-
# Loop through the requirements AST
-
1
class Each < Visitor # :nodoc:
-
1
attr_reader :block
-
-
1
def initialize(block)
-
439
@block = block
-
end
-
-
1
def visit(node)
-
4720
super
-
4720
block.call(node)
-
end
-
end
-
-
1
class String < Visitor # :nodoc:
-
1
private
-
-
1
def binary(node)
-
[visit(node.left), visit(node.right)].join
-
end
-
-
1
def nary(node)
-
node.children.map { |c| visit(c) }.join '|'
-
end
-
-
1
def terminal(node)
-
node.left
-
end
-
-
1
def visit_GROUP(node)
-
"(#{visit(node.left)})"
-
end
-
end
-
-
1
class OptimizedPath < Visitor # :nodoc:
-
1
def accept(node)
-
76
Array(visit(node))
-
end
-
-
1
private
-
-
1
def visit_CAT(node)
-
280
[visit(node.left), visit(node.right)].flatten
-
end
-
-
1
def visit_SYMBOL(node)
-
20
node.left[1..-1].to_sym
-
end
-
-
1
def visit_STAR(node)
-
visit(node.left)
-
end
-
-
1
def visit_GROUP(node)
-
74
[]
-
end
-
-
1
%w{ LITERAL SLASH DOT }.each do |t|
-
3
class_eval %{ def visit_#{t}(n); n.left; end }, __FILE__, __LINE__
-
end
-
end
-
-
# Used for formatting urls (url_for)
-
1
class Formatter < Visitor # :nodoc:
-
1
attr_reader :options
-
-
1
def initialize(options)
-
@options = options
-
end
-
-
1
private
-
-
1
def visit(node, optional = false)
-
case node.type
-
when :LITERAL, :SLASH, :DOT
-
node.left
-
when :STAR
-
visit(node.left)
-
when :GROUP
-
visit(node.left, true)
-
when :CAT
-
visit_CAT(node, optional)
-
when :SYMBOL
-
visit_SYMBOL(node)
-
end
-
end
-
-
1
def visit_CAT(node, optional)
-
left = visit(node.left, optional)
-
right = visit(node.right, optional)
-
-
if optional && !(right && left)
-
""
-
else
-
[left, right].join
-
end
-
end
-
-
1
def visit_SYMBOL(node)
-
if value = options[node.to_sym]
-
Router::Utils.escape_path(value)
-
end
-
end
-
end
-
-
1
class Dot < Visitor # :nodoc:
-
1
def initialize
-
@nodes = []
-
@edges = []
-
end
-
-
1
def accept(node)
-
super
-
<<-eodot
-
digraph parse_tree {
-
size="8,5"
-
node [shape = none];
-
edge [dir = none];
-
#{@nodes.join "\n"}
-
#{@edges.join("\n")}
-
}
-
eodot
-
end
-
-
1
private
-
-
1
def binary(node)
-
node.children.each do |c|
-
@edges << "#{node.object_id} -> #{c.object_id};"
-
end
-
super
-
end
-
-
1
def nary(node)
-
node.children.each do |c|
-
@edges << "#{node.object_id} -> #{c.object_id};"
-
end
-
super
-
end
-
-
1
def unary(node)
-
@edges << "#{node.object_id} -> #{node.left.object_id};"
-
super
-
end
-
-
1
def visit_GROUP(node)
-
@nodes << "#{node.object_id} [label=\"()\"];"
-
super
-
end
-
-
1
def visit_CAT(node)
-
@nodes << "#{node.object_id} [label=\"○\"];"
-
super
-
end
-
-
1
def visit_STAR(node)
-
@nodes << "#{node.object_id} [label=\"*\"];"
-
super
-
end
-
-
1
def visit_OR(node)
-
@nodes << "#{node.object_id} [label=\"|\"];"
-
super
-
end
-
-
1
def terminal(node)
-
value = node.left
-
-
@nodes << "#{node.object_id} [label=\"#{value}\"];"
-
end
-
end
-
end
-
end
-
end
-
-
1
module ActionDispatch
-
# Provide callbacks to be executed before and after the request dispatch.
-
1
class Callbacks
-
1
include ActiveSupport::Callbacks
-
-
1
define_callbacks :call
-
-
1
class << self
-
1
delegate :to_prepare, :to_cleanup, :to => "ActionDispatch::Reloader"
-
-
1
def before(*args, &block)
-
set_callback(:call, :before, *args, &block)
-
end
-
-
1
def after(*args, &block)
-
set_callback(:call, :after, *args, &block)
-
end
-
end
-
-
1
def initialize(app)
-
1
@app = app
-
end
-
-
1
def call(env)
-
error = nil
-
result = run_callbacks :call do
-
begin
-
@app.call(env)
-
rescue => error
-
end
-
end
-
raise error if error
-
result
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/keys'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'active_support/key_generator'
-
1
require 'active_support/message_verifier'
-
-
1
module ActionDispatch
-
1
class Request < Rack::Request
-
1
def cookie_jar
-
env['action_dispatch.cookies'] ||= Cookies::CookieJar.build(self)
-
end
-
end
-
-
# \Cookies are read and written through ActionController#cookies.
-
#
-
# The cookies being read are the ones received along with the request, the cookies
-
# being written will be sent out with the response. Reading a cookie does not get
-
# the cookie object itself back, just the value it holds.
-
#
-
# Examples of writing:
-
#
-
# # Sets a simple session cookie.
-
# # This cookie will be deleted when the user's browser is closed.
-
# cookies[:user_name] = "david"
-
#
-
# # Cookie values are String based. Other data types need to be serialized.
-
# cookies[:lat_lon] = JSON.generate([47.68, -122.37])
-
#
-
# # Sets a cookie that expires in 1 hour.
-
# cookies[:login] = { value: "XJ-122", expires: 1.hour.from_now }
-
#
-
# # Sets a signed cookie, which prevents users from tampering with its value.
-
# # The cookie is signed by your app's `secrets.secret_key_base` value.
-
# # It can be read using the signed method `cookies.signed[:name]`
-
# cookies.signed[:user_id] = current_user.id
-
#
-
# # Sets a "permanent" cookie (which expires in 20 years from now).
-
# cookies.permanent[:login] = "XJ-122"
-
#
-
# # You can also chain these methods:
-
# cookies.permanent.signed[:login] = "XJ-122"
-
#
-
# Examples of reading:
-
#
-
# cookies[:user_name] # => "david"
-
# cookies.size # => 2
-
# JSON.parse(cookies[:lat_lon]) # => [47.68, -122.37]
-
# cookies.signed[:login] # => "XJ-122"
-
#
-
# Example for deleting:
-
#
-
# cookies.delete :user_name
-
#
-
# Please note that if you specify a :domain when setting a cookie, you must also specify the domain when deleting the cookie:
-
#
-
# cookies[:name] = {
-
# value: 'a yummy cookie',
-
# expires: 1.year.from_now,
-
# domain: 'domain.com'
-
# }
-
#
-
# cookies.delete(:name, domain: 'domain.com')
-
#
-
# The option symbols for setting cookies are:
-
#
-
# * <tt>:value</tt> - The cookie's value.
-
# * <tt>:path</tt> - The path for which this cookie applies. Defaults to the root
-
# of the application.
-
# * <tt>:domain</tt> - The domain for which this cookie applies so you can
-
# restrict to the domain level. If you use a schema like www.example.com
-
# and want to share session with user.example.com set <tt>:domain</tt>
-
# to <tt>:all</tt>. Make sure to specify the <tt>:domain</tt> option with
-
# <tt>:all</tt> again when deleting cookies.
-
#
-
# domain: nil # Does not sets cookie domain. (default)
-
# domain: :all # Allow the cookie for the top most level
-
# domain and subdomains.
-
#
-
# * <tt>:expires</tt> - The time at which this cookie expires, as a \Time object.
-
# * <tt>:secure</tt> - Whether this cookie is only transmitted to HTTPS servers.
-
# Default is +false+.
-
# * <tt>:httponly</tt> - Whether this cookie is accessible via scripting or
-
# only HTTP. Defaults to +false+.
-
1
class Cookies
-
1
HTTP_HEADER = "Set-Cookie".freeze
-
1
GENERATOR_KEY = "action_dispatch.key_generator".freeze
-
1
SIGNED_COOKIE_SALT = "action_dispatch.signed_cookie_salt".freeze
-
1
ENCRYPTED_COOKIE_SALT = "action_dispatch.encrypted_cookie_salt".freeze
-
1
ENCRYPTED_SIGNED_COOKIE_SALT = "action_dispatch.encrypted_signed_cookie_salt".freeze
-
1
SECRET_TOKEN = "action_dispatch.secret_token".freeze
-
1
SECRET_KEY_BASE = "action_dispatch.secret_key_base".freeze
-
1
COOKIES_SERIALIZER = "action_dispatch.cookies_serializer".freeze
-
-
# Cookies can typically store 4096 bytes.
-
1
MAX_COOKIE_SIZE = 4096
-
-
# Raised when storing more than 4K of session data.
-
1
CookieOverflow = Class.new StandardError
-
-
# Include in a cookie jar to allow chaining, e.g. cookies.permanent.signed
-
1
module ChainedCookieJars
-
# Returns a jar that'll automatically set the assigned cookies to have an expiration date 20 years from now. Example:
-
#
-
# cookies.permanent[:prefers_open_id] = true
-
# # => Set-Cookie: prefers_open_id=true; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT
-
#
-
# This jar is only meant for writing. You'll read permanent cookies through the regular accessor.
-
#
-
# This jar allows chaining with the signed jar as well, so you can set permanent, signed cookies. Examples:
-
#
-
# cookies.permanent.signed[:remember_me] = current_user.id
-
# # => Set-Cookie: remember_me=BAhU--848956038e692d7046deab32b7131856ab20e14e; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT
-
1
def permanent
-
@permanent ||= PermanentCookieJar.new(self, @key_generator, @options)
-
end
-
-
# Returns a jar that'll automatically generate a signed representation of cookie value and verify it when reading from
-
# the cookie again. This is useful for creating cookies with values that the user is not supposed to change. If a signed
-
# cookie was tampered with by the user (or a 3rd party), nil will be returned.
-
#
-
# If +secrets.secret_key_base+ and +config.secret_token+ (deprecated) are both set,
-
# legacy cookies signed with the old key generator will be transparently upgraded.
-
#
-
# This jar requires that you set a suitable secret for the verification on your app's +secrets.secret_key_base+.
-
#
-
# Example:
-
#
-
# cookies.signed[:discount] = 45
-
# # => Set-Cookie: discount=BAhpMg==--2c1c6906c90a3bc4fd54a51ffb41dffa4bf6b5f7; path=/
-
#
-
# cookies.signed[:discount] # => 45
-
1
def signed
-
@signed ||=
-
if @options[:upgrade_legacy_signed_cookies]
-
UpgradeLegacySignedCookieJar.new(self, @key_generator, @options)
-
else
-
SignedCookieJar.new(self, @key_generator, @options)
-
end
-
end
-
-
# Returns a jar that'll automatically encrypt cookie values before sending them to the client and will decrypt them for read.
-
# If the cookie was tampered with by the user (or a 3rd party), nil will be returned.
-
#
-
# If +secrets.secret_key_base+ and +config.secret_token+ (deprecated) are both set,
-
# legacy cookies signed with the old key generator will be transparently upgraded.
-
#
-
# This jar requires that you set a suitable secret for the verification on your app's +secrets.secret_key_base+.
-
#
-
# Example:
-
#
-
# cookies.encrypted[:discount] = 45
-
# # => Set-Cookie: discount=ZS9ZZ1R4cG1pcUJ1bm80anhQang3dz09LS1mbDZDSU5scGdOT3ltQ2dTdlhSdWpRPT0%3D--ab54663c9f4e3bc340c790d6d2b71e92f5b60315; path=/
-
#
-
# cookies.encrypted[:discount] # => 45
-
1
def encrypted
-
@encrypted ||=
-
if @options[:upgrade_legacy_signed_cookies]
-
UpgradeLegacyEncryptedCookieJar.new(self, @key_generator, @options)
-
else
-
EncryptedCookieJar.new(self, @key_generator, @options)
-
end
-
end
-
-
# Returns the +signed+ or +encrypted+ jar, preferring +encrypted+ if +secret_key_base+ is set.
-
# Used by ActionDispatch::Session::CookieStore to avoid the need to introduce new cookie stores.
-
1
def signed_or_encrypted
-
@signed_or_encrypted ||=
-
if @options[:secret_key_base].present?
-
encrypted
-
else
-
signed
-
end
-
end
-
end
-
-
1
module VerifyAndUpgradeLegacySignedMessage
-
1
def initialize(*args)
-
super
-
@legacy_verifier = ActiveSupport::MessageVerifier.new(@options[:secret_token])
-
end
-
-
1
def verify_and_upgrade_legacy_signed_message(name, signed_message)
-
@legacy_verifier.verify(signed_message).tap do |value|
-
self[name] = { value: value }
-
end
-
rescue ActiveSupport::MessageVerifier::InvalidSignature
-
nil
-
end
-
end
-
-
1
class CookieJar #:nodoc:
-
1
include Enumerable, ChainedCookieJars
-
-
# This regular expression is used to split the levels of a domain.
-
# The top level domain can be any string without a period or
-
# **.**, ***.** style TLDs like co.uk or com.au
-
#
-
# www.example.co.uk gives:
-
# $& => example.co.uk
-
#
-
# example.com gives:
-
# $& => example.com
-
#
-
# lots.of.subdomains.example.local gives:
-
# $& => example.local
-
1
DOMAIN_REGEXP = /[^.]*\.([^.]*|..\...|...\...)$/
-
-
1
def self.options_for_env(env) #:nodoc:
-
{ signed_cookie_salt: env[SIGNED_COOKIE_SALT] || '',
-
encrypted_cookie_salt: env[ENCRYPTED_COOKIE_SALT] || '',
-
encrypted_signed_cookie_salt: env[ENCRYPTED_SIGNED_COOKIE_SALT] || '',
-
secret_token: env[SECRET_TOKEN],
-
secret_key_base: env[SECRET_KEY_BASE],
-
upgrade_legacy_signed_cookies: env[SECRET_TOKEN].present? && env[SECRET_KEY_BASE].present?,
-
serializer: env[COOKIES_SERIALIZER]
-
}
-
end
-
-
1
def self.build(request)
-
env = request.env
-
key_generator = env[GENERATOR_KEY]
-
options = options_for_env env
-
-
host = request.host
-
secure = request.ssl?
-
-
new(key_generator, host, secure, options).tap do |hash|
-
hash.update(request.cookies)
-
end
-
end
-
-
1
def initialize(key_generator, host = nil, secure = false, options = {})
-
@key_generator = key_generator
-
@set_cookies = {}
-
@delete_cookies = {}
-
@host = host
-
@secure = secure
-
@options = options
-
@cookies = {}
-
@committed = false
-
end
-
-
1
def committed?; @committed; end
-
-
1
def commit!
-
@committed = true
-
@set_cookies.freeze
-
@delete_cookies.freeze
-
end
-
-
1
def each(&block)
-
@cookies.each(&block)
-
end
-
-
# Returns the value of the cookie by +name+, or +nil+ if no such cookie exists.
-
1
def [](name)
-
@cookies[name.to_s]
-
end
-
-
1
def fetch(name, *args, &block)
-
@cookies.fetch(name.to_s, *args, &block)
-
end
-
-
1
def key?(name)
-
@cookies.key?(name.to_s)
-
end
-
1
alias :has_key? :key?
-
-
1
def update(other_hash)
-
@cookies.update other_hash.stringify_keys
-
self
-
end
-
-
1
def handle_options(options) #:nodoc:
-
options[:path] ||= "/"
-
-
if options[:domain] == :all
-
# if there is a provided tld length then we use it otherwise default domain regexp
-
domain_regexp = options[:tld_length] ? /([^.]+\.?){#{options[:tld_length]}}$/ : DOMAIN_REGEXP
-
-
# if host is not ip and matches domain regexp
-
# (ip confirms to domain regexp so we explicitly check for ip)
-
options[:domain] = if (@host !~ /^[\d.]+$/) && (@host =~ domain_regexp)
-
".#{$&}"
-
end
-
elsif options[:domain].is_a? Array
-
# if host matches one of the supplied domains without a dot in front of it
-
options[:domain] = options[:domain].find {|domain| @host.include? domain.sub(/^\./, '') }
-
end
-
end
-
-
# Sets the cookie named +name+. The second argument may be the very cookie
-
# value, or a hash of options as documented above.
-
1
def []=(name, options)
-
if options.is_a?(Hash)
-
options.symbolize_keys!
-
value = options[:value]
-
else
-
value = options
-
options = { :value => value }
-
end
-
-
handle_options(options)
-
-
if @cookies[name.to_s] != value or options[:expires]
-
@cookies[name.to_s] = value
-
@set_cookies[name.to_s] = options
-
@delete_cookies.delete(name.to_s)
-
end
-
-
value
-
end
-
-
# Removes the cookie on the client machine by setting the value to an empty string
-
# and the expiration date in the past. Like <tt>[]=</tt>, you can pass in
-
# an options hash to delete cookies with extra data such as a <tt>:path</tt>.
-
1
def delete(name, options = {})
-
return unless @cookies.has_key? name.to_s
-
-
options.symbolize_keys!
-
handle_options(options)
-
-
value = @cookies.delete(name.to_s)
-
@delete_cookies[name.to_s] = options
-
value
-
end
-
-
# Whether the given cookie is to be deleted by this CookieJar.
-
# Like <tt>[]=</tt>, you can pass in an options hash to test if a
-
# deletion applies to a specific <tt>:path</tt>, <tt>:domain</tt> etc.
-
1
def deleted?(name, options = {})
-
options.symbolize_keys!
-
handle_options(options)
-
@delete_cookies[name.to_s] == options
-
end
-
-
# Removes all cookies on the client machine by calling <tt>delete</tt> for each cookie
-
1
def clear(options = {})
-
@cookies.each_key{ |k| delete(k, options) }
-
end
-
-
1
def write(headers)
-
@set_cookies.each { |k, v| ::Rack::Utils.set_cookie_header!(headers, k, v) if write_cookie?(v) }
-
@delete_cookies.each { |k, v| ::Rack::Utils.delete_cookie_header!(headers, k, v) }
-
end
-
-
1
def recycle! #:nodoc:
-
@set_cookies = {}
-
@delete_cookies = {}
-
end
-
-
1
mattr_accessor :always_write_cookie
-
1
self.always_write_cookie = false
-
-
1
private
-
1
def write_cookie?(cookie)
-
@secure || !cookie[:secure] || always_write_cookie
-
end
-
end
-
-
1
class PermanentCookieJar #:nodoc:
-
1
include ChainedCookieJars
-
-
1
def initialize(parent_jar, key_generator, options = {})
-
@parent_jar = parent_jar
-
@key_generator = key_generator
-
@options = options
-
end
-
-
1
def [](name)
-
@parent_jar[name.to_s]
-
end
-
-
1
def []=(name, options)
-
if options.is_a?(Hash)
-
options.symbolize_keys!
-
else
-
options = { :value => options }
-
end
-
-
options[:expires] = 20.years.from_now
-
@parent_jar[name] = options
-
end
-
end
-
-
1
class JsonSerializer
-
1
def self.load(value)
-
JSON.parse(value, quirks_mode: true)
-
end
-
-
1
def self.dump(value)
-
JSON.generate(value, quirks_mode: true)
-
end
-
end
-
-
# Passing the NullSerializer downstream to the Message{Encryptor,Verifier}
-
# allows us to handle the (de)serialization step within the cookie jar,
-
# which gives us the opportunity to detect and migrate legacy cookies.
-
1
class NullSerializer
-
1
def self.load(value)
-
value
-
end
-
-
1
def self.dump(value)
-
value
-
end
-
end
-
-
1
module SerializedCookieJars
-
1
MARSHAL_SIGNATURE = "\x04\x08".freeze
-
-
1
protected
-
1
def needs_migration?(value)
-
@options[:serializer] == :hybrid && value.start_with?(MARSHAL_SIGNATURE)
-
end
-
-
1
def serialize(name, value)
-
serializer.dump(value)
-
end
-
-
1
def deserialize(name, value)
-
if value
-
if needs_migration?(value)
-
Marshal.load(value).tap do |v|
-
self[name] = { value: v }
-
end
-
else
-
serializer.load(value)
-
end
-
end
-
end
-
-
1
def serializer
-
serializer = @options[:serializer] || :marshal
-
case serializer
-
when :marshal
-
Marshal
-
when :json, :hybrid
-
JsonSerializer
-
else
-
serializer
-
end
-
end
-
end
-
-
1
class SignedCookieJar #:nodoc:
-
1
include ChainedCookieJars
-
1
include SerializedCookieJars
-
-
1
def initialize(parent_jar, key_generator, options = {})
-
@parent_jar = parent_jar
-
@options = options
-
secret = key_generator.generate_key(@options[:signed_cookie_salt])
-
@verifier = ActiveSupport::MessageVerifier.new(secret, serializer: NullSerializer)
-
end
-
-
1
def [](name)
-
if signed_message = @parent_jar[name]
-
deserialize name, verify(signed_message)
-
end
-
end
-
-
1
def []=(name, options)
-
if options.is_a?(Hash)
-
options.symbolize_keys!
-
options[:value] = @verifier.generate(serialize(name, options[:value]))
-
else
-
options = { :value => @verifier.generate(serialize(name, options)) }
-
end
-
-
raise CookieOverflow if options[:value].size > MAX_COOKIE_SIZE
-
@parent_jar[name] = options
-
end
-
-
1
private
-
1
def verify(signed_message)
-
@verifier.verify(signed_message)
-
rescue ActiveSupport::MessageVerifier::InvalidSignature
-
nil
-
end
-
end
-
-
# UpgradeLegacySignedCookieJar is used instead of SignedCookieJar if
-
# config.secret_token and secrets.secret_key_base are both set. It reads
-
# legacy cookies signed with the old dummy key generator and re-saves
-
# them using the new key generator to provide a smooth upgrade path.
-
1
class UpgradeLegacySignedCookieJar < SignedCookieJar #:nodoc:
-
1
include VerifyAndUpgradeLegacySignedMessage
-
-
1
def [](name)
-
if signed_message = @parent_jar[name]
-
deserialize(name, verify(signed_message)) || verify_and_upgrade_legacy_signed_message(name, signed_message)
-
end
-
end
-
end
-
-
1
class EncryptedCookieJar #:nodoc:
-
1
include ChainedCookieJars
-
1
include SerializedCookieJars
-
-
1
def initialize(parent_jar, key_generator, options = {})
-
if ActiveSupport::LegacyKeyGenerator === key_generator
-
raise "You didn't set secrets.secret_key_base, which is required for this cookie jar. " +
-
"Read the upgrade documentation to learn more about this new config option."
-
end
-
-
@parent_jar = parent_jar
-
@options = options
-
secret = key_generator.generate_key(@options[:encrypted_cookie_salt])
-
sign_secret = key_generator.generate_key(@options[:encrypted_signed_cookie_salt])
-
@encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret, serializer: NullSerializer)
-
end
-
-
1
def [](name)
-
if encrypted_message = @parent_jar[name]
-
deserialize name, decrypt_and_verify(encrypted_message)
-
end
-
end
-
-
1
def []=(name, options)
-
if options.is_a?(Hash)
-
options.symbolize_keys!
-
else
-
options = { :value => options }
-
end
-
-
options[:value] = @encryptor.encrypt_and_sign(serialize(name, options[:value]))
-
-
raise CookieOverflow if options[:value].size > MAX_COOKIE_SIZE
-
@parent_jar[name] = options
-
end
-
-
1
private
-
1
def decrypt_and_verify(encrypted_message)
-
@encryptor.decrypt_and_verify(encrypted_message)
-
rescue ActiveSupport::MessageVerifier::InvalidSignature, ActiveSupport::MessageEncryptor::InvalidMessage
-
nil
-
end
-
end
-
-
# UpgradeLegacyEncryptedCookieJar is used by ActionDispatch::Session::CookieStore
-
# instead of EncryptedCookieJar if config.secret_token and secrets.secret_key_base
-
# are both set. It reads legacy cookies signed with the old dummy key generator and
-
# encrypts and re-saves them using the new key generator to provide a smooth upgrade path.
-
1
class UpgradeLegacyEncryptedCookieJar < EncryptedCookieJar #:nodoc:
-
1
include VerifyAndUpgradeLegacySignedMessage
-
-
1
def [](name)
-
if encrypted_or_signed_message = @parent_jar[name]
-
deserialize(name, decrypt_and_verify(encrypted_or_signed_message)) || verify_and_upgrade_legacy_signed_message(name, encrypted_or_signed_message)
-
end
-
end
-
end
-
-
1
def initialize(app)
-
1
@app = app
-
end
-
-
1
def call(env)
-
status, headers, body = @app.call(env)
-
-
if cookie_jar = env['action_dispatch.cookies']
-
unless cookie_jar.committed?
-
cookie_jar.write(headers)
-
if headers[HTTP_HEADER].respond_to?(:join)
-
headers[HTTP_HEADER] = headers[HTTP_HEADER].join("\n")
-
end
-
end
-
end
-
-
[status, headers, body]
-
end
-
end
-
end
-
1
require 'action_dispatch/http/request'
-
1
require 'action_dispatch/middleware/exception_wrapper'
-
1
require 'action_dispatch/routing/inspector'
-
-
1
module ActionDispatch
-
# This middleware is responsible for logging exceptions and
-
# showing a debugging page in case the request is local.
-
1
class DebugExceptions
-
1
RESCUES_TEMPLATE_PATH = File.expand_path('../templates', __FILE__)
-
-
1
def initialize(app, routes_app = nil)
-
1
@app = app
-
1
@routes_app = routes_app
-
end
-
-
1
def call(env)
-
_, headers, body = response = @app.call(env)
-
-
if headers['X-Cascade'] == 'pass'
-
body.close if body.respond_to?(:close)
-
raise ActionController::RoutingError, "No route matches [#{env['REQUEST_METHOD']}] #{env['PATH_INFO'].inspect}"
-
end
-
-
response
-
rescue Exception => exception
-
raise exception if env['action_dispatch.show_exceptions'] == false
-
render_exception(env, exception)
-
end
-
-
1
private
-
-
1
def render_exception(env, exception)
-
wrapper = ExceptionWrapper.new(env, exception)
-
log_error(env, wrapper)
-
-
if env['action_dispatch.show_detailed_exceptions']
-
request = Request.new(env)
-
template = ActionView::Base.new([RESCUES_TEMPLATE_PATH],
-
request: request,
-
exception: wrapper.exception,
-
application_trace: wrapper.application_trace,
-
framework_trace: wrapper.framework_trace,
-
full_trace: wrapper.full_trace,
-
routes_inspector: routes_inspector(exception),
-
source_extract: wrapper.source_extract,
-
line_number: wrapper.line_number,
-
file: wrapper.file
-
)
-
file = "rescues/#{wrapper.rescue_template}"
-
-
if request.xhr?
-
body = template.render(template: file, layout: false, formats: [:text])
-
format = "text/plain"
-
else
-
body = template.render(template: file, layout: 'rescues/layout')
-
format = "text/html"
-
end
-
render(wrapper.status_code, body, format)
-
else
-
raise exception
-
end
-
end
-
-
1
def render(status, body, format)
-
[status, {'Content-Type' => "#{format}; charset=#{Response.default_charset}", 'Content-Length' => body.bytesize.to_s}, [body]]
-
end
-
-
1
def log_error(env, wrapper)
-
logger = logger(env)
-
return unless logger
-
-
exception = wrapper.exception
-
-
trace = wrapper.application_trace
-
trace = wrapper.framework_trace if trace.empty?
-
-
ActiveSupport::Deprecation.silence do
-
message = "\n#{exception.class} (#{exception.message}):\n"
-
message << exception.annoted_source_code.to_s if exception.respond_to?(:annoted_source_code)
-
message << " " << trace.join("\n ")
-
logger.fatal("#{message}\n\n")
-
end
-
end
-
-
1
def logger(env)
-
env['action_dispatch.logger'] || stderr_logger
-
end
-
-
1
def stderr_logger
-
@stderr_logger ||= ActiveSupport::Logger.new($stderr)
-
end
-
-
1
def routes_inspector(exception)
-
if @routes_app.respond_to?(:routes) && (exception.is_a?(ActionController::RoutingError) || exception.is_a?(ActionView::Template::Error))
-
ActionDispatch::Routing::RoutesInspector.new(@routes_app.routes.routes)
-
end
-
end
-
end
-
end
-
1
require 'action_controller/metal/exceptions'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
-
1
module ActionDispatch
-
1
class ExceptionWrapper
-
1
cattr_accessor :rescue_responses
-
1
@@rescue_responses = Hash.new(:internal_server_error)
-
1
@@rescue_responses.merge!(
-
'ActionController::RoutingError' => :not_found,
-
'AbstractController::ActionNotFound' => :not_found,
-
'ActionController::MethodNotAllowed' => :method_not_allowed,
-
'ActionController::UnknownHttpMethod' => :method_not_allowed,
-
'ActionController::NotImplemented' => :not_implemented,
-
'ActionController::UnknownFormat' => :not_acceptable,
-
'ActionController::InvalidAuthenticityToken' => :unprocessable_entity,
-
'ActionDispatch::ParamsParser::ParseError' => :bad_request,
-
'ActionController::BadRequest' => :bad_request,
-
'ActionController::ParameterMissing' => :bad_request
-
)
-
-
1
cattr_accessor :rescue_templates
-
1
@@rescue_templates = Hash.new('diagnostics')
-
1
@@rescue_templates.merge!(
-
'ActionView::MissingTemplate' => 'missing_template',
-
'ActionController::RoutingError' => 'routing_error',
-
'AbstractController::ActionNotFound' => 'unknown_action',
-
'ActionView::Template::Error' => 'template_error'
-
)
-
-
1
attr_reader :env, :exception, :line_number, :file
-
-
1
def initialize(env, exception)
-
@env = env
-
@exception = original_exception(exception)
-
end
-
-
1
def rescue_template
-
@@rescue_templates[@exception.class.name]
-
end
-
-
1
def status_code
-
self.class.status_code_for_exception(@exception.class.name)
-
end
-
-
1
def application_trace
-
clean_backtrace(:silent)
-
end
-
-
1
def framework_trace
-
clean_backtrace(:noise)
-
end
-
-
1
def full_trace
-
clean_backtrace(:all)
-
end
-
-
1
def self.status_code_for_exception(class_name)
-
Rack::Utils.status_code(@@rescue_responses[class_name])
-
end
-
-
1
def source_extract
-
if application_trace && trace = application_trace.first
-
file, line, _ = trace.split(":")
-
@file = file
-
@line_number = line.to_i
-
source_fragment(@file, @line_number)
-
end
-
end
-
-
1
private
-
-
1
def original_exception(exception)
-
if registered_original_exception?(exception)
-
exception.original_exception
-
else
-
exception
-
end
-
end
-
-
1
def registered_original_exception?(exception)
-
exception.respond_to?(:original_exception) && @@rescue_responses.has_key?(exception.original_exception.class.name)
-
end
-
-
1
def clean_backtrace(*args)
-
if backtrace_cleaner
-
backtrace_cleaner.clean(@exception.backtrace, *args)
-
else
-
@exception.backtrace
-
end
-
end
-
-
1
def backtrace_cleaner
-
@backtrace_cleaner ||= @env['action_dispatch.backtrace_cleaner']
-
end
-
-
1
def source_fragment(path, line)
-
return unless Rails.respond_to?(:root) && Rails.root
-
full_path = Rails.root.join(path)
-
if File.exist?(full_path)
-
File.open(full_path, "r") do |file|
-
start = [line - 3, 0].max
-
lines = file.each_line.drop(start).take(6)
-
Hash[*(start+1..(lines.count+start)).zip(lines).flatten]
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/keys'
-
-
1
module ActionDispatch
-
1
class Request < Rack::Request
-
# Access the contents of the flash. Use <tt>flash["notice"]</tt> to
-
# read a notice you put there or <tt>flash["notice"] = "hello"</tt>
-
# to put a new one.
-
1
def flash
-
@env[Flash::KEY] ||= Flash::FlashHash.from_session_value(session["flash"])
-
end
-
end
-
-
# The flash provides a way to pass temporary objects between actions. Anything you place in the flash will be exposed
-
# to the very next action and then cleared out. This is a great way of doing notices and alerts, such as a create
-
# action that sets <tt>flash[:notice] = "Post successfully created"</tt> before redirecting to a display action that can
-
# then expose the flash to its template. Actually, that exposure is automatically done.
-
#
-
# class PostsController < ActionController::Base
-
# def create
-
# # save post
-
# flash[:notice] = "Post successfully created"
-
# redirect_to @post
-
# end
-
#
-
# def show
-
# # doesn't need to assign the flash notice to the template, that's done automatically
-
# end
-
# end
-
#
-
# show.html.erb
-
# <% if flash[:notice] %>
-
# <div class="notice"><%= flash[:notice] %></div>
-
# <% end %>
-
#
-
# Since the +notice+ and +alert+ keys are a common idiom, convenience accessors are available:
-
#
-
# flash.alert = "You must be logged in"
-
# flash.notice = "Post successfully created"
-
#
-
# This example just places a string in the flash, but you can put any object in there. And of course, you can put as
-
# many as you like at a time too. Just remember: They'll be gone by the time the next action has been performed.
-
#
-
# See docs on the FlashHash class for more details about the flash.
-
1
class Flash
-
1
KEY = 'action_dispatch.request.flash_hash'.freeze
-
-
1
class FlashNow #:nodoc:
-
1
attr_accessor :flash
-
-
1
def initialize(flash)
-
@flash = flash
-
end
-
-
1
def []=(k, v)
-
k = k.to_s
-
@flash[k] = v
-
@flash.discard(k)
-
v
-
end
-
-
1
def [](k)
-
@flash[k.to_s]
-
end
-
-
# Convenience accessor for <tt>flash.now[:alert]=</tt>.
-
1
def alert=(message)
-
self[:alert] = message
-
end
-
-
# Convenience accessor for <tt>flash.now[:notice]=</tt>.
-
1
def notice=(message)
-
self[:notice] = message
-
end
-
end
-
-
1
class FlashHash
-
1
include Enumerable
-
-
1
def self.from_session_value(value)
-
flash = case value
-
when FlashHash # Rails 3.1, 3.2
-
new(value.instance_variable_get(:@flashes), value.instance_variable_get(:@used))
-
when Hash # Rails 4.0
-
new(value['flashes'], value['discard'])
-
else
-
new
-
end
-
-
flash.tap(&:sweep)
-
end
-
-
1
def to_session_value
-
return nil if empty?
-
{'discard' => @discard.to_a, 'flashes' => @flashes}
-
end
-
-
1
def initialize(flashes = {}, discard = []) #:nodoc:
-
@discard = Set.new(stringify_array(discard))
-
@flashes = flashes.stringify_keys
-
@now = nil
-
end
-
-
1
def initialize_copy(other)
-
if other.now_is_loaded?
-
@now = other.now.dup
-
@now.flash = self
-
end
-
super
-
end
-
-
1
def []=(k, v)
-
k = k.to_s
-
@discard.delete k
-
@flashes[k] = v
-
end
-
-
1
def [](k)
-
@flashes[k.to_s]
-
end
-
-
1
def update(h) #:nodoc:
-
@discard.subtract stringify_array(h.keys)
-
@flashes.update h.stringify_keys
-
self
-
end
-
-
1
def keys
-
@flashes.keys
-
end
-
-
1
def key?(name)
-
@flashes.key? name
-
end
-
-
1
def delete(key)
-
key = key.to_s
-
@discard.delete key
-
@flashes.delete key
-
self
-
end
-
-
1
def to_hash
-
@flashes.dup
-
end
-
-
1
def empty?
-
@flashes.empty?
-
end
-
-
1
def clear
-
@discard.clear
-
@flashes.clear
-
end
-
-
1
def each(&block)
-
@flashes.each(&block)
-
end
-
-
1
alias :merge! :update
-
-
1
def replace(h) #:nodoc:
-
@discard.clear
-
@flashes.replace h.stringify_keys
-
self
-
end
-
-
# Sets a flash that will not be available to the next action, only to the current.
-
#
-
# flash.now[:message] = "Hello current action"
-
#
-
# This method enables you to use the flash as a central messaging system in your app.
-
# When you need to pass an object to the next action, you use the standard flash assign (<tt>[]=</tt>).
-
# When you need to pass an object to the current action, you use <tt>now</tt>, and your object will
-
# vanish when the current action is done.
-
#
-
# Entries set via <tt>now</tt> are accessed the same way as standard entries: <tt>flash['my-key']</tt>.
-
#
-
# Also, brings two convenience accessors:
-
#
-
# flash.now.alert = "Beware now!"
-
# # Equivalent to flash.now[:alert] = "Beware now!"
-
#
-
# flash.now.notice = "Good luck now!"
-
# # Equivalent to flash.now[:notice] = "Good luck now!"
-
1
def now
-
@now ||= FlashNow.new(self)
-
end
-
-
# Keeps either the entire current flash or a specific flash entry available for the next action:
-
#
-
# flash.keep # keeps the entire flash
-
# flash.keep(:notice) # keeps only the "notice" entry, the rest of the flash is discarded
-
1
def keep(k = nil)
-
k = k.to_s if k
-
@discard.subtract Array(k || keys)
-
k ? self[k] : self
-
end
-
-
# Marks the entire flash or a single flash entry to be discarded by the end of the current action:
-
#
-
# flash.discard # discard the entire flash at the end of the current action
-
# flash.discard(:warning) # discard only the "warning" entry at the end of the current action
-
1
def discard(k = nil)
-
k = k.to_s if k
-
@discard.merge Array(k || keys)
-
k ? self[k] : self
-
end
-
-
# Mark for removal entries that were kept, and delete unkept ones.
-
#
-
# This method is called automatically by filters, so you generally don't need to care about it.
-
1
def sweep #:nodoc:
-
@discard.each { |k| @flashes.delete k }
-
@discard.replace @flashes.keys
-
end
-
-
# Convenience accessor for <tt>flash[:alert]</tt>.
-
1
def alert
-
self[:alert]
-
end
-
-
# Convenience accessor for <tt>flash[:alert]=</tt>.
-
1
def alert=(message)
-
self[:alert] = message
-
end
-
-
# Convenience accessor for <tt>flash[:notice]</tt>.
-
1
def notice
-
self[:notice]
-
end
-
-
# Convenience accessor for <tt>flash[:notice]=</tt>.
-
1
def notice=(message)
-
self[:notice] = message
-
end
-
-
1
protected
-
1
def now_is_loaded?
-
@now
-
end
-
-
1
def stringify_array(array)
-
array.map do |item|
-
item.kind_of?(Symbol) ? item.to_s : item
-
end
-
end
-
end
-
-
1
def initialize(app)
-
1
@app = app
-
end
-
-
1
def call(env)
-
@app.call(env)
-
ensure
-
session = Request::Session.find(env) || {}
-
flash_hash = env[KEY]
-
-
if flash_hash && (flash_hash.present? || session.key?('flash'))
-
session["flash"] = flash_hash.to_session_value
-
env[KEY] = flash_hash.dup
-
end
-
-
if (!session.respond_to?(:loaded?) || session.loaded?) && # (reset_session uses {}, which doesn't implement #loaded?)
-
session.key?('flash') && session['flash'].nil?
-
session.delete('flash')
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/conversions'
-
1
require 'action_dispatch/http/request'
-
1
require 'active_support/core_ext/hash/indifferent_access'
-
-
1
module ActionDispatch
-
1
class ParamsParser
-
1
class ParseError < StandardError
-
1
attr_reader :original_exception
-
-
1
def initialize(message, original_exception)
-
super(message)
-
@original_exception = original_exception
-
end
-
end
-
-
1
DEFAULT_PARSERS = { Mime::JSON => :json }
-
-
1
def initialize(app, parsers = {})
-
1
@app, @parsers = app, DEFAULT_PARSERS.merge(parsers)
-
end
-
-
1
def call(env)
-
if params = parse_formatted_parameters(env)
-
env["action_dispatch.request.request_parameters"] = params
-
end
-
-
@app.call(env)
-
end
-
-
1
private
-
1
def parse_formatted_parameters(env)
-
request = Request.new(env)
-
-
return false if request.content_length.zero?
-
-
strategy = @parsers[request.content_mime_type]
-
-
return false unless strategy
-
-
case strategy
-
when Proc
-
strategy.call(request.raw_post)
-
when :json
-
data = ActiveSupport::JSON.decode(request.raw_post)
-
data = {:_json => data} unless data.is_a?(Hash)
-
Request::Utils.deep_munge(data).with_indifferent_access
-
else
-
false
-
end
-
rescue Exception => e # JSON or Ruby code block errors
-
logger(env).debug "Error occurred while parsing request parameters.\nContents:\n\n#{request.raw_post}"
-
-
raise ParseError.new(e.message, e)
-
end
-
-
1
def logger(env)
-
env['action_dispatch.logger'] || ActiveSupport::Logger.new($stderr)
-
end
-
end
-
end
-
1
module ActionDispatch
-
1
class PublicExceptions
-
1
attr_accessor :public_path
-
-
1
def initialize(public_path)
-
1
@public_path = public_path
-
end
-
-
1
def call(env)
-
status = env["PATH_INFO"][1..-1]
-
request = ActionDispatch::Request.new(env)
-
content_type = request.formats.first
-
body = { :status => status, :error => Rack::Utils::HTTP_STATUS_CODES.fetch(status.to_i, Rack::Utils::HTTP_STATUS_CODES[500]) }
-
-
render(status, content_type, body)
-
end
-
-
1
private
-
-
1
def render(status, content_type, body)
-
format = "to_#{content_type.to_sym}" if content_type
-
if format && body.respond_to?(format)
-
render_format(status, content_type, body.public_send(format))
-
else
-
render_html(status)
-
end
-
end
-
-
1
def render_format(status, content_type, body)
-
[status, {'Content-Type' => "#{content_type}; charset=#{ActionDispatch::Response.default_charset}",
-
'Content-Length' => body.bytesize.to_s}, [body]]
-
end
-
-
1
def render_html(status)
-
found = false
-
path = "#{public_path}/#{status}.#{I18n.locale}.html" if I18n.locale
-
path = "#{public_path}/#{status}.html" unless path && (found = File.exist?(path))
-
-
if found || File.exist?(path)
-
render_format(status, 'text/html', File.read(path))
-
else
-
[404, { "X-Cascade" => "pass" }, []]
-
end
-
end
-
end
-
end
-
1
require 'active_support/deprecation/reporting'
-
-
1
module ActionDispatch
-
# ActionDispatch::Reloader provides prepare and cleanup callbacks,
-
# intended to assist with code reloading during development.
-
#
-
# Prepare callbacks are run before each request, and cleanup callbacks
-
# after each request. In this respect they are analogs of ActionDispatch::Callback's
-
# before and after callbacks. However, cleanup callbacks are not called until the
-
# request is fully complete -- that is, after #close has been called on
-
# the response body. This is important for streaming responses such as the
-
# following:
-
#
-
# self.response_body = lambda { |response, output|
-
# # code here which refers to application models
-
# }
-
#
-
# Cleanup callbacks will not be called until after the response_body lambda
-
# is evaluated, ensuring that it can refer to application models and other
-
# classes before they are unloaded.
-
#
-
# By default, ActionDispatch::Reloader is included in the middleware stack
-
# only in the development environment; specifically, when +config.cache_classes+
-
# is false. Callbacks may be registered even when it is not included in the
-
# middleware stack, but are executed only when <tt>ActionDispatch::Reloader.prepare!</tt>
-
# or <tt>ActionDispatch::Reloader.cleanup!</tt> are called manually.
-
#
-
1
class Reloader
-
1
include ActiveSupport::Callbacks
-
1
include ActiveSupport::Deprecation::Reporting
-
-
1
define_callbacks :prepare
-
1
define_callbacks :cleanup
-
-
# Add a prepare callback. Prepare callbacks are run before each request, prior
-
# to ActionDispatch::Callback's before callbacks.
-
1
def self.to_prepare(*args, &block)
-
4
unless block_given?
-
warn "to_prepare without a block is deprecated. Please use a block"
-
end
-
4
set_callback(:prepare, *args, &block)
-
end
-
-
# Add a cleanup callback. Cleanup callbacks are run after each request is
-
# complete (after #close is called on the response body).
-
1
def self.to_cleanup(*args, &block)
-
unless block_given?
-
warn "to_cleanup without a block is deprecated. Please use a block"
-
end
-
set_callback(:cleanup, *args, &block)
-
end
-
-
# Execute all prepare callbacks.
-
1
def self.prepare!
-
1
new(nil).prepare!
-
end
-
-
# Execute all cleanup callbacks.
-
1
def self.cleanup!
-
new(nil).cleanup!
-
end
-
-
1
def initialize(app, condition=nil)
-
1
@app = app
-
1
@condition = condition || lambda { true }
-
1
@validated = true
-
end
-
-
1
def call(env)
-
@validated = @condition.call
-
prepare!
-
-
response = @app.call(env)
-
response[2] = ::Rack::BodyProxy.new(response[2]) { cleanup! }
-
-
response
-
rescue Exception
-
cleanup!
-
raise
-
end
-
-
1
def prepare! #:nodoc:
-
1
run_callbacks :prepare if validated?
-
end
-
-
1
def cleanup! #:nodoc:
-
run_callbacks :cleanup if validated?
-
ensure
-
@validated = true
-
end
-
-
1
private
-
-
1
def validated? #:nodoc:
-
1
@validated
-
end
-
end
-
end
-
1
module ActionDispatch
-
# This middleware calculates the IP address of the remote client that is
-
# making the request. It does this by checking various headers that could
-
# contain the address, and then picking the last-set address that is not
-
# on the list of trusted IPs. This follows the precedent set by e.g.
-
# {the Tomcat server}[https://issues.apache.org/bugzilla/show_bug.cgi?id=50453],
-
# with {reasoning explained at length}[http://blog.gingerlime.com/2012/rails-ip-spoofing-vulnerabilities-and-protection]
-
# by @gingerlime. A more detailed explanation of the algorithm is given
-
# at GetIp#calculate_ip.
-
#
-
# Some Rack servers concatenate repeated headers, like {HTTP RFC 2616}[http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2]
-
# requires. Some Rack servers simply drop preceding headers, and only report
-
# the value that was {given in the last header}[http://andre.arko.net/2011/12/26/repeated-headers-and-ruby-web-servers].
-
# If you are behind multiple proxy servers (like Nginx to HAProxy to Unicorn)
-
# then you should test your Rack server to make sure your data is good.
-
#
-
# IF YOU DON'T USE A PROXY, THIS MAKES YOU VULNERABLE TO IP SPOOFING.
-
# This middleware assumes that there is at least one proxy sitting around
-
# and setting headers with the client's remote IP address. If you don't use
-
# a proxy, because you are hosted on e.g. Heroku without SSL, any client can
-
# claim to have any IP address by setting the X-Forwarded-For header. If you
-
# care about that, then you need to explicitly drop or ignore those headers
-
# sometime before this middleware runs.
-
1
class RemoteIp
-
1
class IpSpoofAttackError < StandardError; end
-
-
# The default trusted IPs list simply includes IP addresses that are
-
# guaranteed by the IP specification to be private addresses. Those will
-
# not be the ultimate client IP in production, and so are discarded. See
-
# http://en.wikipedia.org/wiki/Private_network for details.
-
1
TRUSTED_PROXIES = %r{
-
^127\.0\.0\.1$ | # localhost IPv4
-
^::1$ | # localhost IPv6
-
^fc00: | # private IPv6 range fc00
-
^10\. | # private IPv4 range 10.x.x.x
-
^172\.(1[6-9]|2[0-9]|3[0-1])\.| # private IPv4 range 172.16.0.0 .. 172.31.255.255
-
^192\.168\. # private IPv4 range 192.168.x.x
-
}x
-
-
1
attr_reader :check_ip, :proxies
-
-
# Create a new +RemoteIp+ middleware instance.
-
#
-
# The +check_ip_spoofing+ option is on by default. When on, an exception
-
# is raised if it looks like the client is trying to lie about its own IP
-
# address. It makes sense to turn off this check on sites aimed at non-IP
-
# clients (like WAP devices), or behind proxies that set headers in an
-
# incorrect or confusing way (like AWS ELB).
-
#
-
# The +custom_proxies+ argument can take a regex, which will be used
-
# instead of +TRUSTED_PROXIES+, or a string, which will be used in addition
-
# to +TRUSTED_PROXIES+. Any proxy setup will put the value you want in the
-
# middle (or at the beginning) of the X-Forwarded-For list, with your proxy
-
# servers after it. If your proxies aren't removed, pass them in via the
-
# +custom_proxies+ parameter. That way, the middleware will ignore those
-
# IP addresses, and return the one that you want.
-
1
def initialize(app, check_ip_spoofing = true, custom_proxies = nil)
-
1
@app = app
-
1
@check_ip = check_ip_spoofing
-
1
@proxies = case custom_proxies
-
when Regexp
-
custom_proxies
-
when nil
-
1
TRUSTED_PROXIES
-
else
-
Regexp.union(TRUSTED_PROXIES, custom_proxies)
-
end
-
end
-
-
# Since the IP address may not be needed, we store the object here
-
# without calculating the IP to keep from slowing down the majority of
-
# requests. For those requests that do need to know the IP, the
-
# GetIp#calculate_ip method will calculate the memoized client IP address.
-
1
def call(env)
-
env["action_dispatch.remote_ip"] = GetIp.new(env, self)
-
@app.call(env)
-
end
-
-
# The GetIp class exists as a way to defer processing of the request data
-
# into an actual IP address. If the ActionDispatch::Request#remote_ip method
-
# is called, this class will calculate the value and then memoize it.
-
1
class GetIp
-
-
# This constant contains a regular expression that validates every known
-
# form of IP v4 and v6 address, with or without abbreviations, adapted
-
# from {this gist}[https://gist.github.com/gazay/1289635].
-
1
VALID_IP = %r{
-
(^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})){3}$) | # ip v4
-
(^(
-
(([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}) | # ip v6 not abbreviated
-
(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4}) | # ip v6 with double colon in the end
-
(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4}) | # - ip addresses v6
-
(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4}) | # - with
-
(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4}) | # - double colon
-
(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4}) | # - in the middle
-
(([0-9A-Fa-f]{1,4}:){6} ((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3} (\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4
-
(([0-9A-Fa-f]{1,4}:){1,5}:((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4
-
(([0-9A-Fa-f]{1,4}:){1}:([0-9A-Fa-f]{1,4}:){0,4}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4
-
(([0-9A-Fa-f]{1,4}:){0,2}:([0-9A-Fa-f]{1,4}:){0,3}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4
-
(([0-9A-Fa-f]{1,4}:){0,3}:([0-9A-Fa-f]{1,4}:){0,2}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4
-
(([0-9A-Fa-f]{1,4}:){0,4}:([0-9A-Fa-f]{1,4}:){1}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4
-
(::([0-9A-Fa-f]{1,4}:){0,5}((\b((25[0-5])|(1\d{2})|(2[0-4]\d) |(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4
-
([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4}) | # ip v6 with compatible to v4
-
(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4}) | # ip v6 with double colon at the beginning
-
(([0-9A-Fa-f]{1,4}:){1,7}:) # ip v6 without ending
-
)$)
-
}x
-
-
1
def initialize(env, middleware)
-
@env = env
-
@check_ip = middleware.check_ip
-
@proxies = middleware.proxies
-
end
-
-
# Sort through the various IP address headers, looking for the IP most
-
# likely to be the address of the actual remote client making this
-
# request.
-
#
-
# REMOTE_ADDR will be correct if the request is made directly against the
-
# Ruby process, on e.g. Heroku. When the request is proxied by another
-
# server like HAProxy or Nginx, the IP address that made the original
-
# request will be put in an X-Forwarded-For header. If there are multiple
-
# proxies, that header may contain a list of IPs. Other proxy services
-
# set the Client-Ip header instead, so we check that too.
-
#
-
# As discussed in {this post about Rails IP Spoofing}[http://blog.gingerlime.com/2012/rails-ip-spoofing-vulnerabilities-and-protection/],
-
# while the first IP in the list is likely to be the "originating" IP,
-
# it could also have been set by the client maliciously.
-
#
-
# In order to find the first address that is (probably) accurate, we
-
# take the list of IPs, remove known and trusted proxies, and then take
-
# the last address left, which was presumably set by one of those proxies.
-
1
def calculate_ip
-
# Set by the Rack web server, this is a single value.
-
remote_addr = ips_from('REMOTE_ADDR').last
-
-
# Could be a CSV list and/or repeated headers that were concatenated.
-
client_ips = ips_from('HTTP_CLIENT_IP').reverse
-
forwarded_ips = ips_from('HTTP_X_FORWARDED_FOR').reverse
-
-
# +Client-Ip+ and +X-Forwarded-For+ should not, generally, both be set.
-
# If they are both set, it means that this request passed through two
-
# proxies with incompatible IP header conventions, and there is no way
-
# for us to determine which header is the right one after the fact.
-
# Since we have no idea, we give up and explode.
-
should_check_ip = @check_ip && client_ips.last && forwarded_ips.last
-
if should_check_ip && !forwarded_ips.include?(client_ips.last)
-
# We don't know which came from the proxy, and which from the user
-
raise IpSpoofAttackError, "IP spoofing attack?! " +
-
"HTTP_CLIENT_IP=#{@env['HTTP_CLIENT_IP'].inspect} " +
-
"HTTP_X_FORWARDED_FOR=#{@env['HTTP_X_FORWARDED_FOR'].inspect}"
-
end
-
-
# We assume these things about the IP headers:
-
#
-
# - X-Forwarded-For will be a list of IPs, one per proxy, or blank
-
# - Client-Ip is propagated from the outermost proxy, or is blank
-
# - REMOTE_ADDR will be the IP that made the request to Rack
-
ips = [forwarded_ips, client_ips, remote_addr].flatten.compact
-
-
# If every single IP option is in the trusted list, just return REMOTE_ADDR
-
filter_proxies(ips).first || remote_addr
-
end
-
-
# Memoizes the value returned by #calculate_ip and returns it for
-
# ActionDispatch::Request to use.
-
1
def to_s
-
@ip ||= calculate_ip
-
end
-
-
1
protected
-
-
1
def ips_from(header)
-
# Split the comma-separated list into an array of strings
-
ips = @env[header] ? @env[header].strip.split(/[,\s]+/) : []
-
# Only return IPs that are valid according to the regex
-
ips.select{ |ip| ip =~ VALID_IP }
-
end
-
-
1
def filter_proxies(ips)
-
ips.reject { |ip| ip =~ @proxies }
-
end
-
-
end
-
-
end
-
end
-
1
require 'securerandom'
-
1
require 'active_support/core_ext/string/access'
-
-
1
module ActionDispatch
-
# Makes a unique request id available to the action_dispatch.request_id env variable (which is then accessible through
-
# ActionDispatch::Request#uuid) and sends the same id to the client via the X-Request-Id header.
-
#
-
# The unique request id is either based off the X-Request-Id header in the request, which would typically be generated
-
# by a firewall, load balancer, or the web server, or, if this header is not available, a random uuid. If the
-
# header is accepted from the outside world, we sanitize it to a max of 255 chars and alphanumeric and dashes only.
-
#
-
# The unique request id can be used to trace a request end-to-end and would typically end up being part of log files
-
# from multiple pieces of the stack.
-
1
class RequestId
-
1
def initialize(app)
-
1
@app = app
-
end
-
-
1
def call(env)
-
env["action_dispatch.request_id"] = external_request_id(env) || internal_request_id
-
@app.call(env).tap { |_status, headers, _body| headers["X-Request-Id"] = env["action_dispatch.request_id"] }
-
end
-
-
1
private
-
1
def external_request_id(env)
-
if request_id = env["HTTP_X_REQUEST_ID"].presence
-
request_id.gsub(/[^\w\-]/, "").first(255)
-
end
-
end
-
-
1
def internal_request_id
-
SecureRandom.uuid
-
end
-
end
-
end
-
1
require 'rack/utils'
-
1
require 'rack/request'
-
1
require 'rack/session/abstract/id'
-
1
require 'action_dispatch/middleware/cookies'
-
1
require 'action_dispatch/request/session'
-
-
1
module ActionDispatch
-
1
module Session
-
1
class SessionRestoreError < StandardError #:nodoc:
-
1
attr_reader :original_exception
-
-
1
def initialize(const_error)
-
@original_exception = const_error
-
-
super("Session contains objects whose class definition isn't available.\n" +
-
"Remember to require the classes for all objects kept in the session.\n" +
-
"(Original exception: #{const_error.message} [#{const_error.class}])\n")
-
end
-
end
-
-
1
module Compatibility
-
1
def initialize(app, options = {})
-
1
options[:key] ||= '_session_id'
-
1
super
-
end
-
-
1
def generate_sid
-
sid = SecureRandom.hex(16)
-
sid.encode!(Encoding::UTF_8)
-
sid
-
end
-
-
1
protected
-
-
1
def initialize_sid
-
1
@default_options.delete(:sidbits)
-
1
@default_options.delete(:secure_random)
-
end
-
end
-
-
1
module StaleSessionCheck
-
1
def load_session(env)
-
stale_session_check! { super }
-
end
-
-
1
def extract_session_id(env)
-
stale_session_check! { super }
-
end
-
-
1
def stale_session_check!
-
yield
-
rescue ArgumentError => argument_error
-
if argument_error.message =~ %r{undefined class/module ([\w:]*\w)}
-
begin
-
# Note that the regexp does not allow $1 to end with a ':'
-
$1.constantize
-
rescue LoadError, NameError => e
-
raise ActionDispatch::Session::SessionRestoreError, e, e.backtrace
-
end
-
retry
-
else
-
raise
-
end
-
end
-
end
-
-
1
module SessionObject # :nodoc:
-
1
def prepare_session(env)
-
Request::Session.create(self, env, @default_options)
-
end
-
-
1
def loaded_session?(session)
-
!session.is_a?(Request::Session) || session.loaded?
-
end
-
end
-
-
1
class AbstractStore < Rack::Session::Abstract::ID
-
1
include Compatibility
-
1
include StaleSessionCheck
-
1
include SessionObject
-
-
1
private
-
-
1
def set_cookie(env, session_id, cookie)
-
request = ActionDispatch::Request.new(env)
-
request.cookie_jar[key] = cookie
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/keys'
-
1
require 'action_dispatch/middleware/session/abstract_store'
-
1
require 'rack/session/cookie'
-
-
1
module ActionDispatch
-
1
module Session
-
# This cookie-based session store is the Rails default. It is
-
# dramatically faster than the alternatives.
-
#
-
# Sessions typically contain at most a user_id and flash message; both fit
-
# within the 4K cookie size limit. A CookieOverflow exception is raised if
-
# you attempt to store more than 4K of data.
-
#
-
# The cookie jar used for storage is automatically configured to be the
-
# best possible option given your application's configuration.
-
#
-
# If you only have secret_token set, your cookies will be signed, but
-
# not encrypted. This means a user cannot alter their +user_id+ without
-
# knowing your app's secret key, but can easily read their +user_id+. This
-
# was the default for Rails 3 apps.
-
#
-
# If you have secret_key_base set, your cookies will be encrypted. This
-
# goes a step further than signed cookies in that encrypted cookies cannot
-
# be altered or read by users. This is the default starting in Rails 4.
-
#
-
# If you have both secret_token and secret_key base set, your cookies will
-
# be encrypted, and signed cookies generated by Rails 3 will be
-
# transparently read and encrypted to provide a smooth upgrade path.
-
#
-
# Configure your session store in config/initializers/session_store.rb:
-
#
-
# Myapp::Application.config.session_store :cookie_store, key: '_your_app_session'
-
#
-
# Configure your secret key in config/secrets.yml:
-
#
-
# development:
-
# secret_key_base: 'secret key'
-
#
-
# To generate a secret key for an existing application, run `rake secret`.
-
#
-
# If you are upgrading an existing Rails 3 app, you should leave your
-
# existing secret_token in place and simply add the new secret_key_base.
-
# Note that you should wait to set secret_key_base until you have 100% of
-
# your userbase on Rails 4 and are reasonably sure you will not need to
-
# rollback to Rails 3. This is because cookies signed based on the new
-
# secret_key_base in Rails 4 are not backwards compatible with Rails 3.
-
# You are free to leave your existing secret_token in place, not set the
-
# new secret_key_base, and ignore the deprecation warnings until you are
-
# reasonably sure that your upgrade is otherwise complete. Additionally,
-
# you should take care to make sure you are not relying on the ability to
-
# decode signed cookies generated by your app in external applications or
-
# Javascript before upgrading.
-
#
-
# Note that changing the secret key will invalidate all existing sessions!
-
1
class CookieStore < Rack::Session::Abstract::ID
-
1
include Compatibility
-
1
include StaleSessionCheck
-
1
include SessionObject
-
-
1
def initialize(app, options={})
-
1
super(app, options.merge!(:cookie_only => true))
-
end
-
-
1
def destroy_session(env, session_id, options)
-
new_sid = generate_sid unless options[:drop]
-
# Reset hash and Assign the new session id
-
env["action_dispatch.request.unsigned_session_cookie"] = new_sid ? { "session_id" => new_sid } : {}
-
new_sid
-
end
-
-
1
def load_session(env)
-
stale_session_check! do
-
data = unpacked_cookie_data(env)
-
data = persistent_session_id!(data)
-
[data["session_id"], data]
-
end
-
end
-
-
1
private
-
-
1
def extract_session_id(env)
-
stale_session_check! do
-
unpacked_cookie_data(env)["session_id"]
-
end
-
end
-
-
1
def unpacked_cookie_data(env)
-
env["action_dispatch.request.unsigned_session_cookie"] ||= begin
-
stale_session_check! do
-
if data = get_cookie(env)
-
data.stringify_keys!
-
end
-
data || {}
-
end
-
end
-
end
-
-
1
def persistent_session_id!(data, sid=nil)
-
data ||= {}
-
data["session_id"] ||= sid || generate_sid
-
data
-
end
-
-
1
def set_session(env, sid, session_data, options)
-
session_data["session_id"] = sid
-
session_data
-
end
-
-
1
def set_cookie(env, session_id, cookie)
-
cookie_jar(env)[@key] = cookie
-
end
-
-
1
def get_cookie(env)
-
cookie_jar(env)[@key]
-
end
-
-
1
def cookie_jar(env)
-
request = ActionDispatch::Request.new(env)
-
request.cookie_jar.signed_or_encrypted
-
end
-
end
-
end
-
end
-
1
require 'action_dispatch/http/request'
-
1
require 'action_dispatch/middleware/exception_wrapper'
-
-
1
module ActionDispatch
-
# This middleware rescues any exception returned by the application
-
# and calls an exceptions app that will wrap it in a format for the end user.
-
#
-
# The exceptions app should be passed as parameter on initialization
-
# of ShowExceptions. Every time there is an exception, ShowExceptions will
-
# store the exception in env["action_dispatch.exception"], rewrite the
-
# PATH_INFO to the exception status code and call the rack app.
-
#
-
# If the application returns a "X-Cascade" pass response, this middleware
-
# will send an empty response as result with the correct status code.
-
# If any exception happens inside the exceptions app, this middleware
-
# catches the exceptions and returns a FAILSAFE_RESPONSE.
-
1
class ShowExceptions
-
1
FAILSAFE_RESPONSE = [500, { 'Content-Type' => 'text/plain' },
-
["500 Internal Server Error\n" \
-
"If you are the administrator of this website, then please read this web " \
-
"application's log file and/or the web server's log file to find out what " \
-
"went wrong."]]
-
-
1
def initialize(app, exceptions_app)
-
1
@app = app
-
1
@exceptions_app = exceptions_app
-
end
-
-
1
def call(env)
-
@app.call(env)
-
rescue Exception => exception
-
if env['action_dispatch.show_exceptions'] == false
-
raise exception
-
else
-
render_exception(env, exception)
-
end
-
end
-
-
1
private
-
-
1
def render_exception(env, exception)
-
wrapper = ExceptionWrapper.new(env, exception)
-
status = wrapper.status_code
-
env["action_dispatch.exception"] = wrapper.exception
-
env["PATH_INFO"] = "/#{status}"
-
response = @exceptions_app.call(env)
-
response[1]['X-Cascade'] == 'pass' ? pass_response(status) : response
-
rescue Exception => failsafe_error
-
$stderr.puts "Error during failsafe response: #{failsafe_error}\n #{failsafe_error.backtrace * "\n "}"
-
FAILSAFE_RESPONSE
-
end
-
-
1
def pass_response(status)
-
[status, {"Content-Type" => "text/html; charset=#{Response.default_charset}", "Content-Length" => "0"}, []]
-
end
-
end
-
end
-
1
require "active_support/inflector/methods"
-
1
require "active_support/dependencies"
-
-
1
module ActionDispatch
-
1
class MiddlewareStack
-
1
class Middleware
-
1
attr_reader :args, :block, :name, :classcache
-
-
1
def initialize(klass_or_name, *args, &block)
-
21
@klass = nil
-
-
21
if klass_or_name.respond_to?(:name)
-
19
@klass = klass_or_name
-
19
@name = @klass.name
-
else
-
2
@name = klass_or_name.to_s
-
end
-
-
21
@classcache = ActiveSupport::Dependencies::Reference
-
21
@args, @block = args, block
-
end
-
-
1
def klass
-
21
@klass || classcache[@name]
-
end
-
-
1
def ==(middleware)
-
23
case middleware
-
when Middleware
-
klass == middleware.klass
-
when Class
-
klass == middleware
-
else
-
23
normalize(@name) == normalize(middleware)
-
end
-
end
-
-
1
def inspect
-
klass.to_s
-
end
-
-
1
def build(app)
-
21
klass.new(app, *args, &block)
-
end
-
-
1
private
-
-
1
def normalize(object)
-
46
object.to_s.strip.sub(/^::/, '')
-
end
-
end
-
-
1
include Enumerable
-
-
1
attr_accessor :middlewares
-
-
1
def initialize(*args)
-
2
@middlewares = []
-
2
yield(self) if block_given?
-
end
-
-
1
def each
-
@middlewares.each { |x| yield x }
-
end
-
-
1
def size
-
middlewares.size
-
end
-
-
1
def last
-
middlewares.last
-
end
-
-
1
def [](i)
-
middlewares[i]
-
end
-
-
1
def unshift(*args, &block)
-
middleware = self.class::Middleware.new(*args, &block)
-
middlewares.unshift(middleware)
-
end
-
-
1
def initialize_copy(other)
-
3
self.middlewares = other.middlewares.dup
-
end
-
-
1
def insert(index, *args, &block)
-
3
index = assert_index(index, :before)
-
3
middleware = self.class::Middleware.new(*args, &block)
-
3
middlewares.insert(index, middleware)
-
end
-
-
1
alias_method :insert_before, :insert
-
-
1
def insert_after(index, *args, &block)
-
2
index = assert_index(index, :after)
-
2
insert(index + 1, *args, &block)
-
end
-
-
1
def swap(target, *args, &block)
-
index = assert_index(target, :before)
-
insert(index, *args, &block)
-
middlewares.delete_at(index + 1)
-
end
-
-
1
def delete(target)
-
middlewares.delete target
-
end
-
-
1
def use(*args, &block)
-
18
middleware = self.class::Middleware.new(*args, &block)
-
18
middlewares.push(middleware)
-
end
-
-
1
def build(app = nil, &block)
-
1
app ||= block
-
1
raise "MiddlewareStack#build requires an app" unless app
-
22
middlewares.freeze.reverse.inject(app) { |a, e| e.build(a) }
-
end
-
-
1
protected
-
-
1
def assert_index(index, where)
-
5
i = index.is_a?(Integer) ? index : middlewares.index(index)
-
5
raise "No such middleware to insert #{where}: #{index.inspect}" unless i
-
5
i
-
end
-
end
-
end
-
1
require 'rack/utils'
-
1
require 'active_support/core_ext/uri'
-
-
1
module ActionDispatch
-
1
class FileHandler
-
1
def initialize(root, cache_control)
-
1
@root = root.chomp('/')
-
1
@compiled_root = /^#{Regexp.escape(root)}/
-
1
headers = cache_control && { 'Cache-Control' => cache_control }
-
1
@file_server = ::Rack::File.new(@root, headers)
-
end
-
-
1
def match?(path)
-
path = unescape_path(path)
-
return false unless path.valid_encoding?
-
-
full_path = path.empty? ? @root : File.join(@root, escape_glob_chars(path))
-
paths = "#{full_path}#{ext}"
-
-
matches = Dir[paths]
-
match = matches.detect { |m| File.file?(m) }
-
if match
-
match.sub!(@compiled_root, '')
-
::Rack::Utils.escape(match)
-
end
-
end
-
-
1
def call(env)
-
@file_server.call(env)
-
end
-
-
1
def ext
-
@ext ||= begin
-
ext = ::ActionController::Base.default_static_extension
-
"{,#{ext},/index#{ext}}"
-
end
-
end
-
-
1
def unescape_path(path)
-
URI.parser.unescape(path)
-
end
-
-
1
def escape_glob_chars(path)
-
path.gsub(/[*?{}\[\]]/, "\\\\\\&")
-
end
-
end
-
-
1
class Static
-
1
def initialize(app, path, cache_control=nil)
-
1
@app = app
-
1
@file_handler = FileHandler.new(path, cache_control)
-
end
-
-
1
def call(env)
-
case env['REQUEST_METHOD']
-
when 'GET', 'HEAD'
-
path = env['PATH_INFO'].chomp('/')
-
if match = @file_handler.match?(path)
-
env["PATH_INFO"] = match
-
return @file_handler.call(env)
-
end
-
end
-
-
@app.call(env)
-
end
-
end
-
end
-
1
require "action_dispatch"
-
-
1
module ActionDispatch
-
1
class Railtie < Rails::Railtie # :nodoc:
-
1
config.action_dispatch = ActiveSupport::OrderedOptions.new
-
1
config.action_dispatch.x_sendfile_header = nil
-
1
config.action_dispatch.ip_spoofing_check = true
-
1
config.action_dispatch.show_exceptions = true
-
1
config.action_dispatch.tld_length = 1
-
1
config.action_dispatch.ignore_accept_header = false
-
1
config.action_dispatch.rescue_templates = { }
-
1
config.action_dispatch.rescue_responses = { }
-
1
config.action_dispatch.default_charset = nil
-
1
config.action_dispatch.rack_cache = false
-
1
config.action_dispatch.http_auth_salt = 'http authentication'
-
1
config.action_dispatch.signed_cookie_salt = 'signed cookie'
-
1
config.action_dispatch.encrypted_cookie_salt = 'encrypted cookie'
-
1
config.action_dispatch.encrypted_signed_cookie_salt = 'signed encrypted cookie'
-
1
config.action_dispatch.perform_deep_munge = true
-
-
1
config.action_dispatch.default_headers = {
-
'X-Frame-Options' => 'SAMEORIGIN',
-
'X-XSS-Protection' => '1; mode=block',
-
'X-Content-Type-Options' => 'nosniff'
-
}
-
-
1
config.eager_load_namespaces << ActionDispatch
-
-
1
initializer "action_dispatch.configure" do |app|
-
1
ActionDispatch::Http::URL.tld_length = app.config.action_dispatch.tld_length
-
1
ActionDispatch::Request.ignore_accept_header = app.config.action_dispatch.ignore_accept_header
-
1
ActionDispatch::Request::Utils.perform_deep_munge = app.config.action_dispatch.perform_deep_munge
-
1
ActionDispatch::Response.default_charset = app.config.action_dispatch.default_charset || app.config.encoding
-
1
ActionDispatch::Response.default_headers = app.config.action_dispatch.default_headers
-
-
1
ActionDispatch::ExceptionWrapper.rescue_responses.merge!(config.action_dispatch.rescue_responses)
-
1
ActionDispatch::ExceptionWrapper.rescue_templates.merge!(config.action_dispatch.rescue_templates)
-
-
1
config.action_dispatch.always_write_cookie = Rails.env.development? if config.action_dispatch.always_write_cookie.nil?
-
1
ActionDispatch::Cookies::CookieJar.always_write_cookie = config.action_dispatch.always_write_cookie
-
-
1
ActionDispatch.test_app = app
-
end
-
end
-
end
-
1
require 'rack/session/abstract/id'
-
-
1
module ActionDispatch
-
1
class Request < Rack::Request
-
# Session is responsible for lazily loading the session from store.
-
1
class Session # :nodoc:
-
1
ENV_SESSION_KEY = Rack::Session::Abstract::ENV_SESSION_KEY # :nodoc:
-
1
ENV_SESSION_OPTIONS_KEY = Rack::Session::Abstract::ENV_SESSION_OPTIONS_KEY # :nodoc:
-
-
# Singleton object used to determine if an optional param wasn't specified
-
1
Unspecified = Object.new
-
-
1
def self.create(store, env, default_options)
-
session_was = find env
-
session = Request::Session.new(store, env)
-
session.merge! session_was if session_was
-
-
set(env, session)
-
Options.set(env, Request::Session::Options.new(store, env, default_options))
-
session
-
end
-
-
1
def self.find(env)
-
env[ENV_SESSION_KEY]
-
end
-
-
1
def self.set(env, session)
-
env[ENV_SESSION_KEY] = session
-
end
-
-
1
class Options #:nodoc:
-
1
def self.set(env, options)
-
env[ENV_SESSION_OPTIONS_KEY] = options
-
end
-
-
1
def self.find(env)
-
env[ENV_SESSION_OPTIONS_KEY]
-
end
-
-
1
def initialize(by, env, default_options)
-
@by = by
-
@env = env
-
@delegate = default_options.dup
-
end
-
-
1
def [](key)
-
if key == :id
-
@delegate.fetch(key) {
-
@delegate[:id] = @by.send(:extract_session_id, @env)
-
}
-
else
-
@delegate[key]
-
end
-
end
-
-
1
def []=(k,v); @delegate[k] = v; end
-
1
def to_hash; @delegate.dup; end
-
1
def values_at(*args); @delegate.values_at(*args); end
-
end
-
-
1
def initialize(by, env)
-
@by = by
-
@env = env
-
@delegate = {}
-
@loaded = false
-
@exists = nil # we haven't checked yet
-
end
-
-
1
def id
-
options[:id]
-
end
-
-
1
def options
-
Options.find @env
-
end
-
-
1
def destroy
-
clear
-
options = self.options || {}
-
new_sid = @by.send(:destroy_session, @env, options[:id], options)
-
options[:id] = new_sid # Reset session id with a new value or nil
-
-
# Load the new sid to be written with the response
-
@loaded = false
-
load_for_write!
-
end
-
-
1
def [](key)
-
load_for_read!
-
@delegate[key.to_s]
-
end
-
-
1
def has_key?(key)
-
load_for_read!
-
@delegate.key?(key.to_s)
-
end
-
1
alias :key? :has_key?
-
1
alias :include? :has_key?
-
-
1
def keys
-
@delegate.keys
-
end
-
-
1
def values
-
@delegate.values
-
end
-
-
1
def []=(key, value)
-
load_for_write!
-
@delegate[key.to_s] = value
-
end
-
-
1
def clear
-
load_for_write!
-
@delegate.clear
-
end
-
-
1
def to_hash
-
load_for_read!
-
@delegate.dup.delete_if { |_,v| v.nil? }
-
end
-
-
1
def update(hash)
-
load_for_write!
-
@delegate.update stringify_keys(hash)
-
end
-
-
1
def delete(key)
-
load_for_write!
-
@delegate.delete key.to_s
-
end
-
-
1
def fetch(key, default=Unspecified, &block)
-
load_for_read!
-
if default == Unspecified
-
@delegate.fetch(key.to_s, &block)
-
else
-
@delegate.fetch(key.to_s, default, &block)
-
end
-
end
-
-
1
def inspect
-
if loaded?
-
super
-
else
-
"#<#{self.class}:0x#{(object_id << 1).to_s(16)} not yet loaded>"
-
end
-
end
-
-
1
def exists?
-
return @exists unless @exists.nil?
-
@exists = @by.send(:session_exists?, @env)
-
end
-
-
1
def loaded?
-
@loaded
-
end
-
-
1
def empty?
-
load_for_read!
-
@delegate.empty?
-
end
-
-
1
def merge!(other)
-
load_for_write!
-
@delegate.merge!(other)
-
end
-
-
1
private
-
-
1
def load_for_read!
-
load! if !loaded? && exists?
-
end
-
-
1
def load_for_write!
-
load! unless loaded?
-
end
-
-
1
def load!
-
id, session = @by.load_session @env
-
options[:id] = id
-
@delegate.replace(stringify_keys(session))
-
@loaded = true
-
end
-
-
1
def stringify_keys(other)
-
other.each_with_object({}) { |(key, value), hash|
-
hash[key.to_s] = value
-
}
-
end
-
end
-
end
-
end
-
1
module ActionDispatch
-
1
class Request < Rack::Request
-
1
class Utils # :nodoc:
-
-
1
mattr_accessor :perform_deep_munge
-
1
self.perform_deep_munge = true
-
-
1
class << self
-
# Remove nils from the params hash
-
1
def deep_munge(hash, keys = [])
-
return hash unless perform_deep_munge
-
-
hash.each do |k, v|
-
keys << k
-
case v
-
when Array
-
v.grep(Hash) { |x| deep_munge(x, keys) }
-
v.compact!
-
if v.empty?
-
hash[k] = nil
-
ActiveSupport::Notifications.instrument("deep_munge.action_controller", keys: keys)
-
end
-
when Hash
-
deep_munge(v, keys)
-
end
-
keys.pop
-
end
-
-
hash
-
end
-
end
-
end
-
end
-
end
-
-
# encoding: UTF-8
-
1
require 'active_support/core_ext/object/to_param'
-
1
require 'active_support/core_ext/regexp'
-
-
1
module ActionDispatch
-
# The routing module provides URL rewriting in native Ruby. It's a way to
-
# redirect incoming requests to controllers and actions. This replaces
-
# mod_rewrite rules. Best of all, Rails' \Routing works with any web server.
-
# Routes are defined in <tt>config/routes.rb</tt>.
-
#
-
# Think of creating routes as drawing a map for your requests. The map tells
-
# them where to go based on some predefined pattern:
-
#
-
# AppName::Application.routes.draw do
-
# Pattern 1 tells some request to go to one place
-
# Pattern 2 tell them to go to another
-
# ...
-
# end
-
#
-
# The following symbols are special:
-
#
-
# :controller maps to your controller name
-
# :action maps to an action with your controllers
-
#
-
# Other names simply map to a parameter as in the case of <tt>:id</tt>.
-
#
-
# == Resources
-
#
-
# Resource routing allows you to quickly declare all of the common routes
-
# for a given resourceful controller. Instead of declaring separate routes
-
# for your +index+, +show+, +new+, +edit+, +create+, +update+ and +destroy+
-
# actions, a resourceful route declares them in a single line of code:
-
#
-
# resources :photos
-
#
-
# Sometimes, you have a resource that clients always look up without
-
# referencing an ID. A common example, /profile always shows the profile of
-
# the currently logged in user. In this case, you can use a singular resource
-
# to map /profile (rather than /profile/:id) to the show action.
-
#
-
# resource :profile
-
#
-
# It's common to have resources that are logically children of other
-
# resources:
-
#
-
# resources :magazines do
-
# resources :ads
-
# end
-
#
-
# You may wish to organize groups of controllers under a namespace. Most
-
# commonly, you might group a number of administrative controllers under
-
# an +admin+ namespace. You would place these controllers under the
-
# <tt>app/controllers/admin</tt> directory, and you can group them together
-
# in your router:
-
#
-
# namespace "admin" do
-
# resources :posts, :comments
-
# end
-
#
-
# Alternately, you can add prefixes to your path without using a separate
-
# directory by using +scope+. +scope+ takes additional options which
-
# apply to all enclosed routes.
-
#
-
# scope path: "/cpanel", as: 'admin' do
-
# resources :posts, :comments
-
# end
-
#
-
# For more, see <tt>Routing::Mapper::Resources#resources</tt>,
-
# <tt>Routing::Mapper::Scoping#namespace</tt>, and
-
# <tt>Routing::Mapper::Scoping#scope</tt>.
-
#
-
# == Non-resourceful routes
-
#
-
# For routes that don't fit the <tt>resources</tt> mold, you can use the HTTP helper
-
# methods <tt>get</tt>, <tt>post</tt>, <tt>patch</tt>, <tt>put</tt> and <tt>delete</tt>.
-
#
-
# get 'post/:id' => 'posts#show'
-
# post 'post/:id' => 'posts#create_comment'
-
#
-
# If your route needs to respond to more than one HTTP method (or all methods) then using the
-
# <tt>:via</tt> option on <tt>match</tt> is preferable.
-
#
-
# match 'post/:id' => 'posts#show', via: [:get, :post]
-
#
-
# Now, if you POST to <tt>/posts/:id</tt>, it will route to the <tt>create_comment</tt> action. A GET on the same
-
# URL will route to the <tt>show</tt> action.
-
#
-
# == Named routes
-
#
-
# Routes can be named by passing an <tt>:as</tt> option,
-
# allowing for easy reference within your source as +name_of_route_url+
-
# for the full URL and +name_of_route_path+ for the URI path.
-
#
-
# Example:
-
#
-
# # In routes.rb
-
# get '/login' => 'accounts#login', as: 'login'
-
#
-
# # With render, redirect_to, tests, etc.
-
# redirect_to login_url
-
#
-
# Arguments can be passed as well.
-
#
-
# redirect_to show_item_path(id: 25)
-
#
-
# Use <tt>root</tt> as a shorthand to name a route for the root path "/".
-
#
-
# # In routes.rb
-
# root to: 'blogs#index'
-
#
-
# # would recognize http://www.example.com/ as
-
# params = { controller: 'blogs', action: 'index' }
-
#
-
# # and provide these named routes
-
# root_url # => 'http://www.example.com/'
-
# root_path # => '/'
-
#
-
# Note: when using +controller+, the route is simply named after the
-
# method you call on the block parameter rather than map.
-
#
-
# # In routes.rb
-
# controller :blog do
-
# get 'blog/show' => :list
-
# get 'blog/delete' => :delete
-
# get 'blog/edit/:id' => :edit
-
# end
-
#
-
# # provides named routes for show, delete, and edit
-
# link_to @article.title, show_path(id: @article.id)
-
#
-
# == Pretty URLs
-
#
-
# Routes can generate pretty URLs. For example:
-
#
-
# get '/articles/:year/:month/:day' => 'articles#find_by_id', constraints: {
-
# year: /\d{4}/,
-
# month: /\d{1,2}/,
-
# day: /\d{1,2}/
-
# }
-
#
-
# Using the route above, the URL "http://localhost:3000/articles/2005/11/06"
-
# maps to
-
#
-
# params = {year: '2005', month: '11', day: '06'}
-
#
-
# == Regular Expressions and parameters
-
# You can specify a regular expression to define a format for a parameter.
-
#
-
# controller 'geocode' do
-
# get 'geocode/:postalcode' => :show, constraints: {
-
# postalcode: /\d{5}(-\d{4})?/
-
# }
-
#
-
# Constraints can include the 'ignorecase' and 'extended syntax' regular
-
# expression modifiers:
-
#
-
# controller 'geocode' do
-
# get 'geocode/:postalcode' => :show, constraints: {
-
# postalcode: /hx\d\d\s\d[a-z]{2}/i
-
# }
-
# end
-
#
-
# controller 'geocode' do
-
# get 'geocode/:postalcode' => :show, constraints: {
-
# postalcode: /# Postcode format
-
# \d{5} #Prefix
-
# (-\d{4})? #Suffix
-
# /x
-
# }
-
# end
-
#
-
# Using the multiline modifier will raise an +ArgumentError+.
-
# Encoding regular expression modifiers are silently ignored. The
-
# match will always use the default encoding or ASCII.
-
#
-
# == External redirects
-
#
-
# You can redirect any path to another path using the redirect helper in your router:
-
#
-
# get "/stories" => redirect("/posts")
-
#
-
# == Unicode character routes
-
#
-
# You can specify unicode character routes in your router:
-
#
-
# get "こんにちは" => "welcome#index"
-
#
-
# == Routing to Rack Applications
-
#
-
# Instead of a String, like <tt>posts#index</tt>, which corresponds to the
-
# index action in the PostsController, you can specify any Rack application
-
# as the endpoint for a matcher:
-
#
-
# get "/application.js" => Sprockets
-
#
-
# == Reloading routes
-
#
-
# You can reload routes if you feel you must:
-
#
-
# Rails.application.reload_routes!
-
#
-
# This will clear all named routes and reload routes.rb if the file has been modified from
-
# last load. To absolutely force reloading, use <tt>reload!</tt>.
-
#
-
# == Testing Routes
-
#
-
# The two main methods for testing your routes:
-
#
-
# === +assert_routing+
-
#
-
# def test_movie_route_properly_splits
-
# opts = {controller: "plugin", action: "checkout", id: "2"}
-
# assert_routing "plugin/checkout/2", opts
-
# end
-
#
-
# +assert_routing+ lets you test whether or not the route properly resolves into options.
-
#
-
# === +assert_recognizes+
-
#
-
# def test_route_has_options
-
# opts = {controller: "plugin", action: "show", id: "12"}
-
# assert_recognizes opts, "/plugins/show/12"
-
# end
-
#
-
# Note the subtle difference between the two: +assert_routing+ tests that
-
# a URL fits options while +assert_recognizes+ tests that a URL
-
# breaks into parameters properly.
-
#
-
# In tests you can simply pass the URL or named route to +get+ or +post+.
-
#
-
# def send_to_jail
-
# get '/jail'
-
# assert_response :success
-
# assert_template "jail/front"
-
# end
-
#
-
# def goes_to_login
-
# get login_url
-
# #...
-
# end
-
#
-
# == View a list of all your routes
-
#
-
# rake routes
-
#
-
# Target specific controllers by prefixing the command with <tt>CONTROLLER=x</tt>.
-
#
-
1
module Routing
-
1
extend ActiveSupport::Autoload
-
-
1
autoload :Mapper
-
1
autoload :RouteSet
-
1
autoload :RoutesProxy
-
1
autoload :UrlFor
-
1
autoload :PolymorphicRoutes
-
-
1
SEPARATORS = %w( / . ? ) #:nodoc:
-
1
HTTP_METHODS = [:get, :head, :post, :patch, :put, :delete, :options] #:nodoc:
-
end
-
end
-
1
require 'delegate'
-
1
require 'active_support/core_ext/string/strip'
-
-
1
module ActionDispatch
-
1
module Routing
-
1
class RouteWrapper < SimpleDelegator
-
1
def endpoint
-
rack_app ? rack_app.inspect : "#{controller}##{action}"
-
end
-
-
1
def constraints
-
requirements.except(:controller, :action)
-
end
-
-
1
def rack_app(app = self.app)
-
@rack_app ||= begin
-
class_name = app.class.name.to_s
-
if class_name == "ActionDispatch::Routing::Mapper::Constraints"
-
rack_app(app.app)
-
elsif ActionDispatch::Routing::Redirect === app || class_name !~ /^ActionDispatch::Routing/
-
app
-
end
-
end
-
end
-
-
1
def verb
-
super.source.gsub(/[$^]/, '')
-
end
-
-
1
def path
-
super.spec.to_s
-
end
-
-
1
def name
-
super.to_s
-
end
-
-
1
def regexp
-
__getobj__.path.to_regexp
-
end
-
-
1
def json_regexp
-
str = regexp.inspect.
-
sub('\\A' , '^').
-
sub('\\Z' , '$').
-
sub('\\z' , '$').
-
sub(/^\// , '').
-
sub(/\/[a-z]*$/ , '').
-
gsub(/\(\?#.+\)/ , '').
-
gsub(/\(\?-\w+:/ , '(').
-
gsub(/\s/ , '')
-
Regexp.new(str).source
-
end
-
-
1
def reqs
-
@reqs ||= begin
-
reqs = endpoint
-
reqs += " #{constraints.to_s}" unless constraints.empty?
-
reqs
-
end
-
end
-
-
1
def controller
-
requirements[:controller] || ':controller'
-
end
-
-
1
def action
-
requirements[:action] || ':action'
-
end
-
-
1
def internal?
-
controller.to_s =~ %r{\Arails/(info|mailers|welcome)} || path =~ %r{\A#{Rails.application.config.assets.prefix}\z}
-
end
-
-
1
def engine?
-
rack_app && rack_app.respond_to?(:routes)
-
end
-
end
-
-
##
-
# This class is just used for displaying route information when someone
-
# executes `rake routes` or looks at the RoutingError page.
-
# People should not use this class.
-
1
class RoutesInspector # :nodoc:
-
1
def initialize(routes)
-
@engines = {}
-
@routes = routes
-
end
-
-
1
def format(formatter, filter = nil)
-
routes_to_display = filter_routes(filter)
-
-
routes = collect_routes(routes_to_display)
-
-
if routes.none?
-
formatter.no_routes
-
return formatter.result
-
end
-
-
formatter.header routes
-
formatter.section routes
-
-
@engines.each do |name, engine_routes|
-
formatter.section_title "Routes for #{name}"
-
formatter.section engine_routes
-
end
-
-
formatter.result
-
end
-
-
1
private
-
-
1
def filter_routes(filter)
-
if filter
-
@routes.select { |route| route.defaults[:controller] == filter }
-
else
-
@routes
-
end
-
end
-
-
1
def collect_routes(routes)
-
routes.collect do |route|
-
RouteWrapper.new(route)
-
end.reject do |route|
-
route.internal?
-
end.collect do |route|
-
collect_engine_routes(route)
-
-
{ name: route.name,
-
verb: route.verb,
-
path: route.path,
-
reqs: route.reqs,
-
regexp: route.json_regexp }
-
end
-
end
-
-
1
def collect_engine_routes(route)
-
name = route.endpoint
-
return unless route.engine?
-
return if @engines[name]
-
-
routes = route.rack_app.routes
-
if routes.is_a?(ActionDispatch::Routing::RouteSet)
-
@engines[name] = collect_routes(routes.routes)
-
end
-
end
-
end
-
-
1
class ConsoleFormatter
-
1
def initialize
-
@buffer = []
-
end
-
-
1
def result
-
@buffer.join("\n")
-
end
-
-
1
def section_title(title)
-
@buffer << "\n#{title}:"
-
end
-
-
1
def section(routes)
-
@buffer << draw_section(routes)
-
end
-
-
1
def header(routes)
-
@buffer << draw_header(routes)
-
end
-
-
1
def no_routes
-
@buffer << <<-MESSAGE.strip_heredoc
-
You don't have any routes defined!
-
-
Please add some routes in config/routes.rb.
-
-
For more information about routes, see the Rails guide: http://guides.rubyonrails.org/routing.html.
-
MESSAGE
-
end
-
-
1
private
-
1
def draw_section(routes)
-
header_lengths = ['Prefix', 'Verb', 'URI Pattern'].map(&:length)
-
name_width, verb_width, path_width = widths(routes).zip(header_lengths).map(&:max)
-
-
routes.map do |r|
-
"#{r[:name].rjust(name_width)} #{r[:verb].ljust(verb_width)} #{r[:path].ljust(path_width)} #{r[:reqs]}"
-
end
-
end
-
-
1
def draw_header(routes)
-
name_width, verb_width, path_width = widths(routes)
-
-
"#{"Prefix".rjust(name_width)} #{"Verb".ljust(verb_width)} #{"URI Pattern".ljust(path_width)} Controller#Action"
-
end
-
-
1
def widths(routes)
-
[routes.map { |r| r[:name].length }.max || 0,
-
routes.map { |r| r[:verb].length }.max || 0,
-
routes.map { |r| r[:path].length }.max || 0]
-
end
-
end
-
-
1
class HtmlTableFormatter
-
1
def initialize(view)
-
@view = view
-
@buffer = []
-
end
-
-
1
def section_title(title)
-
@buffer << %(<tr><th colspan="4">#{title}</th></tr>)
-
end
-
-
1
def section(routes)
-
@buffer << @view.render(partial: "routes/route", collection: routes)
-
end
-
-
# the header is part of the HTML page, so we don't construct it here.
-
1
def header(routes)
-
end
-
-
1
def no_routes
-
@buffer << <<-MESSAGE.strip_heredoc
-
<p>You don't have any routes defined!</p>
-
<ul>
-
<li>Please add some routes in <tt>config/routes.rb</tt>.</li>
-
<li>
-
For more information about routes, please see the Rails guide
-
<a href="http://guides.rubyonrails.org/routing.html">Rails Routing from the Outside In</a>.
-
</li>
-
</ul>
-
MESSAGE
-
end
-
-
1
def result
-
@view.raw @view.render(layout: "routes/table") {
-
@view.raw @buffer.join("\n")
-
}
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/hash/reverse_merge'
-
1
require 'active_support/core_ext/hash/slice'
-
1
require 'active_support/core_ext/enumerable'
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'active_support/core_ext/module/remove_method'
-
1
require 'active_support/inflector'
-
1
require 'action_dispatch/routing/redirection'
-
-
1
module ActionDispatch
-
1
module Routing
-
1
class Mapper
-
1
URL_OPTIONS = [:protocol, :subdomain, :domain, :host, :port]
-
1
SCOPE_OPTIONS = [:path, :shallow_path, :as, :shallow_prefix, :module,
-
:controller, :action, :path_names, :constraints,
-
:shallow, :blocks, :defaults, :options]
-
-
1
class Constraints #:nodoc:
-
1
def self.new(app, constraints, request = Rack::Request)
-
73
if constraints.any?
-
15
super(app, constraints, request)
-
else
-
58
app
-
end
-
end
-
-
1
attr_reader :app, :constraints
-
-
1
def initialize(app, constraints, request)
-
15
@app, @constraints, @request = app, constraints, request
-
end
-
-
1
def matches?(env)
-
req = @request.new(env)
-
-
@constraints.all? do |constraint|
-
(constraint.respond_to?(:matches?) && constraint.matches?(req)) ||
-
(constraint.respond_to?(:call) && constraint.call(*constraint_args(constraint, req)))
-
end
-
ensure
-
req.reset_parameters
-
end
-
-
1
def call(env)
-
matches?(env) ? @app.call(env) : [ 404, {'X-Cascade' => 'pass'}, [] ]
-
end
-
-
1
private
-
1
def constraint_args(constraint, request)
-
constraint.arity == 1 ? [request] : [request.symbolized_path_parameters, request]
-
end
-
end
-
-
1
class Mapping #:nodoc:
-
1
IGNORE_OPTIONS = [:to, :as, :via, :on, :constraints, :defaults, :only, :except, :anchor, :shallow, :shallow_path, :shallow_prefix, :format]
-
1
ANCHOR_CHARACTERS_REGEX = %r{\A(\\A|\^)|(\\Z|\\z|\$)\Z}
-
1
WILDCARD_PATH = %r{\*([^/\)]+)\)?$}
-
-
1
attr_reader :scope, :path, :options, :requirements, :conditions, :defaults
-
-
1
def initialize(set, scope, path, options)
-
73
@set, @scope, @path, @options = set, scope, path, options
-
73
@requirements, @conditions, @defaults = {}, {}, {}
-
-
73
normalize_options!
-
73
normalize_path!
-
73
normalize_requirements!
-
73
normalize_conditions!
-
73
normalize_defaults!
-
end
-
-
1
def to_route
-
73
[ app, conditions, requirements, defaults, options[:as], options[:anchor] ]
-
end
-
-
1
private
-
-
1
def normalize_path!
-
73
raise ArgumentError, "path is required" if @path.blank?
-
73
@path = Mapper.normalize_path(@path)
-
-
73
if required_format?
-
@path = "#{@path}.:format"
-
73
elsif optional_format?
-
71
@path = "#{@path}(.:format)"
-
end
-
end
-
-
1
def required_format?
-
73
options[:format] == true
-
end
-
-
1
def optional_format?
-
73
options[:format] != false && !path.include?(':format') && !path.end_with?('/')
-
end
-
-
1
def normalize_options!
-
73
@options.reverse_merge!(scope[:options]) if scope[:options]
-
73
path_without_format = path.sub(/\(\.:format\)$/, '')
-
-
# Add a constraint for wildcard route to make it non-greedy and match the
-
# optional format part of the route by default
-
73
if path_without_format.match(WILDCARD_PATH) && @options[:format] != false
-
@options[$1.to_sym] ||= /.+?/
-
end
-
-
73
if path_without_format.match(':controller')
-
raise ArgumentError, ":controller segment is not allowed within a namespace block" if scope[:module]
-
-
# Add a default constraint for :controller path segments that matches namespaced
-
# controllers with default routes like :controller/:action/:id(.:format), e.g:
-
# GET /admin/products/show/1
-
# => { controller: 'admin/products', action: 'show', id: '1' }
-
@options[:controller] ||= /.+?/
-
end
-
-
73
@options.merge!(default_controller_and_action)
-
end
-
-
1
def normalize_requirements!
-
73
constraints.each do |key, requirement|
-
next unless segment_keys.include?(key) || key == :controller
-
verify_regexp_requirement(requirement) if requirement.is_a?(Regexp)
-
@requirements[key] = requirement
-
end
-
-
73
if options[:format] == true
-
@requirements[:format] ||= /.+/
-
73
elsif Regexp === options[:format]
-
@requirements[:format] = options[:format]
-
73
elsif String === options[:format]
-
@requirements[:format] = Regexp.compile(options[:format])
-
end
-
end
-
-
1
def verify_regexp_requirement(requirement)
-
if requirement.source =~ ANCHOR_CHARACTERS_REGEX
-
raise ArgumentError, "Regexp anchor characters are not allowed in routing requirements: #{requirement.inspect}"
-
end
-
-
if requirement.multiline?
-
raise ArgumentError, "Regexp multiline option is not allowed in routing requirements: #{requirement.inspect}"
-
end
-
end
-
-
1
def normalize_defaults!
-
73
@defaults.merge!(scope[:defaults]) if scope[:defaults]
-
73
@defaults.merge!(options[:defaults]) if options[:defaults]
-
-
73
options.each do |key, default|
-
367
unless Regexp === default || IGNORE_OPTIONS.include?(key)
-
144
@defaults[key] = default
-
end
-
end
-
-
73
if options[:constraints].is_a?(Hash)
-
options[:constraints].each do |key, default|
-
if URL_OPTIONS.include?(key) && (String === default || Fixnum === default)
-
@defaults[key] ||= default
-
end
-
end
-
end
-
-
73
if Regexp === options[:format]
-
@defaults[:format] = nil
-
73
elsif String === options[:format]
-
@defaults[:format] = options[:format]
-
end
-
end
-
-
1
def normalize_conditions!
-
73
@conditions[:path_info] = path
-
-
73
constraints.each do |key, condition|
-
unless segment_keys.include?(key) || key == :controller
-
@conditions[key] = condition
-
end
-
end
-
-
73
required_defaults = []
-
73
options.each do |key, required_default|
-
368
unless segment_keys.include?(key) || IGNORE_OPTIONS.include?(key) || Regexp === required_default
-
144
required_defaults << key
-
end
-
end
-
73
@conditions[:required_defaults] = required_defaults
-
-
73
via_all = options.delete(:via) if options[:via] == :all
-
-
73
if !via_all && options[:via].blank?
-
msg = "You should not use the `match` method in your router without specifying an HTTP method.\n" \
-
"If you want to expose your action to both GET and POST, add `via: [:get, :post]` option.\n" \
-
"If you want to expose your action to GET, use `get` in the router:\n" \
-
" Instead of: match \"controller#action\"\n" \
-
" Do: get \"controller#action\""
-
raise msg
-
end
-
-
73
if via = options[:via]
-
144
@conditions[:request_method] = Array(via).map { |m| m.to_s.dasherize.upcase }
-
end
-
end
-
-
1
def app
-
73
Constraints.new(endpoint, blocks, @set.request_class)
-
end
-
-
1
def default_controller_and_action
-
73
if to.respond_to?(:call)
-
1
{ }
-
else
-
72
if to.is_a?(String)
-
4
controller, action = to.split('#')
-
elsif to.is_a?(Symbol)
-
action = to.to_s
-
end
-
-
72
controller ||= default_controller
-
72
action ||= default_action
-
-
72
if @scope[:module] && !controller.is_a?(Regexp)
-
if controller =~ %r{\A/}
-
controller = controller[1..-1]
-
else
-
controller = [@scope[:module], controller].compact.join("/").presence
-
end
-
end
-
-
72
if controller.is_a?(String) && controller =~ %r{\A/}
-
raise ArgumentError, "controller name should not start with a slash"
-
end
-
-
72
controller = controller.to_s unless controller.is_a?(Regexp)
-
72
action = action.to_s unless action.is_a?(Regexp)
-
-
72
if controller.blank? && segment_keys.exclude?(:controller)
-
message = "Missing :controller key on routes definition, please check your routes."
-
raise ArgumentError, message
-
end
-
-
72
if action.blank? && segment_keys.exclude?(:action)
-
message = "Missing :action key on routes definition, please check your routes."
-
raise ArgumentError, message
-
end
-
-
72
if controller.is_a?(String) && controller !~ /\A[a-z_0-9\/]*\z/
-
message = "'#{controller}' is not a supported controller name. This can lead to potential routing problems."
-
message << " See http://guides.rubyonrails.org/routing.html#specifying-a-controller-to-use"
-
raise ArgumentError, message
-
end
-
-
72
hash = {}
-
72
hash[:controller] = controller unless controller.blank?
-
72
hash[:action] = action unless action.blank?
-
72
hash
-
end
-
end
-
-
1
def blocks
-
73
if options[:constraints].present? && !options[:constraints].is_a?(Hash)
-
[options[:constraints]]
-
else
-
73
scope[:blocks] || []
-
end
-
end
-
-
1
def constraints
-
@constraints ||= {}.tap do |constraints|
-
73
constraints.merge!(scope[:constraints]) if scope[:constraints]
-
-
73
options.except(*IGNORE_OPTIONS).each do |key, option|
-
144
constraints[key] = option if Regexp === option
-
end
-
-
73
constraints.merge!(options[:constraints]) if options[:constraints].is_a?(Hash)
-
146
end
-
end
-
-
1
def segment_keys
-
469
@segment_keys ||= path_pattern.names.map{ |s| s.to_sym }
-
end
-
-
1
def path_pattern
-
73
Journey::Path::Pattern.new(strexp)
-
end
-
-
1
def strexp
-
73
Journey::Router::Strexp.compile(path, requirements, SEPARATORS)
-
end
-
-
1
def endpoint
-
73
to.respond_to?(:call) ? to : dispatcher
-
end
-
-
1
def dispatcher
-
72
Routing::RouteSet::Dispatcher.new(:defaults => defaults)
-
end
-
-
1
def to
-
291
options[:to]
-
end
-
-
1
def default_controller
-
68
options[:controller] || scope[:controller]
-
end
-
-
1
def default_action
-
68
options[:action] || scope[:action]
-
end
-
end
-
-
# Invokes Journey::Router::Utils.normalize_path and ensure that
-
# (:locale) becomes (/:locale) instead of /(:locale). Except
-
# for root cases, where the latter is the correct one.
-
1
def self.normalize_path(path)
-
160
path = Journey::Router::Utils.normalize_path(path)
-
160
path.gsub!(%r{/(\(+)/?}, '\1/') unless path =~ %r{^/\(+[^)]+\)$}
-
160
path
-
end
-
-
1
def self.normalize_name(name)
-
13
normalize_path(name)[1..-1].tr("/", "_")
-
end
-
-
1
module Base
-
# You can specify what Rails should route "/" to with the root method:
-
#
-
# root to: 'pages#main'
-
#
-
# For options, see +match+, as +root+ uses it internally.
-
#
-
# You can also pass a string which will expand
-
#
-
# root 'pages#main'
-
#
-
# You should put the root route at the top of <tt>config/routes.rb</tt>,
-
# because this means it will be matched first. As this is the most popular route
-
# of most Rails applications, this is beneficial.
-
1
def root(options = {})
-
1
match '/', { :as => :root, :via => :get }.merge!(options)
-
end
-
-
# Matches a url pattern to one or more routes. Any symbols in a pattern
-
# are interpreted as url query parameters and thus available as +params+
-
# in an action:
-
#
-
# # sets :controller, :action and :id in params
-
# match ':controller/:action/:id'
-
#
-
# Two of these symbols are special, +:controller+ maps to the controller
-
# and +:action+ to the controller's action. A pattern can also map
-
# wildcard segments (globs) to params:
-
#
-
# match 'songs/*category/:title', to: 'songs#show'
-
#
-
# # 'songs/rock/classic/stairway-to-heaven' sets
-
# # params[:category] = 'rock/classic'
-
# # params[:title] = 'stairway-to-heaven'
-
#
-
# When a pattern points to an internal route, the route's +:action+ and
-
# +:controller+ should be set in options or hash shorthand. Examples:
-
#
-
# match 'photos/:id' => 'photos#show'
-
# match 'photos/:id', to: 'photos#show'
-
# match 'photos/:id', controller: 'photos', action: 'show'
-
#
-
# A pattern can also point to a +Rack+ endpoint i.e. anything that
-
# responds to +call+:
-
#
-
# match 'photos/:id', to: lambda {|hash| [200, {}, ["Coming soon"]] }
-
# match 'photos/:id', to: PhotoRackApp
-
# # Yes, controller actions are just rack endpoints
-
# match 'photos/:id', to: PhotosController.action(:show)
-
#
-
# Because requesting various HTTP verbs with a single action has security
-
# implications, you must either specify the actions in
-
# the via options or use one of the HtttpHelpers[rdoc-ref:HttpHelpers]
-
# instead +match+
-
#
-
# === Options
-
#
-
# Any options not seen here are passed on as params with the url.
-
#
-
# [:controller]
-
# The route's controller.
-
#
-
# [:action]
-
# The route's action.
-
#
-
# [:path]
-
# The path prefix for the routes.
-
#
-
# [:module]
-
# The namespace for :controller.
-
#
-
# match 'path', to: 'c#a', module: 'sekret', controller: 'posts'
-
# # => Sekret::PostsController
-
#
-
# See <tt>Scoping#namespace</tt> for its scope equivalent.
-
#
-
# [:as]
-
# The name used to generate routing helpers.
-
#
-
# [:via]
-
# Allowed HTTP verb(s) for route.
-
#
-
# match 'path', to: 'c#a', via: :get
-
# match 'path', to: 'c#a', via: [:get, :post]
-
# match 'path', to: 'c#a', via: :all
-
#
-
# [:to]
-
# Points to a +Rack+ endpoint. Can be an object that responds to
-
# +call+ or a string representing a controller's action.
-
#
-
# match 'path', to: 'controller#action'
-
# match 'path', to: lambda { |env| [200, {}, ["Success!"]] }
-
# match 'path', to: RackApp
-
#
-
# [:on]
-
# Shorthand for wrapping routes in a specific RESTful context. Valid
-
# values are +:member+, +:collection+, and +:new+. Only use within
-
# <tt>resource(s)</tt> block. For example:
-
#
-
# resource :bar do
-
# match 'foo', to: 'c#a', on: :member, via: [:get, :post]
-
# end
-
#
-
# Is equivalent to:
-
#
-
# resource :bar do
-
# member do
-
# match 'foo', to: 'c#a', via: [:get, :post]
-
# end
-
# end
-
#
-
# [:constraints]
-
# Constrains parameters with a hash of regular expressions
-
# or an object that responds to <tt>matches?</tt>. In addition, constraints
-
# other than path can also be specified with any object
-
# that responds to <tt>===</tt> (eg. String, Array, Range, etc.).
-
#
-
# match 'path/:id', constraints: { id: /[A-Z]\d{5}/ }
-
#
-
# match 'json_only', constraints: { format: 'json' }
-
#
-
# class Whitelist
-
# def matches?(request) request.remote_ip == '1.2.3.4' end
-
# end
-
# match 'path', to: 'c#a', constraints: Whitelist.new
-
#
-
# See <tt>Scoping#constraints</tt> for more examples with its scope
-
# equivalent.
-
#
-
# [:defaults]
-
# Sets defaults for parameters
-
#
-
# # Sets params[:format] to 'jpg' by default
-
# match 'path', to: 'c#a', defaults: { format: 'jpg' }
-
#
-
# See <tt>Scoping#defaults</tt> for its scope equivalent.
-
#
-
# [:anchor]
-
# Boolean to anchor a <tt>match</tt> pattern. Default is true. When set to
-
# false, the pattern matches any request prefixed with the given path.
-
#
-
# # Matches any request starting with 'path'
-
# match 'path', to: 'c#a', anchor: false
-
#
-
# [:format]
-
# Allows you to specify the default value for optional +format+
-
# segment or disable it by supplying +false+.
-
1
def match(path, options=nil)
-
end
-
-
# Mount a Rack-based application to be used within the application.
-
#
-
# mount SomeRackApp, at: "some_route"
-
#
-
# Alternatively:
-
#
-
# mount(SomeRackApp => "some_route")
-
#
-
# For options, see +match+, as +mount+ uses it internally.
-
#
-
# All mounted applications come with routing helpers to access them.
-
# These are named after the class specified, so for the above example
-
# the helper is either +some_rack_app_path+ or +some_rack_app_url+.
-
# To customize this helper's name, use the +:as+ option:
-
#
-
# mount(SomeRackApp => "some_route", as: "exciting")
-
#
-
# This will generate the +exciting_path+ and +exciting_url+ helpers
-
# which can be used to navigate to this mounted app.
-
1
def mount(app, options = nil)
-
1
if options
-
path = options.delete(:at)
-
else
-
1
unless Hash === app
-
raise ArgumentError, "must be called with mount point"
-
end
-
-
1
options = app
-
2
app, path = options.find { |k, _| k.respond_to?(:call) }
-
1
options.delete(app) if app
-
end
-
-
1
raise "A rack application must be specified" unless path
-
-
1
options[:as] ||= app_name(app)
-
1
target_as = name_for_action(options[:as], path)
-
1
options[:via] ||= :all
-
-
1
match(path, options.merge(:to => app, :anchor => false, :format => false))
-
-
1
define_generate_prefix(app, target_as)
-
1
self
-
end
-
-
1
def default_url_options=(options)
-
@set.default_url_options = options
-
end
-
1
alias_method :default_url_options, :default_url_options=
-
-
1
def with_default_scope(scope, &block)
-
scope(scope) do
-
instance_exec(&block)
-
end
-
end
-
-
# Query if the following named route was already defined.
-
1
def has_named_route?(name)
-
@set.named_routes.routes[name.to_sym]
-
end
-
-
1
private
-
1
def app_name(app)
-
1
return unless app.respond_to?(:routes)
-
-
if app.respond_to?(:railtie_name)
-
app.railtie_name
-
else
-
class_name = app.class.is_a?(Class) ? app.name : app.class.name
-
ActiveSupport::Inflector.underscore(class_name).tr("/", "_")
-
end
-
end
-
-
1
def define_generate_prefix(app, name)
-
1
return unless app.respond_to?(:routes) && app.routes.respond_to?(:define_mounted_helper)
-
-
_route = @set.named_routes.routes[name.to_sym]
-
_routes = @set
-
app.routes.define_mounted_helper(name)
-
app.routes.singleton_class.class_eval do
-
redefine_method :mounted? do
-
true
-
end
-
-
redefine_method :_generate_prefix do |options|
-
prefix_options = options.slice(*_route.segment_keys)
-
# we must actually delete prefix segment keys to avoid passing them to next url_for
-
_route.segment_keys.each { |k| options.delete(k) }
-
_routes.url_helpers.send("#{name}_path", prefix_options)
-
end
-
end
-
end
-
end
-
-
1
module HttpHelpers
-
# Define a route that only recognizes HTTP GET.
-
# For supported arguments, see match[rdoc-ref:Base#match]
-
#
-
# get 'bacon', to: 'food#bacon'
-
1
def get(*args, &block)
-
32
map_method(:get, args, &block)
-
end
-
-
# Define a route that only recognizes HTTP POST.
-
# For supported arguments, see match[rdoc-ref:Base#match]
-
#
-
# post 'bacon', to: 'food#bacon'
-
1
def post(*args, &block)
-
11
map_method(:post, args, &block)
-
end
-
-
# Define a route that only recognizes HTTP PATCH.
-
# For supported arguments, see match[rdoc-ref:Base#match]
-
#
-
# patch 'bacon', to: 'food#bacon'
-
1
def patch(*args, &block)
-
9
map_method(:patch, args, &block)
-
end
-
-
# Define a route that only recognizes HTTP PUT.
-
# For supported arguments, see match[rdoc-ref:Base#match]
-
#
-
# put 'bacon', to: 'food#bacon'
-
1
def put(*args, &block)
-
10
map_method(:put, args, &block)
-
end
-
-
# Define a route that only recognizes HTTP DELETE.
-
# For supported arguments, see match[rdoc-ref:Base#match]
-
#
-
# delete 'broccoli', to: 'food#broccoli'
-
1
def delete(*args, &block)
-
8
map_method(:delete, args, &block)
-
end
-
-
1
private
-
1
def map_method(method, args, &block)
-
70
options = args.extract_options!
-
70
options[:via] = method
-
70
match(*args, options, &block)
-
70
self
-
end
-
end
-
-
# You may wish to organize groups of controllers under a namespace.
-
# Most commonly, you might group a number of administrative controllers
-
# under an +admin+ namespace. You would place these controllers under
-
# the <tt>app/controllers/admin</tt> directory, and you can group them
-
# together in your router:
-
#
-
# namespace "admin" do
-
# resources :posts, :comments
-
# end
-
#
-
# This will create a number of routes for each of the posts and comments
-
# controller. For <tt>Admin::PostsController</tt>, Rails will create:
-
#
-
# GET /admin/posts
-
# GET /admin/posts/new
-
# POST /admin/posts
-
# GET /admin/posts/1
-
# GET /admin/posts/1/edit
-
# PATCH/PUT /admin/posts/1
-
# DELETE /admin/posts/1
-
#
-
# If you want to route /posts (without the prefix /admin) to
-
# <tt>Admin::PostsController</tt>, you could use
-
#
-
# scope module: "admin" do
-
# resources :posts
-
# end
-
#
-
# or, for a single case
-
#
-
# resources :posts, module: "admin"
-
#
-
# If you want to route /admin/posts to +PostsController+
-
# (without the Admin:: module prefix), you could use
-
#
-
# scope "/admin" do
-
# resources :posts
-
# end
-
#
-
# or, for a single case
-
#
-
# resources :posts, path: "/admin/posts"
-
#
-
# In each of these cases, the named routes remain the same as if you did
-
# not use scope. In the last case, the following paths map to
-
# +PostsController+:
-
#
-
# GET /admin/posts
-
# GET /admin/posts/new
-
# POST /admin/posts
-
# GET /admin/posts/1
-
# GET /admin/posts/1/edit
-
# PATCH/PUT /admin/posts/1
-
# DELETE /admin/posts/1
-
1
module Scoping
-
# Scopes a set of routes to the given default options.
-
#
-
# Take the following route definition as an example:
-
#
-
# scope path: ":account_id", as: "account" do
-
# resources :projects
-
# end
-
#
-
# This generates helpers such as +account_projects_path+, just like +resources+ does.
-
# The difference here being that the routes generated are like /:account_id/projects,
-
# rather than /accounts/:account_id/projects.
-
#
-
# === Options
-
#
-
# Takes same options as <tt>Base#match</tt> and <tt>Resources#resources</tt>.
-
#
-
# # route /posts (without the prefix /admin) to <tt>Admin::PostsController</tt>
-
# scope module: "admin" do
-
# resources :posts
-
# end
-
#
-
# # prefix the posts resource's requests with '/admin'
-
# scope path: "/admin" do
-
# resources :posts
-
# end
-
#
-
# # prefix the routing helper name: +sekret_posts_path+ instead of +posts_path+
-
# scope as: "sekret" do
-
# resources :posts
-
# end
-
1
def scope(*args)
-
51
options = args.extract_options!.dup
-
51
recover = {}
-
-
51
options[:path] = args.flatten.join('/') if args.any?
-
51
options[:constraints] ||= {}
-
-
51
unless shallow?
-
51
options[:shallow_path] ||= options[:path] if options.key?(:path)
-
51
options[:shallow_prefix] ||= options[:as] if options.key?(:as)
-
end
-
-
51
if options[:constraints].is_a?(Hash)
-
50
defaults = options[:constraints].select do
-
|k, v| URL_OPTIONS.include?(k) && (v.is_a?(String) || v.is_a?(Fixnum))
-
end
-
-
50
(options[:defaults] ||= {}).reverse_merge!(defaults)
-
else
-
1
block, options[:constraints] = options[:constraints], {}
-
end
-
-
51
SCOPE_OPTIONS.each do |option|
-
663
if option == :blocks
-
51
value = block
-
elsif option == :options
-
51
value = options
-
else
-
561
value = options.delete(option)
-
end
-
-
663
if value
-
240
recover[option] = @scope[option]
-
240
@scope[option] = send("merge_#{option}_scope", @scope[option], value)
-
end
-
end
-
-
51
yield
-
51
self
-
ensure
-
51
@scope.merge!(recover)
-
end
-
-
# Scopes routes to a specific controller
-
#
-
# controller "food" do
-
# match "bacon", action: "bacon"
-
# end
-
1
def controller(controller, options={})
-
options[:controller] = controller
-
scope(options) { yield }
-
end
-
-
# Scopes routes to a specific namespace. For example:
-
#
-
# namespace :admin do
-
# resources :posts
-
# end
-
#
-
# This generates the following routes:
-
#
-
# admin_posts GET /admin/posts(.:format) admin/posts#index
-
# admin_posts POST /admin/posts(.:format) admin/posts#create
-
# new_admin_post GET /admin/posts/new(.:format) admin/posts#new
-
# edit_admin_post GET /admin/posts/:id/edit(.:format) admin/posts#edit
-
# admin_post GET /admin/posts/:id(.:format) admin/posts#show
-
# admin_post PATCH/PUT /admin/posts/:id(.:format) admin/posts#update
-
# admin_post DELETE /admin/posts/:id(.:format) admin/posts#destroy
-
#
-
# === Options
-
#
-
# The +:path+, +:as+, +:module+, +:shallow_path+ and +:shallow_prefix+
-
# options all default to the name of the namespace.
-
#
-
# For options, see <tt>Base#match</tt>. For +:shallow_path+ option, see
-
# <tt>Resources#resources</tt>.
-
#
-
# # accessible through /sekret/posts rather than /admin/posts
-
# namespace :admin, path: "sekret" do
-
# resources :posts
-
# end
-
#
-
# # maps to <tt>Sekret::PostsController</tt> rather than <tt>Admin::PostsController</tt>
-
# namespace :admin, module: "sekret" do
-
# resources :posts
-
# end
-
#
-
# # generates +sekret_posts_path+ rather than +admin_posts_path+
-
# namespace :admin, as: "sekret" do
-
# resources :posts
-
# end
-
1
def namespace(path, options = {})
-
path = path.to_s
-
-
defaults = {
-
module: path,
-
path: options.fetch(:path, path),
-
as: options.fetch(:as, path),
-
shallow_path: options.fetch(:path, path),
-
shallow_prefix: options.fetch(:as, path)
-
}
-
-
scope(defaults.merge!(options)) { yield }
-
end
-
-
# === Parameter Restriction
-
# Allows you to constrain the nested routes based on a set of rules.
-
# For instance, in order to change the routes to allow for a dot character in the +id+ parameter:
-
#
-
# constraints(id: /\d+\.\d+/) do
-
# resources :posts
-
# end
-
#
-
# Now routes such as +/posts/1+ will no longer be valid, but +/posts/1.1+ will be.
-
# The +id+ parameter must match the constraint passed in for this example.
-
#
-
# You may use this to also restrict other parameters:
-
#
-
# resources :posts do
-
# constraints(post_id: /\d+\.\d+/) do
-
# resources :comments
-
# end
-
# end
-
#
-
# === Restricting based on IP
-
#
-
# Routes can also be constrained to an IP or a certain range of IP addresses:
-
#
-
# constraints(ip: /192\.168\.\d+\.\d+/) do
-
# resources :posts
-
# end
-
#
-
# Any user connecting from the 192.168.* range will be able to see this resource,
-
# where as any user connecting outside of this range will be told there is no such route.
-
#
-
# === Dynamic request matching
-
#
-
# Requests to routes can be constrained based on specific criteria:
-
#
-
# constraints(lambda { |req| req.env["HTTP_USER_AGENT"] =~ /iPhone/ }) do
-
# resources :iphones
-
# end
-
#
-
# You are able to move this logic out into a class if it is too complex for routes.
-
# This class must have a +matches?+ method defined on it which either returns +true+
-
# if the user should be given access to that route, or +false+ if the user should not.
-
#
-
# class Iphone
-
# def self.matches?(request)
-
# request.env["HTTP_USER_AGENT"] =~ /iPhone/
-
# end
-
# end
-
#
-
# An expected place for this code would be +lib/constraints+.
-
#
-
# This class is then used like this:
-
#
-
# constraints(Iphone) do
-
# resources :iphones
-
# end
-
1
def constraints(constraints = {})
-
2
scope(:constraints => constraints) { yield }
-
end
-
-
# Allows you to set default parameters for a route, such as this:
-
# defaults id: 'home' do
-
# match 'scoped_pages/(:id)', to: 'pages#show'
-
# end
-
# Using this, the +:id+ parameter here will default to 'home'.
-
1
def defaults(defaults = {})
-
scope(:defaults => defaults) { yield }
-
end
-
-
1
private
-
1
def merge_path_scope(parent, child) #:nodoc:
-
37
Mapper.normalize_path("#{parent}/#{child}")
-
end
-
-
1
def merge_shallow_path_scope(parent, child) #:nodoc:
-
37
Mapper.normalize_path("#{parent}/#{child}")
-
end
-
-
1
def merge_as_scope(parent, child) #:nodoc:
-
parent ? "#{parent}_#{child}" : child
-
end
-
-
1
def merge_shallow_prefix_scope(parent, child) #:nodoc:
-
parent ? "#{parent}_#{child}" : child
-
end
-
-
1
def merge_module_scope(parent, child) #:nodoc:
-
parent ? "#{parent}/#{child}" : child
-
end
-
-
1
def merge_controller_scope(parent, child) #:nodoc:
-
12
child
-
end
-
-
1
def merge_action_scope(parent, child) #:nodoc:
-
child
-
end
-
-
1
def merge_path_names_scope(parent, child) #:nodoc:
-
1
merge_options_scope(parent, child)
-
end
-
-
1
def merge_constraints_scope(parent, child) #:nodoc:
-
51
merge_options_scope(parent, child)
-
end
-
-
1
def merge_defaults_scope(parent, child) #:nodoc:
-
50
merge_options_scope(parent, child)
-
end
-
-
1
def merge_blocks_scope(parent, child) #:nodoc:
-
1
merged = parent ? parent.dup : []
-
1
merged << child if child
-
1
merged
-
end
-
-
1
def merge_options_scope(parent, child) #:nodoc:
-
153
(parent || {}).except(*override_keys(child)).merge!(child)
-
end
-
-
1
def merge_shallow_scope(parent, child) #:nodoc:
-
child ? true : false
-
end
-
-
1
def override_keys(child) #:nodoc:
-
153
child.key?(:only) || child.key?(:except) ? [:only, :except] : []
-
end
-
end
-
-
# Resource routing allows you to quickly declare all of the common routes
-
# for a given resourceful controller. Instead of declaring separate routes
-
# for your +index+, +show+, +new+, +edit+, +create+, +update+ and +destroy+
-
# actions, a resourceful route declares them in a single line of code:
-
#
-
# resources :photos
-
#
-
# Sometimes, you have a resource that clients always look up without
-
# referencing an ID. A common example, /profile always shows the profile of
-
# the currently logged in user. In this case, you can use a singular resource
-
# to map /profile (rather than /profile/:id) to the show action.
-
#
-
# resource :profile
-
#
-
# It's common to have resources that are logically children of other
-
# resources:
-
#
-
# resources :magazines do
-
# resources :ads
-
# end
-
#
-
# You may wish to organize groups of controllers under a namespace. Most
-
# commonly, you might group a number of administrative controllers under
-
# an +admin+ namespace. You would place these controllers under the
-
# <tt>app/controllers/admin</tt> directory, and you can group them together
-
# in your router:
-
#
-
# namespace "admin" do
-
# resources :posts, :comments
-
# end
-
#
-
# By default the +:id+ parameter doesn't accept dots. If you need to
-
# use dots as part of the +:id+ parameter add a constraint which
-
# overrides this restriction, e.g:
-
#
-
# resources :articles, id: /[^\/]+/
-
#
-
# This allows any character other than a slash as part of your +:id+.
-
#
-
1
module Resources
-
# CANONICAL_ACTIONS holds all actions that does not need a prefix or
-
# a path appended since they fit properly in their scope level.
-
1
VALID_ON_OPTIONS = [:new, :collection, :member]
-
1
RESOURCE_OPTIONS = [:as, :controller, :path, :only, :except, :param, :concerns]
-
1
CANONICAL_ACTIONS = %w(index create new show update destroy)
-
1
RESOURCE_METHOD_SCOPES = [:collection, :member, :new]
-
1
RESOURCE_SCOPES = [:resource, :resources]
-
-
1
class Resource #:nodoc:
-
1
attr_reader :controller, :path, :options, :param
-
-
1
def initialize(entities, options = {})
-
12
@name = entities.to_s
-
12
@path = (options[:path] || @name).to_s
-
12
@controller = (options[:controller] || @name).to_s
-
12
@as = options[:as]
-
12
@param = (options[:param] || :id).to_sym
-
12
@options = options
-
end
-
-
1
def default_actions
-
21
[:index, :create, :new, :show, :update, :destroy, :edit]
-
end
-
-
1
def actions
-
81
if only = @options[:only]
-
60
Array(only).map(&:to_sym)
-
21
elsif except = @options[:except]
-
default_actions - Array(except).map(&:to_sym)
-
else
-
21
default_actions
-
end
-
end
-
-
1
def name
-
21
@as || @name
-
end
-
-
1
def plural
-
104
@plural ||= name.to_s
-
end
-
-
1
def singular
-
104
@singular ||= name.to_s.singularize
-
end
-
-
1
alias :member_name :singular
-
-
# Checks for uncountable plurals, and appends "_index" if the plural
-
# and singular form are the same.
-
1
def collection_name
-
52
singular == plural ? "#{plural}_index" : plural
-
end
-
-
1
def resource_scope
-
12
{ :controller => controller }
-
end
-
-
1
alias :collection_scope :path
-
-
1
def member_scope
-
9
"#{path}/:#{param}"
-
end
-
-
1
alias :shallow_scope :member_scope
-
-
1
def new_scope(new_path)
-
9
"#{path}/#{new_path}"
-
end
-
-
1
def nested_param
-
:"#{singular}_#{param}"
-
end
-
-
1
def nested_scope
-
"#{path}/:#{nested_param}"
-
end
-
-
end
-
-
1
class SingletonResource < Resource #:nodoc:
-
1
def initialize(entities, options)
-
3
super
-
3
@as = nil
-
3
@controller = (options[:controller] || plural).to_s
-
3
@as = options[:as]
-
end
-
-
1
def default_actions
-
[:show, :create, :update, :destroy, :new, :edit]
-
end
-
-
1
def plural
-
@plural ||= name.to_s.pluralize
-
end
-
-
1
def singular
-
30
@singular ||= name.to_s
-
end
-
-
1
alias :member_name :singular
-
1
alias :collection_name :singular
-
-
1
alias :member_scope :path
-
1
alias :nested_scope :path
-
end
-
-
1
def resources_path_names(options)
-
@scope[:path_names].merge!(options)
-
end
-
-
# Sometimes, you have a resource that clients always look up without
-
# referencing an ID. A common example, /profile always shows the
-
# profile of the currently logged in user. In this case, you can use
-
# a singular resource to map /profile (rather than /profile/:id) to
-
# the show action:
-
#
-
# resource :profile
-
#
-
# creates six different routes in your application, all mapping to
-
# the +Profiles+ controller (note that the controller is named after
-
# the plural):
-
#
-
# GET /profile/new
-
# POST /profile
-
# GET /profile
-
# GET /profile/edit
-
# PATCH/PUT /profile
-
# DELETE /profile
-
#
-
# === Options
-
# Takes same options as +resources+.
-
1
def resource(*resources, &block)
-
4
options = resources.extract_options!.dup
-
-
4
if apply_common_behavior_for(:resource, resources, options, &block)
-
1
return self
-
end
-
-
3
resource_scope(:resource, SingletonResource.new(resources.pop, options)) do
-
3
yield if block_given?
-
-
3
concerns(options[:concerns]) if options[:concerns]
-
-
collection do
-
2
post :create
-
3
end if parent_resource.actions.include?(:create)
-
-
new do
-
2
get :new
-
3
end if parent_resource.actions.include?(:new)
-
-
3
set_member_mappings_for_resource
-
end
-
-
3
self
-
end
-
-
# In Rails, a resourceful route provides a mapping between HTTP verbs
-
# and URLs and controller actions. By convention, each action also maps
-
# to particular CRUD operations in a database. A single entry in the
-
# routing file, such as
-
#
-
# resources :photos
-
#
-
# creates seven different routes in your application, all mapping to
-
# the +Photos+ controller:
-
#
-
# GET /photos
-
# GET /photos/new
-
# POST /photos
-
# GET /photos/:id
-
# GET /photos/:id/edit
-
# PATCH/PUT /photos/:id
-
# DELETE /photos/:id
-
#
-
# Resources can also be nested infinitely by using this block syntax:
-
#
-
# resources :photos do
-
# resources :comments
-
# end
-
#
-
# This generates the following comments routes:
-
#
-
# GET /photos/:photo_id/comments
-
# GET /photos/:photo_id/comments/new
-
# POST /photos/:photo_id/comments
-
# GET /photos/:photo_id/comments/:id
-
# GET /photos/:photo_id/comments/:id/edit
-
# PATCH/PUT /photos/:photo_id/comments/:id
-
# DELETE /photos/:photo_id/comments/:id
-
#
-
# === Options
-
# Takes same options as <tt>Base#match</tt> as well as:
-
#
-
# [:path_names]
-
# Allows you to change the segment component of the +edit+ and +new+ actions.
-
# Actions not specified are not changed.
-
#
-
# resources :posts, path_names: { new: "brand_new" }
-
#
-
# The above example will now change /posts/new to /posts/brand_new
-
#
-
# [:path]
-
# Allows you to change the path prefix for the resource.
-
#
-
# resources :posts, path: 'postings'
-
#
-
# The resource and all segments will now route to /postings instead of /posts
-
#
-
# [:only]
-
# Only generate routes for the given actions.
-
#
-
# resources :cows, only: :show
-
# resources :cows, only: [:show, :index]
-
#
-
# [:except]
-
# Generate all routes except for the given actions.
-
#
-
# resources :cows, except: :show
-
# resources :cows, except: [:show, :index]
-
#
-
# [:shallow]
-
# Generates shallow routes for nested resource(s). When placed on a parent resource,
-
# generates shallow routes for all nested resources.
-
#
-
# resources :posts, shallow: true do
-
# resources :comments
-
# end
-
#
-
# Is the same as:
-
#
-
# resources :posts do
-
# resources :comments, except: [:show, :edit, :update, :destroy]
-
# end
-
# resources :comments, only: [:show, :edit, :update, :destroy]
-
#
-
# This allows URLs for resources that otherwise would be deeply nested such
-
# as a comment on a blog post like <tt>/posts/a-long-permalink/comments/1234</tt>
-
# to be shortened to just <tt>/comments/1234</tt>.
-
#
-
# [:shallow_path]
-
# Prefixes nested shallow routes with the specified path.
-
#
-
# scope shallow_path: "sekret" do
-
# resources :posts do
-
# resources :comments, shallow: true
-
# end
-
# end
-
#
-
# The +comments+ resource here will have the following routes generated for it:
-
#
-
# post_comments GET /posts/:post_id/comments(.:format)
-
# post_comments POST /posts/:post_id/comments(.:format)
-
# new_post_comment GET /posts/:post_id/comments/new(.:format)
-
# edit_comment GET /sekret/comments/:id/edit(.:format)
-
# comment GET /sekret/comments/:id(.:format)
-
# comment PATCH/PUT /sekret/comments/:id(.:format)
-
# comment DELETE /sekret/comments/:id(.:format)
-
#
-
# [:shallow_prefix]
-
# Prefixes nested shallow route names with specified prefix.
-
#
-
# scope shallow_prefix: "sekret" do
-
# resources :posts do
-
# resources :comments, shallow: true
-
# end
-
# end
-
#
-
# The +comments+ resource here will have the following routes generated for it:
-
#
-
# post_comments GET /posts/:post_id/comments(.:format)
-
# post_comments POST /posts/:post_id/comments(.:format)
-
# new_post_comment GET /posts/:post_id/comments/new(.:format)
-
# edit_sekret_comment GET /comments/:id/edit(.:format)
-
# sekret_comment GET /comments/:id(.:format)
-
# sekret_comment PATCH/PUT /comments/:id(.:format)
-
# sekret_comment DELETE /comments/:id(.:format)
-
#
-
# [:format]
-
# Allows you to specify the default value for optional +format+
-
# segment or disable it by supplying +false+.
-
#
-
# === Examples
-
#
-
# # routes call <tt>Admin::PostsController</tt>
-
# resources :posts, module: "admin"
-
#
-
# # resource actions are at /admin/posts.
-
# resources :posts, path: "admin/posts"
-
1
def resources(*resources, &block)
-
9
options = resources.extract_options!.dup
-
-
9
if apply_common_behavior_for(:resources, resources, options, &block)
-
return self
-
end
-
-
9
resource_scope(:resources, Resource.new(resources.pop, options)) do
-
9
yield if block_given?
-
-
9
concerns(options[:concerns]) if options[:concerns]
-
-
9
collection do
-
9
get :index if parent_resource.actions.include?(:index)
-
9
post :create if parent_resource.actions.include?(:create)
-
end
-
-
new do
-
7
get :new
-
9
end if parent_resource.actions.include?(:new)
-
-
9
set_member_mappings_for_resource
-
end
-
-
9
self
-
end
-
-
# To add a route to the collection:
-
#
-
# resources :photos do
-
# collection do
-
# get 'search'
-
# end
-
# end
-
#
-
# This will enable Rails to recognize paths such as <tt>/photos/search</tt>
-
# with GET, and route to the search action of +PhotosController+. It will also
-
# create the <tt>search_photos_url</tt> and <tt>search_photos_path</tt>
-
# route helpers.
-
1
def collection
-
12
unless resource_scope?
-
raise ArgumentError, "can't use collection outside resource(s) scope"
-
end
-
-
12
with_scope_level(:collection) do
-
12
scope(parent_resource.collection_scope) do
-
12
yield
-
end
-
end
-
end
-
-
# To add a member route, add a member block into the resource block:
-
#
-
# resources :photos do
-
# member do
-
# get 'preview'
-
# end
-
# end
-
#
-
# This will recognize <tt>/photos/1/preview</tt> with GET, and route to the
-
# preview action of +PhotosController+. It will also create the
-
# <tt>preview_photo_url</tt> and <tt>preview_photo_path</tt> helpers.
-
1
def member
-
16
unless resource_scope?
-
raise ArgumentError, "can't use member outside resource(s) scope"
-
end
-
-
16
with_scope_level(:member) do
-
16
if shallow?
-
shallow_scope(parent_resource.member_scope) { yield }
-
else
-
32
scope(parent_resource.member_scope) { yield }
-
end
-
end
-
end
-
-
1
def new
-
9
unless resource_scope?
-
raise ArgumentError, "can't use new outside resource(s) scope"
-
end
-
-
9
with_scope_level(:new) do
-
9
scope(parent_resource.new_scope(action_path(:new))) do
-
9
yield
-
end
-
end
-
end
-
-
1
def nested
-
unless resource_scope?
-
raise ArgumentError, "can't use nested outside resource(s) scope"
-
end
-
-
with_scope_level(:nested) do
-
if shallow? && nesting_depth > 1
-
shallow_scope(parent_resource.nested_scope, nested_options) { yield }
-
else
-
scope(parent_resource.nested_scope, nested_options) { yield }
-
end
-
end
-
end
-
-
# See ActionDispatch::Routing::Mapper::Scoping#namespace
-
1
def namespace(path, options = {})
-
if resource_scope?
-
nested { super }
-
else
-
super
-
end
-
end
-
-
1
def shallow
-
scope(:shallow => true) do
-
yield
-
end
-
end
-
-
1
def shallow?
-
67
parent_resource.instance_of?(Resource) && @scope[:shallow]
-
end
-
-
# match 'path' => 'controller#action'
-
# match 'path', to: 'controller#action'
-
# match 'path', 'otherpath', on: :member, via: :get
-
1
def match(path, *rest)
-
73
if rest.empty? && Hash === path
-
options = path
-
path, to = options.find { |name, _value| name.is_a?(String) }
-
options[:to] = to
-
options.delete(path)
-
paths = [path]
-
else
-
73
options = rest.pop || {}
-
73
paths = [path] + rest
-
end
-
-
73
options[:anchor] = true unless options.key?(:anchor)
-
-
73
if options[:on] && !VALID_ON_OPTIONS.include?(options[:on])
-
raise ArgumentError, "Unknown scope #{on.inspect} given to :on"
-
end
-
-
73
if @scope[:controller] && @scope[:action]
-
options[:to] ||= "#{@scope[:controller]}##{@scope[:action]}"
-
end
-
-
73
paths.each do |_path|
-
73
route_options = options.dup
-
73
route_options[:path] ||= _path if _path.is_a?(String)
-
-
73
path_without_format = _path.to_s.sub(/\(\.:format\)$/, '')
-
73
if using_match_shorthand?(path_without_format, route_options)
-
3
route_options[:to] ||= path_without_format.gsub(%r{^/}, "").sub(%r{/([^/]*)$}, '#\1')
-
3
route_options[:to].tr!("-", "_")
-
end
-
-
73
decomposed_match(_path, route_options)
-
end
-
73
self
-
end
-
-
1
def using_match_shorthand?(path, options)
-
73
path && (options[:to] || options[:action]).nil? && path =~ %r{/[\w/]+$}
-
end
-
-
1
def decomposed_match(path, options) # :nodoc:
-
78
if on = options.delete(:on)
-
2
send(on) { decomposed_match(path, options) }
-
else
-
77
case @scope[:scope_level]
-
when :resources
-
nested { decomposed_match(path, options) }
-
when :resource
-
8
member { decomposed_match(path, options) }
-
else
-
73
add_route(path, options)
-
end
-
end
-
end
-
-
1
def add_route(action, options) # :nodoc:
-
73
path = path_for_action(action, options.delete(:path))
-
73
action = action.to_s.dup
-
-
73
if action =~ /^[\w\-\/]+$/
-
72
options[:action] ||= action.tr('-', '_') unless action.include?("/")
-
else
-
1
action = nil
-
end
-
-
73
if !options.fetch(:as, true)
-
1
options.delete(:as)
-
else
-
72
options[:as] = name_for_action(options[:as], action)
-
end
-
-
73
mapping = Mapping.new(@set, @scope, URI.parser.escape(path), options)
-
73
app, conditions, requirements, defaults, as, anchor = mapping.to_route
-
73
@set.add_route(app, conditions, requirements, defaults, as, anchor)
-
end
-
-
1
def root(path, options={})
-
1
if path.is_a?(String)
-
1
options[:to] = path
-
elsif path.is_a?(Hash) and options.empty?
-
options = path
-
else
-
raise ArgumentError, "must be called with a path and/or options"
-
end
-
-
1
if @scope[:scope_level] == :resources
-
with_scope_level(:root) do
-
scope(parent_resource.path) do
-
super(options)
-
end
-
end
-
else
-
1
super(options)
-
end
-
end
-
-
1
protected
-
-
1
def parent_resource #:nodoc:
-
404
@scope[:scope_level_resource]
-
end
-
-
1
def apply_common_behavior_for(method, resources, options, &block) #:nodoc:
-
13
if resources.length > 1
-
resources.each { |r| send(method, r, options, &block) }
-
return true
-
end
-
-
13
if options.delete(:shallow)
-
shallow do
-
send(method, resources.pop, options, &block)
-
end
-
return true
-
end
-
-
13
if resource_scope?
-
nested { send(method, resources.pop, options, &block) }
-
return true
-
end
-
-
13
options.keys.each do |k|
-
19
(options[:constraints] ||= {})[k] = options.delete(k) if options[k].is_a?(Regexp)
-
end
-
-
13
scope_options = options.slice!(*RESOURCE_OPTIONS)
-
13
unless scope_options.empty?
-
1
scope(scope_options) do
-
1
send(method, resources.pop, options, &block)
-
end
-
1
return true
-
end
-
-
12
unless action_options?(options)
-
3
options.merge!(scope_action_options) if scope_action_options?
-
end
-
-
12
false
-
end
-
-
1
def action_options?(options) #:nodoc:
-
12
options[:only] || options[:except]
-
end
-
-
1
def scope_action_options? #:nodoc:
-
3
@scope[:options] && (@scope[:options][:only] || @scope[:options][:except])
-
end
-
-
1
def scope_action_options #:nodoc:
-
@scope[:options].slice(:only, :except)
-
end
-
-
1
def resource_scope? #:nodoc:
-
50
RESOURCE_SCOPES.include? @scope[:scope_level]
-
end
-
-
1
def resource_method_scope? #:nodoc:
-
130
RESOURCE_METHOD_SCOPES.include? @scope[:scope_level]
-
end
-
-
1
def with_exclusive_scope
-
begin
-
old_name_prefix, old_path = @scope[:as], @scope[:path]
-
@scope[:as], @scope[:path] = nil, nil
-
-
with_scope_level(:exclusive) do
-
yield
-
end
-
ensure
-
@scope[:as], @scope[:path] = old_name_prefix, old_path
-
end
-
end
-
-
1
def with_scope_level(kind)
-
49
old, @scope[:scope_level] = @scope[:scope_level], kind
-
49
yield
-
ensure
-
49
@scope[:scope_level] = old
-
end
-
-
1
def resource_scope(kind, resource) #:nodoc:
-
12
old_resource, @scope[:scope_level_resource] = @scope[:scope_level_resource], resource
-
12
@nesting.push(resource)
-
-
12
with_scope_level(kind) do
-
24
scope(parent_resource.resource_scope) { yield }
-
end
-
ensure
-
12
@nesting.pop
-
12
@scope[:scope_level_resource] = old_resource
-
end
-
-
1
def nested_options #:nodoc:
-
options = { :as => parent_resource.member_name }
-
options[:constraints] = {
-
parent_resource.nested_param => param_constraint
-
} if param_constraint?
-
-
options
-
end
-
-
1
def nesting_depth #:nodoc:
-
@nesting.size
-
end
-
-
1
def param_constraint? #:nodoc:
-
@scope[:constraints] && @scope[:constraints][parent_resource.param].is_a?(Regexp)
-
end
-
-
1
def param_constraint #:nodoc:
-
@scope[:constraints][parent_resource.param]
-
end
-
-
1
def canonical_action?(action, flag) #:nodoc:
-
143
flag && resource_method_scope? && CANONICAL_ACTIONS.include?(action.to_s)
-
end
-
-
1
def shallow_scope(path, options = {}) #:nodoc:
-
old_name_prefix, old_path = @scope[:as], @scope[:path]
-
@scope[:as], @scope[:path] = @scope[:shallow_prefix], @scope[:shallow_path]
-
-
scope(path, options) { yield }
-
ensure
-
@scope[:as], @scope[:path] = old_name_prefix, old_path
-
end
-
-
1
def path_for_action(action, path) #:nodoc:
-
73
if canonical_action?(action, path.blank?)
-
58
@scope[:path].to_s
-
else
-
15
"#{@scope[:path]}/#{action_path(action, path)}"
-
end
-
end
-
-
1
def action_path(name, path = nil) #:nodoc:
-
24
name = name.to_sym if name.is_a?(String)
-
24
path || @scope[:path_names][name] || name.to_s
-
end
-
-
1
def prefix_name_for_action(as, action) #:nodoc:
-
73
if as
-
3
prefix = as
-
elsif !canonical_action?(action, @scope[:scope_level])
-
11
prefix = action
-
end
-
73
prefix.to_s.tr('-', '_') if prefix
-
end
-
-
1
def name_for_action(as, action) #:nodoc:
-
73
prefix = prefix_name_for_action(as, action)
-
73
prefix = Mapper.normalize_name(prefix) if prefix
-
73
name_prefix = @scope[:as]
-
-
73
if parent_resource
-
68
return nil unless as || action
-
-
67
collection_name = parent_resource.collection_name
-
67
member_name = parent_resource.member_name
-
end
-
-
72
name = case @scope[:scope_level]
-
when :nested
-
[name_prefix, prefix]
-
when :collection
-
18
[prefix, name_prefix, collection_name]
-
when :new
-
9
[prefix, :new, name_prefix, member_name]
-
when :member
-
40
[prefix, name_prefix, member_name]
-
when :root
-
[name_prefix, collection_name, prefix]
-
else
-
5
[name_prefix, member_name, prefix]
-
end
-
-
72
if candidate = name.select(&:present?).join("_").presence
-
# If a name was not explicitly given, we check if it is valid
-
# and return nil in case it isn't. Otherwise, we pass the invalid name
-
# forward so the underlying router engine treats it and raises an exception.
-
72
if as.nil?
-
2035
candidate unless @set.routes.find { |r| r.name == candidate } || candidate !~ /\A[_a-z]/i
-
else
-
3
candidate
-
end
-
end
-
end
-
-
1
def set_member_mappings_for_resource
-
12
member do
-
12
get :edit if parent_resource.actions.include?(:edit)
-
12
get :show if parent_resource.actions.include?(:show)
-
12
if parent_resource.actions.include?(:update)
-
9
patch :update
-
9
put :update
-
end
-
12
delete :destroy if parent_resource.actions.include?(:destroy)
-
end
-
end
-
end
-
-
# Routing Concerns allow you to declare common routes that can be reused
-
# inside others resources and routes.
-
#
-
# concern :commentable do
-
# resources :comments
-
# end
-
#
-
# concern :image_attachable do
-
# resources :images, only: :index
-
# end
-
#
-
# These concerns are used in Resources routing:
-
#
-
# resources :messages, concerns: [:commentable, :image_attachable]
-
#
-
# or in a scope or namespace:
-
#
-
# namespace :posts do
-
# concerns :commentable
-
# end
-
1
module Concerns
-
# Define a routing concern using a name.
-
#
-
# Concerns may be defined inline, using a block, or handled by
-
# another object, by passing that object as the second parameter.
-
#
-
# The concern object, if supplied, should respond to <tt>call</tt>,
-
# which will receive two parameters:
-
#
-
# * The current mapper
-
# * A hash of options which the concern object may use
-
#
-
# Options may also be used by concerns defined in a block by accepting
-
# a block parameter. So, using a block, you might do something as
-
# simple as limit the actions available on certain resources, passing
-
# standard resource options through the concern:
-
#
-
# concern :commentable do |options|
-
# resources :comments, options
-
# end
-
#
-
# resources :posts, concerns: :commentable
-
# resources :archived_posts do
-
# # Don't allow comments on archived posts
-
# concerns :commentable, only: [:index, :show]
-
# end
-
#
-
# Or, using a callable object, you might implement something more
-
# specific to your application, which would be out of place in your
-
# routes file.
-
#
-
# # purchasable.rb
-
# class Purchasable
-
# def initialize(defaults = {})
-
# @defaults = defaults
-
# end
-
#
-
# def call(mapper, options = {})
-
# options = @defaults.merge(options)
-
# mapper.resources :purchases
-
# mapper.resources :receipts
-
# mapper.resources :returns if options[:returnable]
-
# end
-
# end
-
#
-
# # routes.rb
-
# concern :purchasable, Purchasable.new(returnable: true)
-
#
-
# resources :toys, concerns: :purchasable
-
# resources :electronics, concerns: :purchasable
-
# resources :pets do
-
# concerns :purchasable, returnable: false
-
# end
-
#
-
# Any routing helpers can be used inside a concern. If using a
-
# callable, they're accessible from the Mapper that's passed to
-
# <tt>call</tt>.
-
1
def concern(name, callable = nil, &block)
-
callable ||= lambda { |mapper, options| mapper.instance_exec(options, &block) }
-
@concerns[name] = callable
-
end
-
-
# Use the named concerns
-
#
-
# resources :posts do
-
# concerns :commentable
-
# end
-
#
-
# concerns also work in any routes helper that you want to use:
-
#
-
# namespace :posts do
-
# concerns :commentable
-
# end
-
1
def concerns(*args)
-
options = args.extract_options!
-
args.flatten.each do |name|
-
if concern = @concerns[name]
-
concern.call(self, options)
-
else
-
raise ArgumentError, "No concern named #{name} was found!"
-
end
-
end
-
end
-
end
-
-
1
def initialize(set) #:nodoc:
-
2
@set = set
-
2
@scope = { :path_names => @set.resources_path_names }
-
2
@concerns = {}
-
2
@nesting = []
-
end
-
-
1
include Base
-
1
include HttpHelpers
-
1
include Redirection
-
1
include Scoping
-
1
include Concerns
-
1
include Resources
-
end
-
end
-
end
-
1
require 'action_controller/model_naming'
-
-
1
module ActionDispatch
-
1
module Routing
-
# Polymorphic URL helpers are methods for smart resolution to a named route call when
-
# given an Active Record model instance. They are to be used in combination with
-
# ActionController::Resources.
-
#
-
# These methods are useful when you want to generate correct URL or path to a RESTful
-
# resource without having to know the exact type of the record in question.
-
#
-
# Nested resources and/or namespaces are also supported, as illustrated in the example:
-
#
-
# polymorphic_url([:admin, @article, @comment])
-
#
-
# results in:
-
#
-
# admin_article_comment_url(@article, @comment)
-
#
-
# == Usage within the framework
-
#
-
# Polymorphic URL helpers are used in a number of places throughout the \Rails framework:
-
#
-
# * <tt>url_for</tt>, so you can use it with a record as the argument, e.g.
-
# <tt>url_for(@article)</tt>;
-
# * ActionView::Helpers::FormHelper uses <tt>polymorphic_path</tt>, so you can write
-
# <tt>form_for(@article)</tt> without having to specify <tt>:url</tt> parameter for the form
-
# action;
-
# * <tt>redirect_to</tt> (which, in fact, uses <tt>url_for</tt>) so you can write
-
# <tt>redirect_to(post)</tt> in your controllers;
-
# * ActionView::Helpers::AtomFeedHelper, so you don't have to explicitly specify URLs
-
# for feed entries.
-
#
-
# == Prefixed polymorphic helpers
-
#
-
# In addition to <tt>polymorphic_url</tt> and <tt>polymorphic_path</tt> methods, a
-
# number of prefixed helpers are available as a shorthand to <tt>action: "..."</tt>
-
# in options. Those are:
-
#
-
# * <tt>edit_polymorphic_url</tt>, <tt>edit_polymorphic_path</tt>
-
# * <tt>new_polymorphic_url</tt>, <tt>new_polymorphic_path</tt>
-
#
-
# Example usage:
-
#
-
# edit_polymorphic_path(@post) # => "/posts/1/edit"
-
# polymorphic_path(@post, format: :pdf) # => "/posts/1.pdf"
-
#
-
# == Usage with mounted engines
-
#
-
# If you are using a mounted engine and you need to use a polymorphic_url
-
# pointing at the engine's routes, pass in the engine's route proxy as the first
-
# argument to the method. For example:
-
#
-
# polymorphic_url([blog, @post]) # calls blog.post_path(@post)
-
# form_for([blog, @post]) # => "/blog/posts/1"
-
#
-
1
module PolymorphicRoutes
-
1
include ActionController::ModelNaming
-
-
# Constructs a call to a named RESTful route for the given record and returns the
-
# resulting URL string. For example:
-
#
-
# # calls post_url(post)
-
# polymorphic_url(post) # => "http://example.com/posts/1"
-
# polymorphic_url([blog, post]) # => "http://example.com/blogs/1/posts/1"
-
# polymorphic_url([:admin, blog, post]) # => "http://example.com/admin/blogs/1/posts/1"
-
# polymorphic_url([user, :blog, post]) # => "http://example.com/users/1/blog/posts/1"
-
# polymorphic_url(Comment) # => "http://example.com/comments"
-
#
-
# ==== Options
-
#
-
# * <tt>:action</tt> - Specifies the action prefix for the named route:
-
# <tt>:new</tt> or <tt>:edit</tt>. Default is no prefix.
-
# * <tt>:routing_type</tt> - Allowed values are <tt>:path</tt> or <tt>:url</tt>.
-
# Default is <tt>:url</tt>.
-
#
-
# Also includes all the options from <tt>url_for</tt>. These include such
-
# things as <tt>:anchor</tt> or <tt>:trailing_slash</tt>. Example usage
-
# is given below:
-
#
-
# polymorphic_url([blog, post], anchor: 'my_anchor')
-
# # => "http://example.com/blogs/1/posts/1#my_anchor"
-
# polymorphic_url([blog, post], anchor: 'my_anchor', script_name: "/my_app")
-
# # => "http://example.com/my_app/blogs/1/posts/1#my_anchor"
-
#
-
# For all of these options, see the documentation for <tt>url_for</tt>.
-
#
-
# ==== Functionality
-
#
-
# # an Article record
-
# polymorphic_url(record) # same as article_url(record)
-
#
-
# # a Comment record
-
# polymorphic_url(record) # same as comment_url(record)
-
#
-
# # it recognizes new records and maps to the collection
-
# record = Comment.new
-
# polymorphic_url(record) # same as comments_url()
-
#
-
# # the class of a record will also map to the collection
-
# polymorphic_url(Comment) # same as comments_url()
-
#
-
1
def polymorphic_url(record_or_hash_or_array, options = {})
-
if record_or_hash_or_array.kind_of?(Array)
-
record_or_hash_or_array = record_or_hash_or_array.compact
-
if record_or_hash_or_array.first.is_a?(ActionDispatch::Routing::RoutesProxy)
-
proxy = record_or_hash_or_array.shift
-
end
-
record_or_hash_or_array = record_or_hash_or_array[0] if record_or_hash_or_array.size == 1
-
end
-
-
record = extract_record(record_or_hash_or_array)
-
record = convert_to_model(record)
-
-
args = Array === record_or_hash_or_array ?
-
record_or_hash_or_array.dup :
-
[ record_or_hash_or_array ]
-
-
inflection = if options[:action] && options[:action].to_s == "new"
-
args.pop
-
:singular
-
elsif (record.respond_to?(:persisted?) && !record.persisted?)
-
args.pop
-
:plural
-
elsif record.is_a?(Class)
-
args.pop
-
:plural
-
else
-
:singular
-
end
-
-
args.delete_if {|arg| arg.is_a?(Symbol) || arg.is_a?(String)}
-
named_route = build_named_route_call(record_or_hash_or_array, inflection, options)
-
-
url_options = options.except(:action, :routing_type)
-
unless url_options.empty?
-
args.last.kind_of?(Hash) ? args.last.merge!(url_options) : args << url_options
-
end
-
-
args.collect! { |a| convert_to_model(a) }
-
-
(proxy || self).send(named_route, *args)
-
end
-
-
# Returns the path component of a URL for the given record. It uses
-
# <tt>polymorphic_url</tt> with <tt>routing_type: :path</tt>.
-
1
def polymorphic_path(record_or_hash_or_array, options = {})
-
polymorphic_url(record_or_hash_or_array, options.merge(:routing_type => :path))
-
end
-
-
1
%w(edit new).each do |action|
-
2
module_eval <<-EOT, __FILE__, __LINE__ + 1
-
def #{action}_polymorphic_url(record_or_hash, options = {}) # def edit_polymorphic_url(record_or_hash, options = {})
-
polymorphic_url( # polymorphic_url(
-
record_or_hash, # record_or_hash,
-
options.merge(:action => "#{action}")) # options.merge(:action => "edit"))
-
end # end
-
#
-
def #{action}_polymorphic_path(record_or_hash, options = {}) # def edit_polymorphic_path(record_or_hash, options = {})
-
polymorphic_url( # polymorphic_url(
-
record_or_hash, # record_or_hash,
-
options.merge(:action => "#{action}", :routing_type => :path)) # options.merge(:action => "edit", :routing_type => :path))
-
end # end
-
EOT
-
end
-
-
1
private
-
1
def action_prefix(options)
-
options[:action] ? "#{options[:action]}_" : ''
-
end
-
-
1
def routing_type(options)
-
options[:routing_type] || :url
-
end
-
-
1
def build_named_route_call(records, inflection, options = {})
-
if records.is_a?(Array)
-
record = records.pop
-
route = records.map do |parent|
-
if parent.is_a?(Symbol) || parent.is_a?(String)
-
parent
-
else
-
model_name_from_record_or_class(parent).singular_route_key
-
end
-
end
-
else
-
record = extract_record(records)
-
route = []
-
end
-
-
if record.is_a?(Symbol) || record.is_a?(String)
-
route << record
-
elsif record
-
if inflection == :singular
-
route << model_name_from_record_or_class(record).singular_route_key
-
else
-
route << model_name_from_record_or_class(record).route_key
-
end
-
else
-
raise ArgumentError, "Nil location provided. Can't build URI."
-
end
-
-
route << routing_type(options)
-
-
action_prefix(options) + route.join("_")
-
end
-
-
1
def extract_record(record_or_hash_or_array)
-
case record_or_hash_or_array
-
when Array; record_or_hash_or_array.last
-
when Hash; record_or_hash_or_array[:id]
-
else record_or_hash_or_array
-
end
-
end
-
end
-
end
-
end
-
-
1
require 'action_dispatch/http/request'
-
1
require 'active_support/core_ext/uri'
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'rack/utils'
-
1
require 'action_controller/metal/exceptions'
-
-
1
module ActionDispatch
-
1
module Routing
-
1
class Redirect # :nodoc:
-
1
attr_reader :status, :block
-
-
1
def initialize(status, block)
-
@status = status
-
@block = block
-
end
-
-
1
def call(env)
-
req = Request.new(env)
-
-
# If any of the path parameters has an invalid encoding then
-
# raise since it's likely to trigger errors further on.
-
req.symbolized_path_parameters.each do |key, value|
-
unless value.valid_encoding?
-
raise ActionController::BadRequest, "Invalid parameter: #{key} => #{value}"
-
end
-
end
-
-
uri = URI.parse(path(req.symbolized_path_parameters, req))
-
-
unless uri.host
-
if relative_path?(uri.path)
-
uri.path = "#{req.script_name}/#{uri.path}"
-
elsif uri.path.empty?
-
uri.path = req.script_name.empty? ? "/" : req.script_name
-
end
-
end
-
-
uri.scheme ||= req.scheme
-
uri.host ||= req.host
-
uri.port ||= req.port unless req.standard_port?
-
-
body = %(<html><body>You are being <a href="#{ERB::Util.h(uri.to_s)}">redirected</a>.</body></html>)
-
-
headers = {
-
'Location' => uri.to_s,
-
'Content-Type' => 'text/html',
-
'Content-Length' => body.length.to_s
-
}
-
-
[ status, headers, [body] ]
-
end
-
-
1
def path(params, request)
-
block.call params, request
-
end
-
-
1
def inspect
-
"redirect(#{status})"
-
end
-
-
1
private
-
1
def relative_path?(path)
-
path && !path.empty? && path[0] != '/'
-
end
-
-
1
def escape(params)
-
Hash[params.map{ |k,v| [k, Rack::Utils.escape(v)] }]
-
end
-
-
1
def escape_fragment(params)
-
Hash[params.map{ |k,v| [k, Journey::Router::Utils.escape_fragment(v)] }]
-
end
-
-
1
def escape_path(params)
-
Hash[params.map{ |k,v| [k, Journey::Router::Utils.escape_path(v)] }]
-
end
-
end
-
-
1
class PathRedirect < Redirect
-
1
URL_PARTS = /\A([^?]+)?(\?[^#]+)?(#.+)?\z/
-
-
1
def path(params, request)
-
if block.match(URL_PARTS)
-
path = interpolation_required?($1, params) ? $1 % escape_path(params) : $1
-
query = interpolation_required?($2, params) ? $2 % escape(params) : $2
-
fragment = interpolation_required?($3, params) ? $3 % escape_fragment(params) : $3
-
-
"#{path}#{query}#{fragment}"
-
else
-
interpolation_required?(block, params) ? block % escape(params) : block
-
end
-
end
-
-
1
def inspect
-
"redirect(#{status}, #{block})"
-
end
-
-
1
private
-
1
def interpolation_required?(string, params)
-
!params.empty? && string && string.match(/%\{\w*\}/)
-
end
-
end
-
-
1
class OptionRedirect < Redirect # :nodoc:
-
1
alias :options :block
-
-
1
def path(params, request)
-
url_options = {
-
:protocol => request.protocol,
-
:host => request.host,
-
:port => request.optional_port,
-
:path => request.path,
-
:params => request.query_parameters
-
}.merge! options
-
-
if !params.empty? && url_options[:path].match(/%\{\w*\}/)
-
url_options[:path] = (url_options[:path] % escape_path(params))
-
end
-
-
unless options[:host] || options[:domain]
-
if relative_path?(url_options[:path])
-
url_options[:path] = "/#{url_options[:path]}"
-
url_options[:script_name] = request.script_name
-
elsif url_options[:path].empty?
-
url_options[:path] = request.script_name.empty? ? "/" : ""
-
url_options[:script_name] = request.script_name
-
end
-
end
-
-
ActionDispatch::Http::URL.url_for url_options
-
end
-
-
1
def inspect
-
"redirect(#{status}, #{options.map{ |k,v| "#{k}: #{v}" }.join(', ')})"
-
end
-
end
-
-
1
module Redirection
-
-
# Redirect any path to another path:
-
#
-
# get "/stories" => redirect("/posts")
-
#
-
# You can also use interpolation in the supplied redirect argument:
-
#
-
# get 'docs/:article', to: redirect('/wiki/%{article}')
-
#
-
# Note that if you return a path without a leading slash then the url is prefixed with the
-
# current SCRIPT_NAME environment variable. This is typically '/' but may be different in
-
# a mounted engine or where the application is deployed to a subdirectory of a website.
-
#
-
# Alternatively you can use one of the other syntaxes:
-
#
-
# The block version of redirect allows for the easy encapsulation of any logic associated with
-
# the redirect in question. Either the params and request are supplied as arguments, or just
-
# params, depending of how many arguments your block accepts. A string is required as a
-
# return value.
-
#
-
# get 'jokes/:number', to: redirect { |params, request|
-
# path = (params[:number].to_i.even? ? "wheres-the-beef" : "i-love-lamp")
-
# "http://#{request.host_with_port}/#{path}"
-
# }
-
#
-
# Note that the +do end+ syntax for the redirect block wouldn't work, as Ruby would pass
-
# the block to +get+ instead of +redirect+. Use <tt>{ ... }</tt> instead.
-
#
-
# The options version of redirect allows you to supply only the parts of the url which need
-
# to change, it also supports interpolation of the path similar to the first example.
-
#
-
# get 'stores/:name', to: redirect(subdomain: 'stores', path: '/%{name}')
-
# get 'stores/:name(*all)', to: redirect(subdomain: 'stores', path: '/%{name}%{all}')
-
#
-
# Finally, an object which responds to call can be supplied to redirect, allowing you to reuse
-
# common redirect routes. The call method must accept two arguments, params and request, and return
-
# a string.
-
#
-
# get 'accounts/:name' => redirect(SubdomainRedirector.new('api'))
-
#
-
1
def redirect(*args, &block)
-
options = args.extract_options!
-
status = options.delete(:status) || 301
-
path = args.shift
-
-
return OptionRedirect.new(status, options) if options.any?
-
return PathRedirect.new(status, path) if String === path
-
-
block = path if path.respond_to? :call
-
raise ArgumentError, "redirection argument not supported" unless block
-
Redirect.new status, block
-
end
-
end
-
end
-
end
-
1
require 'action_dispatch/journey'
-
1
require 'forwardable'
-
1
require 'thread_safe'
-
1
require 'active_support/core_ext/object/to_query'
-
1
require 'active_support/core_ext/hash/slice'
-
1
require 'active_support/core_ext/module/remove_method'
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'action_controller/metal/exceptions'
-
-
1
module ActionDispatch
-
1
module Routing
-
1
class RouteSet #:nodoc:
-
# Since the router holds references to many parts of the system
-
# like engines, controllers and the application itself, inspecting
-
# the route set can actually be really slow, therefore we default
-
# alias inspect to to_s.
-
1
alias inspect to_s
-
-
1
PARAMETERS_KEY = 'action_dispatch.request.path_parameters'
-
-
1
class Dispatcher #:nodoc:
-
1
def initialize(options={})
-
72
@defaults = options[:defaults]
-
72
@glob_param = options.delete(:glob)
-
72
@controller_class_names = ThreadSafe::Cache.new
-
end
-
-
1
def call(env)
-
params = env[PARAMETERS_KEY]
-
-
# If any of the path parameters has an invalid encoding then
-
# raise since it's likely to trigger errors further on.
-
params.each do |key, value|
-
next unless value.respond_to?(:valid_encoding?)
-
-
unless value.valid_encoding?
-
raise ActionController::BadRequest, "Invalid parameter: #{key} => #{value}"
-
end
-
end
-
-
prepare_params!(params)
-
-
# Just raise undefined constant errors if a controller was specified as default.
-
unless controller = controller(params, @defaults.key?(:controller))
-
return [404, {'X-Cascade' => 'pass'}, []]
-
end
-
-
dispatch(controller, params[:action], env)
-
end
-
-
1
def prepare_params!(params)
-
normalize_controller!(params)
-
merge_default_action!(params)
-
split_glob_param!(params) if @glob_param
-
end
-
-
# If this is a default_controller (i.e. a controller specified by the user)
-
# we should raise an error in case it's not found, because it usually means
-
# a user error. However, if the controller was retrieved through a dynamic
-
# segment, as in :controller(/:action), we should simply return nil and
-
# delegate the control back to Rack cascade. Besides, if this is not a default
-
# controller, it means we should respect the @scope[:module] parameter.
-
1
def controller(params, default_controller=true)
-
if params && params.key?(:controller)
-
controller_param = params[:controller]
-
controller_reference(controller_param)
-
end
-
rescue NameError => e
-
raise ActionController::RoutingError, e.message, e.backtrace if default_controller
-
end
-
-
1
private
-
-
1
def controller_reference(controller_param)
-
const_name = @controller_class_names[controller_param] ||= "#{controller_param.camelize}Controller"
-
ActiveSupport::Dependencies.constantize(const_name)
-
end
-
-
1
def dispatch(controller, action, env)
-
controller.action(action).call(env)
-
end
-
-
1
def normalize_controller!(params)
-
params[:controller] = params[:controller].underscore if params.key?(:controller)
-
end
-
-
1
def merge_default_action!(params)
-
params[:action] ||= 'index'
-
end
-
-
1
def split_glob_param!(params)
-
params[@glob_param] = params[@glob_param].split('/').map { |v| URI.parser.unescape(v) }
-
end
-
end
-
-
# A NamedRouteCollection instance is a collection of named routes, and also
-
# maintains an anonymous module that can be used to install helpers for the
-
# named routes.
-
1
class NamedRouteCollection #:nodoc:
-
1
include Enumerable
-
1
attr_reader :routes, :helpers, :module
-
-
1
def initialize
-
2
@routes = {}
-
2
@helpers = []
-
2
@module = Module.new
-
end
-
-
1
def helper_names
-
@helpers.map(&:to_s)
-
end
-
-
1
def clear!
-
2
@helpers.each do |helper|
-
@module.remove_possible_method helper
-
end
-
-
2
@routes.clear
-
2
@helpers.clear
-
end
-
-
1
def add(name, route)
-
38
routes[name.to_sym] = route
-
38
define_named_route_methods(name, route)
-
end
-
-
1
def get(name)
-
38
routes[name.to_sym]
-
end
-
-
1
alias []= add
-
1
alias [] get
-
1
alias clear clear!
-
-
1
def each
-
routes.each { |name, route| yield name, route }
-
self
-
end
-
-
1
def names
-
routes.keys
-
end
-
-
1
def length
-
routes.length
-
end
-
-
1
class UrlHelper # :nodoc:
-
1
def self.create(route, options)
-
76
if optimize_helper?(route)
-
76
OptimizedUrlHelper.new(route, options)
-
else
-
new route, options
-
end
-
end
-
-
1
def self.optimize_helper?(route)
-
76
route.requirements.except(:controller, :action).empty?
-
end
-
-
1
class OptimizedUrlHelper < UrlHelper # :nodoc:
-
1
attr_reader :arg_size
-
-
1
def initialize(route, options)
-
76
super
-
76
@klass = Journey::Router::Utils
-
76
@required_parts = @route.required_parts
-
76
@arg_size = @required_parts.size
-
76
@optimized_path = @route.optimized_path
-
end
-
-
1
def call(t, args)
-
if args.size == arg_size && !args.last.is_a?(Hash) && optimize_routes_generation?(t)
-
options = @options.dup
-
options.merge!(t.url_options) if t.respond_to?(:url_options)
-
options[:path] = optimized_helper(args)
-
ActionDispatch::Http::URL.url_for(options)
-
else
-
super
-
end
-
end
-
-
1
private
-
-
1
def optimized_helper(args)
-
params = Hash[parameterize_args(args)]
-
missing_keys = missing_keys(params)
-
-
unless missing_keys.empty?
-
raise_generation_error(params, missing_keys)
-
end
-
-
@optimized_path.map{ |segment| replace_segment(params, segment) }.join
-
end
-
-
1
def replace_segment(params, segment)
-
Symbol === segment ? @klass.escape_fragment(params[segment]) : segment
-
end
-
-
1
def optimize_routes_generation?(t)
-
t.send(:optimize_routes_generation?)
-
end
-
-
1
def parameterize_args(args)
-
@required_parts.zip(args.map(&:to_param))
-
end
-
-
1
def missing_keys(args)
-
args.select{ |part, arg| arg.nil? || arg.empty? }.keys
-
end
-
-
1
def raise_generation_error(args, missing_keys)
-
constraints = Hash[@route.requirements.merge(args).sort]
-
message = "No route matches #{constraints.inspect}"
-
message << " missing required keys: #{missing_keys.sort.inspect}"
-
-
raise ActionController::UrlGenerationError, message
-
end
-
end
-
-
1
def initialize(route, options)
-
76
@options = options
-
76
@segment_keys = route.segment_keys.uniq
-
76
@route = route
-
end
-
-
1
def call(t, args)
-
t.url_for(handle_positional_args(t, args, @options, @segment_keys))
-
end
-
-
1
def handle_positional_args(t, args, options, keys)
-
inner_options = args.extract_options!
-
result = options.dup
-
-
if args.size > 0
-
if args.size < keys.size - 1 # take format into account
-
keys -= t.url_options.keys if t.respond_to?(:url_options)
-
keys -= options.keys
-
end
-
keys -= inner_options.keys
-
result.merge!(Hash[keys.zip(args)])
-
end
-
-
result.merge!(inner_options)
-
end
-
end
-
-
1
private
-
# Create a url helper allowing ordered parameters to be associated
-
# with corresponding dynamic segments, so you can do:
-
#
-
# foo_url(bar, baz, bang)
-
#
-
# Instead of:
-
#
-
# foo_url(bar: bar, baz: baz, bang: bang)
-
#
-
# Also allow options hash, so you can do:
-
#
-
# foo_url(bar, baz, bang, sort_by: 'baz')
-
#
-
1
def define_url_helper(route, name, options)
-
76
helper = UrlHelper.create(route, options.dup)
-
-
76
@module.remove_possible_method name
-
76
@module.module_eval do
-
76
define_method(name) do |*args|
-
helper.call self, args
-
end
-
end
-
-
76
helpers << name
-
end
-
-
1
def define_named_route_methods(name, route)
-
38
define_url_helper route, :"#{name}_path",
-
route.defaults.merge(:use_route => name, :only_path => true)
-
38
define_url_helper route, :"#{name}_url",
-
route.defaults.merge(:use_route => name, :only_path => false)
-
end
-
end
-
-
1
attr_accessor :formatter, :set, :named_routes, :default_scope, :router
-
1
attr_accessor :disable_clear_and_finalize, :resources_path_names
-
1
attr_accessor :default_url_options, :request_class
-
-
1
alias :routes :set
-
-
1
def self.default_resources_path_names
-
2
{ :new => 'new', :edit => 'edit' }
-
end
-
-
1
def initialize(request_class = ActionDispatch::Request)
-
2
self.named_routes = NamedRouteCollection.new
-
2
self.resources_path_names = self.class.default_resources_path_names.dup
-
2
self.default_url_options = {}
-
2
self.request_class = request_class
-
-
2
@append = []
-
2
@prepend = []
-
2
@disable_clear_and_finalize = false
-
2
@finalized = false
-
-
2
@set = Journey::Routes.new
-
2
@router = Journey::Router.new(@set, {
-
:parameters_key => PARAMETERS_KEY,
-
:request_class => request_class})
-
2
@formatter = Journey::Formatter.new @set
-
end
-
-
1
def draw(&block)
-
1
clear! unless @disable_clear_and_finalize
-
1
eval_block(block)
-
1
finalize! unless @disable_clear_and_finalize
-
nil
-
end
-
-
1
def append(&block)
-
@append << block
-
end
-
-
1
def prepend(&block)
-
1
@prepend << block
-
end
-
-
1
def eval_block(block)
-
2
if block.arity == 1
-
raise "You are using the old router DSL which has been removed in Rails 3.1. " <<
-
"Please check how to update your routes file at: http://www.engineyard.com/blog/2010/the-lowdown-on-routes-in-rails-3/"
-
end
-
2
mapper = Mapper.new(self)
-
2
if default_scope
-
mapper.with_default_scope(default_scope, &block)
-
else
-
2
mapper.instance_exec(&block)
-
end
-
end
-
-
1
def finalize!
-
2
return if @finalized
-
2
@append.each { |blk| eval_block(blk) }
-
2
@finalized = true
-
end
-
-
1
def clear!
-
2
@finalized = false
-
2
named_routes.clear
-
2
set.clear
-
2
formatter.clear
-
3
@prepend.each { |blk| eval_block(blk) }
-
end
-
-
1
module MountedHelpers #:nodoc:
-
1
extend ActiveSupport::Concern
-
1
include UrlFor
-
end
-
-
# Contains all the mounted helpers across different
-
# engines and the `main_app` helper for the application.
-
# You can include this in your classes if you want to
-
# access routes for other engines.
-
1
def mounted_helpers
-
3
MountedHelpers
-
end
-
-
1
def define_mounted_helper(name)
-
1
return if MountedHelpers.method_defined?(name)
-
-
1
routes = self
-
1
MountedHelpers.class_eval do
-
1
define_method "_#{name}" do
-
RoutesProxy.new(routes, _routes_context)
-
end
-
end
-
-
1
MountedHelpers.class_eval(<<-RUBY, __FILE__, __LINE__ + 1)
-
def #{name}
-
@_#{name} ||= _#{name}
-
end
-
RUBY
-
end
-
-
1
def url_helpers
-
@url_helpers ||= begin
-
1
routes = self
-
-
1
Module.new do
-
1
extend ActiveSupport::Concern
-
1
include UrlFor
-
-
# Define url_for in the singleton level so one can do:
-
# Rails.application.routes.url_helpers.url_for(args)
-
1
@_routes = routes
-
1
class << self
-
1
delegate :url_for, :optimize_routes_generation?, :to => '@_routes'
-
end
-
-
# Make named_routes available in the module singleton
-
# as well, so one can do:
-
# Rails.application.routes.url_helpers.posts_path
-
1
extend routes.named_routes.module
-
-
# Any class that includes this module will get all
-
# named routes...
-
1
include routes.named_routes.module
-
-
# plus a singleton class method called _routes ...
-
1
included do
-
2
singleton_class.send(:redefine_method, :_routes) { routes }
-
end
-
-
# And an instance method _routes. Note that
-
# UrlFor (included in this module) add extra
-
# conveniences for working with @_routes.
-
1
define_method(:_routes) { @_routes || routes }
-
end
-
2
end
-
end
-
-
1
def empty?
-
routes.empty?
-
end
-
-
1
def add_route(app, conditions = {}, requirements = {}, defaults = {}, name = nil, anchor = true)
-
73
raise ArgumentError, "Invalid route name: '#{name}'" unless name.blank? || name.to_s.match(/^[_a-z]\w*$/i)
-
-
73
if name && named_routes[name]
-
raise ArgumentError, "Invalid route name, already in use: '#{name}' \n" \
-
"You may have defined two routes with the same name using the `:as` option, or " \
-
"you may be overriding a route already defined by a resource with the same naming. " \
-
"For the latter, you can restrict the routes created with `resources` as explained here: \n" \
-
"http://guides.rubyonrails.org/routing.html#restricting-the-routes-created"
-
end
-
-
73
path = build_path(conditions.delete(:path_info), requirements, SEPARATORS, anchor)
-
174
conditions = build_conditions(conditions, path.names.map { |x| x.to_sym })
-
-
73
route = @set.add_route(app, path, conditions, defaults, name)
-
73
named_routes[name] = route if name
-
73
route
-
end
-
-
1
def build_path(path, requirements, separators, anchor)
-
73
strexp = Journey::Router::Strexp.new(
-
path,
-
requirements,
-
SEPARATORS,
-
anchor)
-
-
73
pattern = Journey::Path::Pattern.new(strexp)
-
-
73
builder = Journey::GTG::Builder.new pattern.spec
-
-
# Get all the symbol nodes followed by literals that are not the
-
# dummy node.
-
73
symbols = pattern.spec.grep(Journey::Nodes::Symbol).find_all { |n|
-
101
builder.followpos(n).first.literal?
-
}
-
-
# Get all the symbol nodes preceded by literals.
-
73
symbols.concat pattern.spec.find_all(&:literal?).map { |n|
-
99
builder.followpos(n).first
-
}.find_all(&:symbol?)
-
-
73
symbols.each { |x|
-
x.regexp = /(?:#{Regexp.union(x.regexp, '-')})+/
-
}
-
-
73
pattern
-
end
-
1
private :build_path
-
-
1
def build_conditions(current_conditions, path_values)
-
73
conditions = current_conditions.dup
-
-
# Rack-Mount requires that :request_method be a regular expression.
-
# :request_method represents the HTTP verb that matches this route.
-
#
-
# Here we munge values before they get sent on to rack-mount.
-
73
verbs = conditions[:request_method] || []
-
73
unless verbs.empty?
-
72
conditions[:request_method] = %r[^#{verbs.join('|')}$]
-
end
-
-
73
conditions.keep_if do |k, _|
-
145
k == :action || k == :controller || k == :required_defaults ||
-
@request_class.public_method_defined?(k) || path_values.include?(k)
-
end
-
end
-
1
private :build_conditions
-
-
1
class Generator #:nodoc:
-
1
PARAMETERIZE = lambda do |name, value|
-
if name == :controller
-
value
-
elsif value.is_a?(Array)
-
value.map { |v| v.to_param }.join('/')
-
elsif param = value.to_param
-
param
-
end
-
end
-
-
1
attr_reader :options, :recall, :set, :named_route
-
-
1
def initialize(options, recall, set)
-
@named_route = options.delete(:use_route)
-
@options = options.dup
-
@recall = recall.dup
-
@set = set
-
-
normalize_recall!
-
normalize_options!
-
normalize_controller_action_id!
-
use_relative_controller!
-
normalize_controller!
-
normalize_action!
-
end
-
-
1
def controller
-
@options[:controller]
-
end
-
-
1
def current_controller
-
@recall[:controller]
-
end
-
-
1
def use_recall_for(key)
-
if @recall[key] && (!@options.key?(key) || @options[key] == @recall[key])
-
if !named_route_exists? || segment_keys.include?(key)
-
@options[key] = @recall.delete(key)
-
end
-
end
-
end
-
-
# Set 'index' as default action for recall
-
1
def normalize_recall!
-
@recall[:action] ||= 'index'
-
end
-
-
1
def normalize_options!
-
# If an explicit :controller was given, always make :action explicit
-
# too, so that action expiry works as expected for things like
-
#
-
# generate({controller: 'content'}, {controller: 'content', action: 'show'})
-
#
-
# (the above is from the unit tests). In the above case, because the
-
# controller was explicitly given, but no action, the action is implied to
-
# be "index", not the recalled action of "show".
-
-
if options[:controller]
-
options[:action] ||= 'index'
-
options[:controller] = options[:controller].to_s
-
end
-
-
if options.key?(:action)
-
options[:action] = (options[:action] || 'index').to_s
-
end
-
end
-
-
# This pulls :controller, :action, and :id out of the recall.
-
# The recall key is only used if there is no key in the options
-
# or if the key in the options is identical. If any of
-
# :controller, :action or :id is not found, don't pull any
-
# more keys from the recall.
-
1
def normalize_controller_action_id!
-
use_recall_for(:controller) or return
-
use_recall_for(:action) or return
-
use_recall_for(:id)
-
end
-
-
# if the current controller is "foo/bar/baz" and controller: "baz/bat"
-
# is specified, the controller becomes "foo/baz/bat"
-
1
def use_relative_controller!
-
if !named_route && different_controller? && !controller.start_with?("/")
-
old_parts = current_controller.split('/')
-
size = controller.count("/") + 1
-
parts = old_parts[0...-size] << controller
-
@options[:controller] = parts.join("/")
-
end
-
end
-
-
# Remove leading slashes from controllers
-
1
def normalize_controller!
-
@options[:controller] = controller.sub(%r{^/}, '') if controller
-
end
-
-
# Move 'index' action from options to recall
-
1
def normalize_action!
-
if @options[:action] == 'index'
-
@recall[:action] = @options.delete(:action)
-
end
-
end
-
-
# Generates a path from routes, returns [path, params].
-
# If no route is generated the formatter will raise ActionController::UrlGenerationError
-
1
def generate
-
@set.formatter.generate(:path_info, named_route, options, recall, PARAMETERIZE)
-
end
-
-
1
def different_controller?
-
return false unless current_controller
-
controller.to_param != current_controller.to_param
-
end
-
-
1
private
-
1
def named_route_exists?
-
named_route && set.named_routes[named_route]
-
end
-
-
1
def segment_keys
-
set.named_routes[named_route].segment_keys
-
end
-
end
-
-
# Generate the path indicated by the arguments, and return an array of
-
# the keys that were not used to generate it.
-
1
def extra_keys(options, recall={})
-
generate_extras(options, recall).last
-
end
-
-
1
def generate_extras(options, recall={})
-
path, params = generate(options, recall)
-
return path, params.keys
-
end
-
-
1
def generate(options, recall = {})
-
Generator.new(options, recall, self).generate
-
end
-
-
1
RESERVED_OPTIONS = [:host, :protocol, :port, :subdomain, :domain, :tld_length,
-
:trailing_slash, :anchor, :params, :only_path, :script_name,
-
:original_script_name]
-
-
1
def mounted?
-
false
-
end
-
-
1
def optimize_routes_generation?
-
!mounted? && default_url_options.empty?
-
end
-
-
1
def _generate_prefix(options = {})
-
nil
-
end
-
-
# The +options+ argument must be +nil+ or a hash whose keys are *symbols*.
-
1
def url_for(options)
-
options = default_url_options.merge(options || {})
-
-
user, password = extract_authentication(options)
-
recall = options.delete(:_recall)
-
-
original_script_name = options.delete(:original_script_name).presence
-
script_name = options.delete(:script_name).presence || _generate_prefix(options)
-
-
if script_name && original_script_name
-
script_name = original_script_name + script_name
-
end
-
-
path_options = options.except(*RESERVED_OPTIONS)
-
path_options = yield(path_options) if block_given?
-
-
path, params = generate(path_options, recall || {})
-
params.merge!(options[:params] || {})
-
-
ActionDispatch::Http::URL.url_for(options.merge!({
-
:path => path,
-
:script_name => script_name,
-
:params => params,
-
:user => user,
-
:password => password
-
}))
-
end
-
-
1
def call(env)
-
@router.call(env)
-
end
-
-
1
def recognize_path(path, environment = {})
-
method = (environment[:method] || "GET").to_s.upcase
-
path = Journey::Router::Utils.normalize_path(path) unless path =~ %r{://}
-
extras = environment[:extras] || {}
-
-
begin
-
env = Rack::MockRequest.env_for(path, {:method => method})
-
rescue URI::InvalidURIError => e
-
raise ActionController::RoutingError, e.message
-
end
-
-
req = @request_class.new(env)
-
@router.recognize(req) do |route, _matches, params|
-
params.merge!(extras)
-
params.each do |key, value|
-
if value.is_a?(String)
-
value = value.dup.force_encoding(Encoding::BINARY)
-
params[key] = URI.parser.unescape(value)
-
end
-
end
-
old_params = env[::ActionDispatch::Routing::RouteSet::PARAMETERS_KEY]
-
env[::ActionDispatch::Routing::RouteSet::PARAMETERS_KEY] = (old_params || {}).merge(params)
-
dispatcher = route.app
-
while dispatcher.is_a?(Mapper::Constraints) && dispatcher.matches?(env) do
-
dispatcher = dispatcher.app
-
end
-
-
if dispatcher.is_a?(Dispatcher)
-
if dispatcher.controller(params, false)
-
dispatcher.prepare_params!(params)
-
return params
-
else
-
raise ActionController::RoutingError, "A route matches #{path.inspect}, but references missing controller: #{params[:controller].camelize}Controller"
-
end
-
end
-
end
-
-
raise ActionController::RoutingError, "No route matches #{path.inspect}"
-
end
-
-
1
private
-
-
1
def extract_authentication(options)
-
if options[:user] && options[:password]
-
[options.delete(:user), options.delete(:password)]
-
else
-
nil
-
end
-
end
-
-
end
-
end
-
end
-
1
require 'active_support/core_ext/array/extract_options'
-
-
1
module ActionDispatch
-
1
module Routing
-
1
class RoutesProxy #:nodoc:
-
1
include ActionDispatch::Routing::UrlFor
-
-
1
attr_accessor :scope, :routes
-
1
alias :_routes :routes
-
-
1
def initialize(routes, scope)
-
@routes, @scope = routes, scope
-
end
-
-
1
def url_options
-
scope.send(:_with_routes, routes) do
-
scope.url_options
-
end
-
end
-
-
1
def respond_to?(method, include_private = false)
-
super || routes.url_helpers.respond_to?(method)
-
end
-
-
1
def method_missing(method, *args)
-
if routes.url_helpers.respond_to?(method)
-
self.class.class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{method}(*args)
-
options = args.extract_options!
-
args << url_options.merge((options || {}).symbolize_keys)
-
routes.url_helpers.#{method}(*args)
-
end
-
RUBY
-
send(method, *args)
-
else
-
super
-
end
-
end
-
end
-
end
-
end
-
1
module ActionDispatch
-
1
module Routing
-
# In <tt>config/routes.rb</tt> you define URL-to-controller mappings, but the reverse
-
# is also possible: an URL can be generated from one of your routing definitions.
-
# URL generation functionality is centralized in this module.
-
#
-
# See ActionDispatch::Routing for general information about routing and routes.rb.
-
#
-
# <b>Tip:</b> If you need to generate URLs from your models or some other place,
-
# then ActionController::UrlFor is what you're looking for. Read on for
-
# an introduction. In general, this module should not be included on its own,
-
# as it is usually included by url_helpers (as in Rails.application.routes.url_helpers).
-
#
-
# == URL generation from parameters
-
#
-
# As you may know, some functions, such as ActionController::Base#url_for
-
# and ActionView::Helpers::UrlHelper#link_to, can generate URLs given a set
-
# of parameters. For example, you've probably had the chance to write code
-
# like this in one of your views:
-
#
-
# <%= link_to('Click here', controller: 'users',
-
# action: 'new', message: 'Welcome!') %>
-
# # => <a href="/users/new?message=Welcome%21">Click here</a>
-
#
-
# link_to, and all other functions that require URL generation functionality,
-
# actually use ActionController::UrlFor under the hood. And in particular,
-
# they use the ActionController::UrlFor#url_for method. One can generate
-
# the same path as the above example by using the following code:
-
#
-
# include UrlFor
-
# url_for(controller: 'users',
-
# action: 'new',
-
# message: 'Welcome!',
-
# only_path: true)
-
# # => "/users/new?message=Welcome%21"
-
#
-
# Notice the <tt>only_path: true</tt> part. This is because UrlFor has no
-
# information about the website hostname that your Rails app is serving. So if you
-
# want to include the hostname as well, then you must also pass the <tt>:host</tt>
-
# argument:
-
#
-
# include UrlFor
-
# url_for(controller: 'users',
-
# action: 'new',
-
# message: 'Welcome!',
-
# host: 'www.example.com')
-
# # => "http://www.example.com/users/new?message=Welcome%21"
-
#
-
# By default, all controllers and views have access to a special version of url_for,
-
# that already knows what the current hostname is. So if you use url_for in your
-
# controllers or your views, then you don't need to explicitly pass the <tt>:host</tt>
-
# argument.
-
#
-
# For convenience reasons, mailers provide a shortcut for ActionController::UrlFor#url_for.
-
# So within mailers, you only have to type 'url_for' instead of 'ActionController::UrlFor#url_for'
-
# in full. However, mailers don't have hostname information, and that's why you'll still
-
# have to specify the <tt>:host</tt> argument when generating URLs in mailers.
-
#
-
#
-
# == URL generation for named routes
-
#
-
# UrlFor also allows one to access methods that have been auto-generated from
-
# named routes. For example, suppose that you have a 'users' resource in your
-
# <tt>config/routes.rb</tt>:
-
#
-
# resources :users
-
#
-
# This generates, among other things, the method <tt>users_path</tt>. By default,
-
# this method is accessible from your controllers, views and mailers. If you need
-
# to access this auto-generated method from other places (such as a model), then
-
# you can do that by including Rails.application.routes.url_helpers in your class:
-
#
-
# class User < ActiveRecord::Base
-
# include Rails.application.routes.url_helpers
-
#
-
# def base_uri
-
# user_path(self)
-
# end
-
# end
-
#
-
# User.find(1).base_uri # => "/users/1"
-
#
-
1
module UrlFor
-
1
extend ActiveSupport::Concern
-
1
include PolymorphicRoutes
-
-
1
included do
-
7
unless method_defined?(:default_url_options)
-
# Including in a class uses an inheritable hash. Modules get a plain hash.
-
6
if respond_to?(:class_attribute)
-
5
class_attribute :default_url_options
-
else
-
1
mattr_writer :default_url_options
-
end
-
-
6
self.default_url_options = {}
-
end
-
-
7
include(*_url_for_modules) if respond_to?(:_url_for_modules)
-
end
-
-
1
def initialize(*)
-
@_routes = nil
-
super
-
end
-
-
# Hook overridden in controller to add request information
-
# with `default_url_options`. Application logic should not
-
# go into url_options.
-
1
def url_options
-
default_url_options
-
end
-
-
# Generate a url based on the options provided, default_url_options and the
-
# routes defined in routes.rb. The following options are supported:
-
#
-
# * <tt>:only_path</tt> - If true, the relative url is returned. Defaults to +false+.
-
# * <tt>:protocol</tt> - The protocol to connect to. Defaults to 'http'.
-
# * <tt>:host</tt> - Specifies the host the link should be targeted at.
-
# If <tt>:only_path</tt> is false, this option must be
-
# provided either explicitly, or via +default_url_options+.
-
# * <tt>:subdomain</tt> - Specifies the subdomain of the link, using the +tld_length+
-
# to split the subdomain from the host.
-
# If false, removes all subdomains from the host part of the link.
-
# * <tt>:domain</tt> - Specifies the domain of the link, using the +tld_length+
-
# to split the domain from the host.
-
# * <tt>:tld_length</tt> - Number of labels the TLD id composed of, only used if
-
# <tt>:subdomain</tt> or <tt>:domain</tt> are supplied. Defaults to
-
# <tt>ActionDispatch::Http::URL.tld_length</tt>, which in turn defaults to 1.
-
# * <tt>:port</tt> - Optionally specify the port to connect to.
-
# * <tt>:anchor</tt> - An anchor name to be appended to the path.
-
# * <tt>:trailing_slash</tt> - If true, adds a trailing slash, as in "/archive/2009/"
-
# * <tt>:script_name</tt> - Specifies application path relative to domain root. If provided, prepends application path.
-
#
-
# Any other key (<tt>:controller</tt>, <tt>:action</tt>, etc.) given to
-
# +url_for+ is forwarded to the Routes module.
-
#
-
# url_for controller: 'tasks', action: 'testing', host: 'somehost.org', port: '8080'
-
# # => 'http://somehost.org:8080/tasks/testing'
-
# url_for controller: 'tasks', action: 'testing', host: 'somehost.org', anchor: 'ok', only_path: true
-
# # => '/tasks/testing#ok'
-
# url_for controller: 'tasks', action: 'testing', trailing_slash: true
-
# # => 'http://somehost.org/tasks/testing/'
-
# url_for controller: 'tasks', action: 'testing', host: 'somehost.org', number: '33'
-
# # => 'http://somehost.org/tasks/testing?number=33'
-
# url_for controller: 'tasks', action: 'testing', host: 'somehost.org', script_name: "/myapp"
-
# # => 'http://somehost.org/myapp/tasks/testing'
-
# url_for controller: 'tasks', action: 'testing', host: 'somehost.org', script_name: "/myapp", only_path: true
-
# # => '/myapp/tasks/testing'
-
1
def url_for(options = nil)
-
case options
-
when nil
-
_routes.url_for(url_options.symbolize_keys)
-
when Hash
-
_routes.url_for(options.symbolize_keys.reverse_merge!(url_options))
-
when String
-
options
-
when Array
-
polymorphic_url(options, options.extract_options!)
-
else
-
polymorphic_url(options)
-
end
-
end
-
-
1
protected
-
-
1
def optimize_routes_generation?
-
return @_optimized_routes if defined?(@_optimized_routes)
-
@_optimized_routes = _routes.optimize_routes_generation? && default_url_options.empty?
-
end
-
-
1
def _with_routes(routes)
-
old_routes, @_routes = @_routes, routes
-
yield
-
ensure
-
@_routes = old_routes
-
end
-
-
1
def _routes_context
-
self
-
end
-
end
-
end
-
end
-
1
module ActionDispatch
-
1
module Assertions
-
1
autoload :DomAssertions, 'action_dispatch/testing/assertions/dom'
-
1
autoload :ResponseAssertions, 'action_dispatch/testing/assertions/response'
-
1
autoload :RoutingAssertions, 'action_dispatch/testing/assertions/routing'
-
1
autoload :SelectorAssertions, 'action_dispatch/testing/assertions/selector'
-
1
autoload :TagAssertions, 'action_dispatch/testing/assertions/tag'
-
-
1
extend ActiveSupport::Concern
-
-
1
include DomAssertions
-
1
include ResponseAssertions
-
1
include RoutingAssertions
-
1
include SelectorAssertions
-
1
include TagAssertions
-
end
-
end
-
-
1
require 'action_view/vendor/html-scanner'
-
-
1
module ActionDispatch
-
1
module Assertions
-
1
module DomAssertions
-
# \Test two HTML strings for equivalency (e.g., identical up to reordering of attributes)
-
#
-
# # assert that the referenced method generates the appropriate HTML string
-
# assert_dom_equal '<a href="http://www.example.com">Apples</a>', link_to("Apples", "http://www.example.com")
-
1
def assert_dom_equal(expected, actual, message = nil)
-
expected_dom = HTML::Document.new(expected).root
-
actual_dom = HTML::Document.new(actual).root
-
assert_equal expected_dom, actual_dom, message
-
end
-
-
# The negated form of +assert_dom_equivalent+.
-
#
-
# # assert that the referenced method does not generate the specified HTML string
-
# assert_dom_not_equal '<a href="http://www.example.com">Apples</a>', link_to("Oranges", "http://www.example.com")
-
1
def assert_dom_not_equal(expected, actual, message = nil)
-
expected_dom = HTML::Document.new(expected).root
-
actual_dom = HTML::Document.new(actual).root
-
assert_not_equal expected_dom, actual_dom, message
-
end
-
end
-
end
-
end
-
-
1
module ActionDispatch
-
1
module Assertions
-
# A small suite of assertions that test responses from \Rails applications.
-
1
module ResponseAssertions
-
# Asserts that the response is one of the following types:
-
#
-
# * <tt>:success</tt> - Status code was in the 200-299 range
-
# * <tt>:redirect</tt> - Status code was in the 300-399 range
-
# * <tt>:missing</tt> - Status code was 404
-
# * <tt>:error</tt> - Status code was in the 500-599 range
-
#
-
# You can also pass an explicit status number like <tt>assert_response(501)</tt>
-
# or its symbolic equivalent <tt>assert_response(:not_implemented)</tt>.
-
# See Rack::Utils::SYMBOL_TO_STATUS_CODE for a full list.
-
#
-
# # assert that the response was a redirection
-
# assert_response :redirect
-
#
-
# # assert that the response code was status code 401 (unauthorized)
-
# assert_response 401
-
1
def assert_response(type, message = nil)
-
message ||= "Expected response to be a <#{type}>, but was <#{@response.response_code}>"
-
-
if Symbol === type
-
if [:success, :missing, :redirect, :error].include?(type)
-
assert @response.send("#{type}?"), message
-
else
-
code = Rack::Utils::SYMBOL_TO_STATUS_CODE[type]
-
if code.nil?
-
raise ArgumentError, "Invalid response type :#{type}"
-
end
-
assert_equal code, @response.response_code, message
-
end
-
else
-
assert_equal type, @response.response_code, message
-
end
-
end
-
-
# Assert that the redirection options passed in match those of the redirect called in the latest action.
-
# This match can be partial, such that <tt>assert_redirected_to(controller: "weblog")</tt> will also
-
# match the redirection of <tt>redirect_to(controller: "weblog", action: "show")</tt> and so on.
-
#
-
# # assert that the redirection was to the "index" action on the WeblogController
-
# assert_redirected_to controller: "weblog", action: "index"
-
#
-
# # assert that the redirection was to the named route login_url
-
# assert_redirected_to login_url
-
#
-
# # assert that the redirection was to the url for @customer
-
# assert_redirected_to @customer
-
#
-
# # asserts that the redirection matches the regular expression
-
# assert_redirected_to %r(\Ahttp://example.org)
-
1
def assert_redirected_to(options = {}, message=nil)
-
assert_response(:redirect, message)
-
return true if options === @response.location
-
-
redirect_is = normalize_argument_to_redirection(@response.location)
-
redirect_expected = normalize_argument_to_redirection(options)
-
-
message ||= "Expected response to be a redirect to <#{redirect_expected}> but was a redirect to <#{redirect_is}>"
-
assert_operator redirect_expected, :===, redirect_is, message
-
end
-
-
1
private
-
# Proxy to to_param if the object will respond to it.
-
1
def parameterize(value)
-
value.respond_to?(:to_param) ? value.to_param : value
-
end
-
-
1
def normalize_argument_to_redirection(fragment)
-
if Regexp === fragment
-
fragment
-
else
-
@controller._compute_redirect_to_location(fragment)
-
end
-
end
-
end
-
end
-
end
-
1
require 'uri'
-
1
require 'active_support/core_ext/hash/indifferent_access'
-
1
require 'active_support/core_ext/string/access'
-
1
require 'action_controller/metal/exceptions'
-
-
1
module ActionDispatch
-
1
module Assertions
-
# Suite of assertions to test routes generated by \Rails and the handling of requests made to them.
-
1
module RoutingAssertions
-
# Asserts that the routing of the given +path+ was handled correctly and that the parsed options (given in the +expected_options+ hash)
-
# match +path+. Basically, it asserts that \Rails recognizes the route given by +expected_options+.
-
#
-
# Pass a hash in the second argument (+path+) to specify the request method. This is useful for routes
-
# requiring a specific HTTP method. The hash should contain a :path with the incoming request path
-
# and a :method containing the required HTTP verb.
-
#
-
# # assert that POSTing to /items will call the create action on ItemsController
-
# assert_recognizes({controller: 'items', action: 'create'}, {path: 'items', method: :post})
-
#
-
# You can also pass in +extras+ with a hash containing URL parameters that would normally be in the query string. This can be used
-
# to assert that values in the query string string will end up in the params hash correctly. To test query strings you must use the
-
# extras argument, appending the query string on the path directly will not work. For example:
-
#
-
# # assert that a path of '/items/list/1?view=print' returns the correct options
-
# assert_recognizes({controller: 'items', action: 'list', id: '1', view: 'print'}, 'items/list/1', { view: "print" })
-
#
-
# The +message+ parameter allows you to pass in an error message that is displayed upon failure.
-
#
-
# # Check the default route (i.e., the index action)
-
# assert_recognizes({controller: 'items', action: 'index'}, 'items')
-
#
-
# # Test a specific action
-
# assert_recognizes({controller: 'items', action: 'list'}, 'items/list')
-
#
-
# # Test an action with a parameter
-
# assert_recognizes({controller: 'items', action: 'destroy', id: '1'}, 'items/destroy/1')
-
#
-
# # Test a custom route
-
# assert_recognizes({controller: 'items', action: 'show', id: '1'}, 'view/item1')
-
1
def assert_recognizes(expected_options, path, extras={}, msg=nil)
-
request = recognized_request_for(path, extras)
-
-
expected_options = expected_options.clone
-
-
expected_options.stringify_keys!
-
-
msg = message(msg, "") {
-
sprintf("The recognized options <%s> did not match <%s>, difference:",
-
request.path_parameters, expected_options)
-
}
-
-
assert_equal(expected_options, request.path_parameters, msg)
-
end
-
-
# Asserts that the provided options can be used to generate the provided path. This is the inverse of +assert_recognizes+.
-
# The +extras+ parameter is used to tell the request the names and values of additional request parameters that would be in
-
# a query string. The +message+ parameter allows you to specify a custom error message for assertion failures.
-
#
-
# The +defaults+ parameter is unused.
-
#
-
# # Asserts that the default action is generated for a route with no action
-
# assert_generates "/items", controller: "items", action: "index"
-
#
-
# # Tests that the list action is properly routed
-
# assert_generates "/items/list", controller: "items", action: "list"
-
#
-
# # Tests the generation of a route with a parameter
-
# assert_generates "/items/list/1", { controller: "items", action: "list", id: "1" }
-
#
-
# # Asserts that the generated route gives us our custom route
-
# assert_generates "changesets/12", { controller: 'scm', action: 'show_diff', revision: "12" }
-
1
def assert_generates(expected_path, options, defaults={}, extras = {}, message=nil)
-
if expected_path =~ %r{://}
-
fail_on(URI::InvalidURIError) do
-
uri = URI.parse(expected_path)
-
expected_path = uri.path.to_s.empty? ? "/" : uri.path
-
end
-
else
-
expected_path = "/#{expected_path}" unless expected_path.first == '/'
-
end
-
# Load routes.rb if it hasn't been loaded.
-
-
generated_path, extra_keys = @routes.generate_extras(options, defaults)
-
found_extras = options.reject { |k, _| ! extra_keys.include? k }
-
-
msg = message || sprintf("found extras <%s>, not <%s>", found_extras, extras)
-
assert_equal(extras, found_extras, msg)
-
-
msg = message || sprintf("The generated path <%s> did not match <%s>", generated_path,
-
expected_path)
-
assert_equal(expected_path, generated_path, msg)
-
end
-
-
# Asserts that path and options match both ways; in other words, it verifies that <tt>path</tt> generates
-
# <tt>options</tt> and then that <tt>options</tt> generates <tt>path</tt>. This essentially combines +assert_recognizes+
-
# and +assert_generates+ into one step.
-
#
-
# The +extras+ hash allows you to specify options that would normally be provided as a query string to the action. The
-
# +message+ parameter allows you to specify a custom error message to display upon failure.
-
#
-
# # Assert a basic route: a controller with the default action (index)
-
# assert_routing '/home', controller: 'home', action: 'index'
-
#
-
# # Test a route generated with a specific controller, action, and parameter (id)
-
# assert_routing '/entries/show/23', controller: 'entries', action: 'show', id: 23
-
#
-
# # Assert a basic route (controller + default action), with an error message if it fails
-
# assert_routing '/store', { controller: 'store', action: 'index' }, {}, {}, 'Route for store index not generated properly'
-
#
-
# # Tests a route, providing a defaults hash
-
# assert_routing 'controller/action/9', {id: "9", item: "square"}, {controller: "controller", action: "action"}, {}, {item: "square"}
-
#
-
# # Tests a route with a HTTP method
-
# assert_routing({ method: 'put', path: '/product/321' }, { controller: "product", action: "update", id: "321" })
-
1
def assert_routing(path, options, defaults={}, extras={}, message=nil)
-
assert_recognizes(options, path, extras, message)
-
-
controller, default_controller = options[:controller], defaults[:controller]
-
if controller && controller.include?(?/) && default_controller && default_controller.include?(?/)
-
options[:controller] = "/#{controller}"
-
end
-
-
generate_options = options.dup.delete_if{ |k, _| defaults.key?(k) }
-
assert_generates(path.is_a?(Hash) ? path[:path] : path, generate_options, defaults, extras, message)
-
end
-
-
# A helper to make it easier to test different route configurations.
-
# This method temporarily replaces @routes
-
# with a new RouteSet instance.
-
#
-
# The new instance is yielded to the passed block. Typically the block
-
# will create some routes using <tt>set.draw { match ... }</tt>:
-
#
-
# with_routing do |set|
-
# set.draw do
-
# resources :users
-
# end
-
# assert_equal "/users", users_path
-
# end
-
#
-
1
def with_routing
-
old_routes, @routes = @routes, ActionDispatch::Routing::RouteSet.new
-
if defined?(@controller) && @controller
-
old_controller, @controller = @controller, @controller.clone
-
_routes = @routes
-
-
# Unfortunately, there is currently an abstraction leak between AC::Base
-
# and AV::Base which requires having the URL helpers in both AC and AV.
-
# To do this safely at runtime for tests, we need to bump up the helper serial
-
# to that the old AV subclass isn't cached.
-
#
-
# TODO: Make this unnecessary
-
@controller.singleton_class.send(:include, _routes.url_helpers)
-
@controller.view_context_class = Class.new(@controller.view_context_class) do
-
include _routes.url_helpers
-
end
-
end
-
yield @routes
-
ensure
-
@routes = old_routes
-
if defined?(@controller) && @controller
-
@controller = old_controller
-
end
-
end
-
-
# ROUTES TODO: These assertions should really work in an integration context
-
1
def method_missing(selector, *args, &block)
-
if defined?(@controller) && @controller && @routes && @routes.named_routes.helpers.include?(selector)
-
@controller.send(selector, *args, &block)
-
else
-
super
-
end
-
end
-
-
1
private
-
# Recognizes the route for a given path.
-
1
def recognized_request_for(path, extras = {})
-
if path.is_a?(Hash)
-
method = path[:method]
-
path = path[:path]
-
else
-
method = :get
-
end
-
-
# Assume given controller
-
request = ActionController::TestRequest.new
-
-
if path =~ %r{://}
-
fail_on(URI::InvalidURIError) do
-
uri = URI.parse(path)
-
request.env["rack.url_scheme"] = uri.scheme || "http"
-
request.host = uri.host if uri.host
-
request.port = uri.port if uri.port
-
request.path = uri.path.to_s.empty? ? "/" : uri.path
-
end
-
else
-
path = "/#{path}" unless path.first == "/"
-
request.path = path
-
end
-
-
request.request_method = method if method
-
-
params = fail_on(ActionController::RoutingError) do
-
@routes.recognize_path(path, { :method => method, :extras => extras })
-
end
-
request.path_parameters = params.with_indifferent_access
-
-
request
-
end
-
-
1
def fail_on(exception_class)
-
yield
-
rescue exception_class => e
-
raise Minitest::Assertion, e.message
-
end
-
end
-
end
-
end
-
1
require 'action_view/vendor/html-scanner'
-
1
require 'active_support/core_ext/object/inclusion'
-
-
#--
-
# Copyright (c) 2006 Assaf Arkin (http://labnotes.org)
-
# Under MIT and/or CC By license.
-
#++
-
-
1
module ActionDispatch
-
1
module Assertions
-
1
NO_STRIP = %w{pre script style textarea}
-
-
# Adds the +assert_select+ method for use in Rails functional
-
# test cases, which can be used to make assertions on the response HTML of a controller
-
# action. You can also call +assert_select+ within another +assert_select+ to
-
# make assertions on elements selected by the enclosing assertion.
-
#
-
# Use +css_select+ to select elements without making an assertions, either
-
# from the response HTML or elements selected by the enclosing assertion.
-
#
-
# In addition to HTML responses, you can make the following assertions:
-
#
-
# * +assert_select_encoded+ - Assertions on HTML encoded inside XML, for example for dealing with feed item descriptions.
-
# * +assert_select_email+ - Assertions on the HTML body of an e-mail.
-
#
-
# Also see HTML::Selector to learn how to use selectors.
-
1
module SelectorAssertions
-
# Select and return all matching elements.
-
#
-
# If called with a single argument, uses that argument as a selector
-
# to match all elements of the current page. Returns an empty array
-
# if no match is found.
-
#
-
# If called with two arguments, uses the first argument as the base
-
# element and the second argument as the selector. Attempts to match the
-
# base element and any of its children. Returns an empty array if no
-
# match is found.
-
#
-
# The selector may be a CSS selector expression (String), an expression
-
# with substitution values (Array) or an HTML::Selector object.
-
#
-
# # Selects all div tags
-
# divs = css_select("div")
-
#
-
# # Selects all paragraph tags and does something interesting
-
# pars = css_select("p")
-
# pars.each do |par|
-
# # Do something fun with paragraphs here...
-
# end
-
#
-
# # Selects all list items in unordered lists
-
# items = css_select("ul>li")
-
#
-
# # Selects all form tags and then all inputs inside the form
-
# forms = css_select("form")
-
# forms.each do |form|
-
# inputs = css_select(form, "input")
-
# ...
-
# end
-
1
def css_select(*args)
-
# See assert_select to understand what's going on here.
-
arg = args.shift
-
-
if arg.is_a?(HTML::Node)
-
root = arg
-
arg = args.shift
-
elsif arg == nil
-
raise ArgumentError, "First argument is either selector or element to select, but nil found. Perhaps you called assert_select with an element that does not exist?"
-
elsif defined?(@selected) && @selected
-
matches = []
-
-
@selected.each do |selected|
-
subset = css_select(selected, HTML::Selector.new(arg.dup, args.dup))
-
subset.each do |match|
-
matches << match unless matches.any? { |m| m.equal?(match) }
-
end
-
end
-
-
return matches
-
else
-
root = response_from_page
-
end
-
-
case arg
-
when String
-
selector = HTML::Selector.new(arg, args)
-
when Array
-
selector = HTML::Selector.new(*arg)
-
when HTML::Selector
-
selector = arg
-
else raise ArgumentError, "Expecting a selector as the first argument"
-
end
-
-
selector.select(root)
-
end
-
-
# An assertion that selects elements and makes one or more equality tests.
-
#
-
# If the first argument is an element, selects all matching elements
-
# starting from (and including) that element and all its children in
-
# depth-first order.
-
#
-
# If no element if specified, calling +assert_select+ selects from the
-
# response HTML unless +assert_select+ is called from within an +assert_select+ block.
-
#
-
# When called with a block +assert_select+ passes an array of selected elements
-
# to the block. Calling +assert_select+ from the block, with no element specified,
-
# runs the assertion on the complete set of elements selected by the enclosing assertion.
-
# Alternatively the array may be iterated through so that +assert_select+ can be called
-
# separately for each element.
-
#
-
#
-
# ==== Example
-
# If the response contains two ordered lists, each with four list elements then:
-
# assert_select "ol" do |elements|
-
# elements.each do |element|
-
# assert_select element, "li", 4
-
# end
-
# end
-
#
-
# will pass, as will:
-
# assert_select "ol" do
-
# assert_select "li", 8
-
# end
-
#
-
# The selector may be a CSS selector expression (String), an expression
-
# with substitution values, or an HTML::Selector object.
-
#
-
# === Equality Tests
-
#
-
# The equality test may be one of the following:
-
# * <tt>true</tt> - Assertion is true if at least one element selected.
-
# * <tt>false</tt> - Assertion is true if no element selected.
-
# * <tt>String/Regexp</tt> - Assertion is true if the text value of at least
-
# one element matches the string or regular expression.
-
# * <tt>Integer</tt> - Assertion is true if exactly that number of
-
# elements are selected.
-
# * <tt>Range</tt> - Assertion is true if the number of selected
-
# elements fit the range.
-
# If no equality test specified, the assertion is true if at least one
-
# element selected.
-
#
-
# To perform more than one equality tests, use a hash with the following keys:
-
# * <tt>:text</tt> - Narrow the selection to elements that have this text
-
# value (string or regexp).
-
# * <tt>:html</tt> - Narrow the selection to elements that have this HTML
-
# content (string or regexp).
-
# * <tt>:count</tt> - Assertion is true if the number of selected elements
-
# is equal to this value.
-
# * <tt>:minimum</tt> - Assertion is true if the number of selected
-
# elements is at least this value.
-
# * <tt>:maximum</tt> - Assertion is true if the number of selected
-
# elements is at most this value.
-
#
-
# If the method is called with a block, once all equality tests are
-
# evaluated the block is called with an array of all matched elements.
-
#
-
# # At least one form element
-
# assert_select "form"
-
#
-
# # Form element includes four input fields
-
# assert_select "form input", 4
-
#
-
# # Page title is "Welcome"
-
# assert_select "title", "Welcome"
-
#
-
# # Page title is "Welcome" and there is only one title element
-
# assert_select "title", {count: 1, text: "Welcome"},
-
# "Wrong title or more than one title element"
-
#
-
# # Page contains no forms
-
# assert_select "form", false, "This page must contain no forms"
-
#
-
# # Test the content and style
-
# assert_select "body div.header ul.menu"
-
#
-
# # Use substitution values
-
# assert_select "ol>li#?", /item-\d+/
-
#
-
# # All input fields in the form have a name
-
# assert_select "form input" do
-
# assert_select "[name=?]", /.+/ # Not empty
-
# end
-
1
def assert_select(*args, &block)
-
# Start with optional element followed by mandatory selector.
-
arg = args.shift
-
@selected ||= nil
-
-
if arg.is_a?(HTML::Node)
-
# First argument is a node (tag or text, but also HTML root),
-
# so we know what we're selecting from.
-
root = arg
-
arg = args.shift
-
elsif arg == nil
-
# This usually happens when passing a node/element that
-
# happens to be nil.
-
raise ArgumentError, "First argument is either selector or element to select, but nil found. Perhaps you called assert_select with an element that does not exist?"
-
elsif @selected
-
root = HTML::Node.new(nil)
-
root.children.concat @selected
-
else
-
# Otherwise just operate on the response document.
-
root = response_from_page
-
end
-
-
# First or second argument is the selector: string and we pass
-
# all remaining arguments. Array and we pass the argument. Also
-
# accepts selector itself.
-
case arg
-
when String
-
selector = HTML::Selector.new(arg, args)
-
when Array
-
selector = HTML::Selector.new(*arg)
-
when HTML::Selector
-
selector = arg
-
else raise ArgumentError, "Expecting a selector as the first argument"
-
end
-
-
# Next argument is used for equality tests.
-
equals = {}
-
case arg = args.shift
-
when Hash
-
equals = arg
-
when String, Regexp
-
equals[:text] = arg
-
when Integer
-
equals[:count] = arg
-
when Range
-
equals[:minimum] = arg.begin
-
equals[:maximum] = arg.end
-
when FalseClass
-
equals[:count] = 0
-
when NilClass, TrueClass
-
equals[:minimum] = 1
-
else raise ArgumentError, "I don't understand what you're trying to match"
-
end
-
-
# By default we're looking for at least one match.
-
if equals[:count]
-
equals[:minimum] = equals[:maximum] = equals[:count]
-
else
-
equals[:minimum] = 1 unless equals[:minimum]
-
end
-
-
# Last argument is the message we use if the assertion fails.
-
message = args.shift
-
#- message = "No match made with selector #{selector.inspect}" unless message
-
if args.shift
-
raise ArgumentError, "Not expecting that last argument, you either have too many arguments, or they're the wrong type"
-
end
-
-
matches = selector.select(root)
-
# If text/html, narrow down to those elements that match it.
-
content_mismatch = nil
-
if match_with = equals[:text]
-
matches.delete_if do |match|
-
text = ""
-
stack = match.children.reverse
-
while node = stack.pop
-
if node.tag?
-
stack.concat node.children.reverse
-
else
-
content = node.content
-
text << content
-
end
-
end
-
text.strip! unless NO_STRIP.include?(match.name)
-
text.sub!(/\A\n/, '') if match.name == "textarea"
-
unless match_with.is_a?(Regexp) ? (text =~ match_with) : (text == match_with.to_s)
-
content_mismatch ||= sprintf("<%s> expected but was\n<%s>.", match_with, text)
-
true
-
end
-
end
-
elsif match_with = equals[:html]
-
matches.delete_if do |match|
-
html = match.children.map(&:to_s).join
-
html.strip! unless NO_STRIP.include?(match.name)
-
unless match_with.is_a?(Regexp) ? (html =~ match_with) : (html == match_with.to_s)
-
content_mismatch ||= sprintf("<%s> expected but was\n<%s>.", match_with, html)
-
true
-
end
-
end
-
end
-
# Expecting foo found bar element only if found zero, not if
-
# found one but expecting two.
-
message ||= content_mismatch if matches.empty?
-
# Test minimum/maximum occurrence.
-
min, max, count = equals[:minimum], equals[:maximum], equals[:count]
-
-
# FIXME: minitest provides messaging when we use assert_operator,
-
# so is this custom message really needed?
-
message = message || %(Expected #{count_description(min, max, count)} matching "#{selector.to_s}", found #{matches.size}.)
-
if count
-
assert_equal count, matches.size, message
-
else
-
assert_operator matches.size, :>=, min, message if min
-
assert_operator matches.size, :<=, max, message if max
-
end
-
-
# If a block is given call that block. Set @selected to allow
-
# nested assert_select, which can be nested several levels deep.
-
if block_given? && !matches.empty?
-
begin
-
in_scope, @selected = @selected, matches
-
yield matches
-
ensure
-
@selected = in_scope
-
end
-
end
-
-
# Returns all matches elements.
-
matches
-
end
-
-
1
def count_description(min, max, count) #:nodoc:
-
pluralize = lambda {|word, quantity| word << (quantity == 1 ? '' : 's')}
-
-
if min && max && (max != min)
-
"between #{min} and #{max} elements"
-
elsif min && max && max == min && count
-
"exactly #{count} #{pluralize['element', min]}"
-
elsif min && !(min == 1 && max == 1)
-
"at least #{min} #{pluralize['element', min]}"
-
elsif max
-
"at most #{max} #{pluralize['element', max]}"
-
end
-
end
-
-
# Extracts the content of an element, treats it as encoded HTML and runs
-
# nested assertion on it.
-
#
-
# You typically call this method within another assertion to operate on
-
# all currently selected elements. You can also pass an element or array
-
# of elements.
-
#
-
# The content of each element is un-encoded, and wrapped in the root
-
# element +encoded+. It then calls the block with all un-encoded elements.
-
#
-
# # Selects all bold tags from within the title of an Atom feed's entries (perhaps to nab a section name prefix)
-
# assert_select "feed[xmlns='http://www.w3.org/2005/Atom']" do
-
# # Select each entry item and then the title item
-
# assert_select "entry>title" do
-
# # Run assertions on the encoded title elements
-
# assert_select_encoded do
-
# assert_select "b"
-
# end
-
# end
-
# end
-
#
-
#
-
# # Selects all paragraph tags from within the description of an RSS feed
-
# assert_select "rss[version=2.0]" do
-
# # Select description element of each feed item.
-
# assert_select "channel>item>description" do
-
# # Run assertions on the encoded elements.
-
# assert_select_encoded do
-
# assert_select "p"
-
# end
-
# end
-
# end
-
1
def assert_select_encoded(element = nil, &block)
-
case element
-
when Array
-
elements = element
-
when HTML::Node
-
elements = [element]
-
when nil
-
unless elements = @selected
-
raise ArgumentError, "First argument is optional, but must be called from a nested assert_select"
-
end
-
else
-
raise ArgumentError, "Argument is optional, and may be node or array of nodes"
-
end
-
-
fix_content = lambda do |node|
-
# Gets around a bug in the Rails 1.1 HTML parser.
-
node.content.gsub(/<!\[CDATA\[(.*)(\]\]>)?/m) { Rack::Utils.escapeHTML($1) }
-
end
-
-
selected = elements.map do |elem|
-
text = elem.children.select{ |c| not c.tag? }.map{ |c| fix_content[c] }.join
-
root = HTML::Document.new(CGI.unescapeHTML("<encoded>#{text}</encoded>")).root
-
css_select(root, "encoded:root", &block)[0]
-
end
-
-
begin
-
old_selected, @selected = @selected, selected
-
assert_select ":root", &block
-
ensure
-
@selected = old_selected
-
end
-
end
-
-
# Extracts the body of an email and runs nested assertions on it.
-
#
-
# You must enable deliveries for this assertion to work, use:
-
# ActionMailer::Base.perform_deliveries = true
-
#
-
# assert_select_email do
-
# assert_select "h1", "Email alert"
-
# end
-
#
-
# assert_select_email do
-
# items = assert_select "ol>li"
-
# items.each do
-
# # Work with items here...
-
# end
-
# end
-
1
def assert_select_email(&block)
-
deliveries = ActionMailer::Base.deliveries
-
assert !deliveries.empty?, "No e-mail in delivery list"
-
-
deliveries.each do |delivery|
-
(delivery.parts.empty? ? [delivery] : delivery.parts).each do |part|
-
if part["Content-Type"].to_s =~ /^text\/html\W/
-
root = HTML::Document.new(part.body.to_s).root
-
assert_select root, ":root", &block
-
end
-
end
-
end
-
end
-
-
1
protected
-
# +assert_select+ and +css_select+ call this to obtain the content in the HTML page.
-
1
def response_from_page
-
html_document.root
-
end
-
end
-
end
-
end
-
1
require 'action_view/vendor/html-scanner'
-
-
1
module ActionDispatch
-
1
module Assertions
-
# Pair of assertions to testing elements in the HTML output of the response.
-
1
module TagAssertions
-
# Asserts that there is a tag/node/element in the body of the response
-
# that meets all of the given conditions. The +conditions+ parameter must
-
# be a hash of any of the following keys (all are optional):
-
#
-
# * <tt>:tag</tt>: the node type must match the corresponding value
-
# * <tt>:attributes</tt>: a hash. The node's attributes must match the
-
# corresponding values in the hash.
-
# * <tt>:parent</tt>: a hash. The node's parent must match the
-
# corresponding hash.
-
# * <tt>:child</tt>: a hash. At least one of the node's immediate children
-
# must meet the criteria described by the hash.
-
# * <tt>:ancestor</tt>: a hash. At least one of the node's ancestors must
-
# meet the criteria described by the hash.
-
# * <tt>:descendant</tt>: a hash. At least one of the node's descendants
-
# must meet the criteria described by the hash.
-
# * <tt>:sibling</tt>: a hash. At least one of the node's siblings must
-
# meet the criteria described by the hash.
-
# * <tt>:after</tt>: a hash. The node must be after any sibling meeting
-
# the criteria described by the hash, and at least one sibling must match.
-
# * <tt>:before</tt>: a hash. The node must be before any sibling meeting
-
# the criteria described by the hash, and at least one sibling must match.
-
# * <tt>:children</tt>: a hash, for counting children of a node. Accepts
-
# the keys:
-
# * <tt>:count</tt>: either a number or a range which must equal (or
-
# include) the number of children that match.
-
# * <tt>:less_than</tt>: the number of matching children must be less
-
# than this number.
-
# * <tt>:greater_than</tt>: the number of matching children must be
-
# greater than this number.
-
# * <tt>:only</tt>: another hash consisting of the keys to use
-
# to match on the children, and only matching children will be
-
# counted.
-
# * <tt>:content</tt>: the textual content of the node must match the
-
# given value. This will not match HTML tags in the body of a
-
# tag--only text.
-
#
-
# Conditions are matched using the following algorithm:
-
#
-
# * if the condition is a string, it must be a substring of the value.
-
# * if the condition is a regexp, it must match the value.
-
# * if the condition is a number, the value must match number.to_s.
-
# * if the condition is +true+, the value must not be +nil+.
-
# * if the condition is +false+ or +nil+, the value must be +nil+.
-
#
-
# # Assert that there is a "span" tag
-
# assert_tag tag: "span"
-
#
-
# # Assert that there is a "span" tag with id="x"
-
# assert_tag tag: "span", attributes: { id: "x" }
-
#
-
# # Assert that there is a "span" tag using the short-hand
-
# assert_tag :span
-
#
-
# # Assert that there is a "span" tag with id="x" using the short-hand
-
# assert_tag :span, attributes: { id: "x" }
-
#
-
# # Assert that there is a "span" inside of a "div"
-
# assert_tag tag: "span", parent: { tag: "div" }
-
#
-
# # Assert that there is a "span" somewhere inside a table
-
# assert_tag tag: "span", ancestor: { tag: "table" }
-
#
-
# # Assert that there is a "span" with at least one "em" child
-
# assert_tag tag: "span", child: { tag: "em" }
-
#
-
# # Assert that there is a "span" containing a (possibly nested)
-
# # "strong" tag.
-
# assert_tag tag: "span", descendant: { tag: "strong" }
-
#
-
# # Assert that there is a "span" containing between 2 and 4 "em" tags
-
# # as immediate children
-
# assert_tag tag: "span",
-
# children: { count: 2..4, only: { tag: "em" } }
-
#
-
# # Get funky: assert that there is a "div", with an "ul" ancestor
-
# # and an "li" parent (with "class" = "enum"), and containing a
-
# # "span" descendant that contains text matching /hello world/
-
# assert_tag tag: "div",
-
# ancestor: { tag: "ul" },
-
# parent: { tag: "li",
-
# attributes: { class: "enum" } },
-
# descendant: { tag: "span",
-
# child: /hello world/ }
-
#
-
# <b>Please note</b>: +assert_tag+ and +assert_no_tag+ only work
-
# with well-formed XHTML. They recognize a few tags as implicitly self-closing
-
# (like br and hr and such) but will not work correctly with tags
-
# that allow optional closing tags (p, li, td). <em>You must explicitly
-
# close all of your tags to use these assertions.</em>
-
1
def assert_tag(*opts)
-
opts = opts.size > 1 ? opts.last.merge({ :tag => opts.first.to_s }) : opts.first
-
tag = find_tag(opts)
-
assert tag, "expected tag, but no tag found matching #{opts.inspect} in:\n#{@response.body.inspect}"
-
end
-
-
# Identical to +assert_tag+, but asserts that a matching tag does _not_
-
# exist. (See +assert_tag+ for a full discussion of the syntax.)
-
#
-
# # Assert that there is not a "div" containing a "p"
-
# assert_no_tag tag: "div", descendant: { tag: "p" }
-
#
-
# # Assert that an unordered list is empty
-
# assert_no_tag tag: "ul", descendant: { tag: "li" }
-
#
-
# # Assert that there is not a "p" tag with between 1 to 3 "img" tags
-
# # as immediate children
-
# assert_no_tag tag: "p",
-
# children: { count: 1..3, only: { tag: "img" } }
-
1
def assert_no_tag(*opts)
-
opts = opts.size > 1 ? opts.last.merge({ :tag => opts.first.to_s }) : opts.first
-
tag = find_tag(opts)
-
assert !tag, "expected no tag, but found tag matching #{opts.inspect} in:\n#{@response.body.inspect}"
-
end
-
-
1
def find_tag(conditions)
-
html_document.find(conditions)
-
end
-
-
1
def find_all_tag(conditions)
-
html_document.find_all(conditions)
-
end
-
-
1
def html_document
-
xml = @response.content_type =~ /xml$/
-
@html_document ||= HTML::Document.new(@response.body, false, xml)
-
end
-
end
-
end
-
end
-
1
require 'stringio'
-
1
require 'uri'
-
1
require 'active_support/core_ext/kernel/singleton_class'
-
1
require 'active_support/core_ext/object/try'
-
1
require 'rack/test'
-
1
require 'minitest'
-
-
1
module ActionDispatch
-
1
module Integration #:nodoc:
-
1
module RequestHelpers
-
# Performs a GET request with the given parameters.
-
#
-
# - +path+: The URI (as a String) on which you want to perform a GET
-
# request.
-
# - +parameters+: The HTTP parameters that you want to pass. This may
-
# be +nil+,
-
# a Hash, or a String that is appropriately encoded
-
# (<tt>application/x-www-form-urlencoded</tt> or
-
# <tt>multipart/form-data</tt>).
-
# - +headers_or_env+: Additional headers to pass, as a Hash. The headers will be
-
# merged into the Rack env hash.
-
#
-
# This method returns a Response object, which one can use to
-
# inspect the details of the response. Furthermore, if this method was
-
# called from an ActionDispatch::IntegrationTest object, then that
-
# object's <tt>@response</tt> instance variable will point to the same
-
# response object.
-
#
-
# You can also perform POST, PATCH, PUT, DELETE, and HEAD requests with
-
# +#post+, +#patch+, +#put+, +#delete+, and +#head+.
-
1
def get(path, parameters = nil, headers_or_env = nil)
-
process :get, path, parameters, headers_or_env
-
end
-
-
# Performs a POST request with the given parameters. See +#get+ for more
-
# details.
-
1
def post(path, parameters = nil, headers_or_env = nil)
-
process :post, path, parameters, headers_or_env
-
end
-
-
# Performs a PATCH request with the given parameters. See +#get+ for more
-
# details.
-
1
def patch(path, parameters = nil, headers_or_env = nil)
-
process :patch, path, parameters, headers_or_env
-
end
-
-
# Performs a PUT request with the given parameters. See +#get+ for more
-
# details.
-
1
def put(path, parameters = nil, headers_or_env = nil)
-
process :put, path, parameters, headers_or_env
-
end
-
-
# Performs a DELETE request with the given parameters. See +#get+ for
-
# more details.
-
1
def delete(path, parameters = nil, headers_or_env = nil)
-
process :delete, path, parameters, headers_or_env
-
end
-
-
# Performs a HEAD request with the given parameters. See +#get+ for more
-
# details.
-
1
def head(path, parameters = nil, headers_or_env = nil)
-
process :head, path, parameters, headers_or_env
-
end
-
-
# Performs an XMLHttpRequest request with the given parameters, mirroring
-
# a request from the Prototype library.
-
#
-
# The request_method is +:get+, +:post+, +:patch+, +:put+, +:delete+ or
-
# +:head+; the parameters are +nil+, a hash, or a url-encoded or multipart
-
# string; the headers are a hash.
-
1
def xml_http_request(request_method, path, parameters = nil, headers_or_env = nil)
-
headers_or_env ||= {}
-
headers_or_env['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
-
headers_or_env['HTTP_ACCEPT'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
-
process(request_method, path, parameters, headers_or_env)
-
end
-
1
alias xhr :xml_http_request
-
-
# Follow a single redirect response. If the last response was not a
-
# redirect, an exception will be raised. Otherwise, the redirect is
-
# performed on the location header.
-
1
def follow_redirect!
-
raise "not a redirect! #{status} #{status_message}" unless redirect?
-
get(response.location)
-
status
-
end
-
-
# Performs a request using the specified method, following any subsequent
-
# redirect. Note that the redirects are followed until the response is
-
# not a redirect--this means you may run into an infinite loop if your
-
# redirect loops back to itself.
-
1
def request_via_redirect(http_method, path, parameters = nil, headers_or_env = nil)
-
process(http_method, path, parameters, headers_or_env)
-
follow_redirect! while redirect?
-
status
-
end
-
-
# Performs a GET request, following any subsequent redirect.
-
# See +request_via_redirect+ for more information.
-
1
def get_via_redirect(path, parameters = nil, headers_or_env = nil)
-
request_via_redirect(:get, path, parameters, headers_or_env)
-
end
-
-
# Performs a POST request, following any subsequent redirect.
-
# See +request_via_redirect+ for more information.
-
1
def post_via_redirect(path, parameters = nil, headers_or_env = nil)
-
request_via_redirect(:post, path, parameters, headers_or_env)
-
end
-
-
# Performs a PATCH request, following any subsequent redirect.
-
# See +request_via_redirect+ for more information.
-
1
def patch_via_redirect(path, parameters = nil, headers_or_env = nil)
-
request_via_redirect(:patch, path, parameters, headers_or_env)
-
end
-
-
# Performs a PUT request, following any subsequent redirect.
-
# See +request_via_redirect+ for more information.
-
1
def put_via_redirect(path, parameters = nil, headers_or_env = nil)
-
request_via_redirect(:put, path, parameters, headers_or_env)
-
end
-
-
# Performs a DELETE request, following any subsequent redirect.
-
# See +request_via_redirect+ for more information.
-
1
def delete_via_redirect(path, parameters = nil, headers_or_env = nil)
-
request_via_redirect(:delete, path, parameters, headers_or_env)
-
end
-
end
-
-
# An instance of this class represents a set of requests and responses
-
# performed sequentially by a test process. Because you can instantiate
-
# multiple sessions and run them side-by-side, you can also mimic (to some
-
# limited extent) multiple simultaneous users interacting with your system.
-
#
-
# Typically, you will instantiate a new session using
-
# IntegrationTest#open_session, rather than instantiating
-
# Integration::Session directly.
-
1
class Session
-
1
DEFAULT_HOST = "www.example.com"
-
-
1
include Minitest::Assertions
-
1
include TestProcess, RequestHelpers, Assertions
-
-
1
%w( status status_message headers body redirect? ).each do |method|
-
5
delegate method, :to => :response, :allow_nil => true
-
end
-
-
1
%w( path ).each do |method|
-
1
delegate method, :to => :request, :allow_nil => true
-
end
-
-
# The hostname used in the last request.
-
1
def host
-
@host || DEFAULT_HOST
-
end
-
1
attr_writer :host
-
-
# The remote_addr used in the last request.
-
1
attr_accessor :remote_addr
-
-
# The Accept header to send.
-
1
attr_accessor :accept
-
-
# A map of the cookies returned by the last response, and which will be
-
# sent with the next request.
-
1
def cookies
-
_mock_session.cookie_jar
-
end
-
-
# A reference to the controller instance used by the last request.
-
1
attr_reader :controller
-
-
# A reference to the request instance used by the last request.
-
1
attr_reader :request
-
-
# A reference to the response instance used by the last request.
-
1
attr_reader :response
-
-
# A running counter of the number of requests processed.
-
1
attr_accessor :request_count
-
-
1
include ActionDispatch::Routing::UrlFor
-
-
# Create and initialize a new Session instance.
-
1
def initialize(app)
-
super()
-
@app = app
-
-
# If the app is a Rails app, make url_helpers available on the session
-
# This makes app.url_for and app.foo_path available in the console
-
if app.respond_to?(:routes)
-
singleton_class.class_eval do
-
include app.routes.url_helpers if app.routes.respond_to?(:url_helpers)
-
include app.routes.mounted_helpers if app.routes.respond_to?(:mounted_helpers)
-
end
-
end
-
-
reset!
-
end
-
-
1
def url_options
-
@url_options ||= default_url_options.dup.tap do |url_options|
-
url_options.reverse_merge!(controller.url_options) if controller
-
-
if @app.respond_to?(:routes) && @app.routes.respond_to?(:default_url_options)
-
url_options.reverse_merge!(@app.routes.default_url_options)
-
end
-
-
url_options.reverse_merge!(:host => host, :protocol => https? ? "https" : "http")
-
end
-
end
-
-
# Resets the instance. This can be used to reset the state information
-
# in an existing session instance, so it can be used from a clean-slate
-
# condition.
-
#
-
# session.reset!
-
1
def reset!
-
@https = false
-
@controller = @request = @response = nil
-
@_mock_session = nil
-
@request_count = 0
-
@url_options = nil
-
-
self.host = DEFAULT_HOST
-
self.remote_addr = "127.0.0.1"
-
self.accept = "text/xml,application/xml,application/xhtml+xml," +
-
"text/html;q=0.9,text/plain;q=0.8,image/png," +
-
"*/*;q=0.5"
-
-
unless defined? @named_routes_configured
-
# the helpers are made protected by default--we make them public for
-
# easier access during testing and troubleshooting.
-
@named_routes_configured = true
-
end
-
end
-
-
# Specify whether or not the session should mimic a secure HTTPS request.
-
#
-
# session.https!
-
# session.https!(false)
-
1
def https!(flag = true)
-
@https = flag
-
end
-
-
# Returns +true+ if the session is mimicking a secure HTTPS request.
-
#
-
# if session.https?
-
# ...
-
# end
-
1
def https?
-
@https
-
end
-
-
# Set the host name to use in the next request.
-
#
-
# session.host! "www.example.com"
-
1
alias :host! :host=
-
-
1
private
-
1
def _mock_session
-
@_mock_session ||= Rack::MockSession.new(@app, host)
-
end
-
-
# Performs the actual request.
-
1
def process(method, path, parameters = nil, headers_or_env = nil)
-
if path =~ %r{://}
-
location = URI.parse(path)
-
https! URI::HTTPS === location if location.scheme
-
host! "#{location.host}:#{location.port}" if location.host
-
path = location.query ? "#{location.path}?#{location.query}" : location.path
-
end
-
-
unless ActionController::Base < ActionController::Testing
-
ActionController::Base.class_eval do
-
include ActionController::Testing
-
end
-
end
-
-
hostname, port = host.split(':')
-
-
env = {
-
:method => method,
-
:params => parameters,
-
-
"SERVER_NAME" => hostname,
-
"SERVER_PORT" => port || (https? ? "443" : "80"),
-
"HTTPS" => https? ? "on" : "off",
-
"rack.url_scheme" => https? ? "https" : "http",
-
-
"REQUEST_URI" => path,
-
"HTTP_HOST" => host,
-
"REMOTE_ADDR" => remote_addr,
-
"CONTENT_TYPE" => "application/x-www-form-urlencoded",
-
"HTTP_ACCEPT" => accept
-
}
-
# this modifies the passed env directly
-
Http::Headers.new(env).merge!(headers_or_env || {})
-
-
session = Rack::Test::Session.new(_mock_session)
-
-
# NOTE: rack-test v0.5 doesn't build a default uri correctly
-
# Make sure requested path is always a full uri
-
uri = URI.parse('/')
-
uri.scheme ||= env['rack.url_scheme']
-
uri.host ||= env['SERVER_NAME']
-
uri.port ||= env['SERVER_PORT'].try(:to_i)
-
uri += path
-
-
session.request(uri.to_s, env)
-
-
@request_count += 1
-
@request = ActionDispatch::Request.new(session.last_request.env)
-
response = _mock_session.last_response
-
@response = ActionDispatch::TestResponse.new(response.status, response.headers, response.body)
-
@html_document = nil
-
@url_options = nil
-
-
@controller = session.last_request.env['action_controller.instance']
-
-
return response.status
-
end
-
end
-
-
1
module Runner
-
1
include ActionDispatch::Assertions
-
-
1
def app
-
@app ||= nil
-
end
-
-
# Reset the current session. This is useful for testing multiple sessions
-
# in a single test case.
-
1
def reset!
-
@integration_session = Integration::Session.new(app)
-
end
-
-
%w(get post patch put head delete cookies assigns
-
1
xml_http_request xhr get_via_redirect post_via_redirect).each do |method|
-
12
define_method(method) do |*args|
-
reset! unless integration_session
-
# reset the html_document variable, but only for new get/post calls
-
@html_document = nil unless method == 'cookies' || method == 'assigns'
-
integration_session.__send__(method, *args).tap do
-
copy_session_variables!
-
end
-
end
-
end
-
-
# Open a new session instance. If a block is given, the new session is
-
# yielded to the block before being returned.
-
#
-
# session = open_session do |sess|
-
# sess.extend(CustomAssertions)
-
# end
-
#
-
# By default, a single session is automatically created for you, but you
-
# can use this method to open multiple sessions that ought to be tested
-
# simultaneously.
-
1
def open_session(app = nil)
-
dup.tap do |session|
-
yield session if block_given?
-
end
-
end
-
-
# Copy the instance variables from the current session instance into the
-
# test instance.
-
1
def copy_session_variables! #:nodoc:
-
return unless integration_session
-
%w(controller response request).each do |var|
-
instance_variable_set("@#{var}", @integration_session.__send__(var))
-
end
-
end
-
-
1
def default_url_options
-
reset! unless integration_session
-
integration_session.default_url_options
-
end
-
-
1
def default_url_options=(options)
-
reset! unless integration_session
-
integration_session.default_url_options = options
-
end
-
-
1
def respond_to?(method, include_private = false)
-
integration_session.respond_to?(method, include_private) || super
-
end
-
-
# Delegate unhandled messages to the current session instance.
-
1
def method_missing(sym, *args, &block)
-
reset! unless integration_session
-
if integration_session.respond_to?(sym)
-
integration_session.__send__(sym, *args, &block).tap do
-
copy_session_variables!
-
end
-
else
-
super
-
end
-
end
-
-
1
private
-
1
def integration_session
-
@integration_session ||= nil
-
end
-
end
-
end
-
-
# An integration test spans multiple controllers and actions,
-
# tying them all together to ensure they work together as expected. It tests
-
# more completely than either unit or functional tests do, exercising the
-
# entire stack, from the dispatcher to the database.
-
#
-
# At its simplest, you simply extend <tt>IntegrationTest</tt> and write your tests
-
# using the get/post methods:
-
#
-
# require "test_helper"
-
#
-
# class ExampleTest < ActionDispatch::IntegrationTest
-
# fixtures :people
-
#
-
# def test_login
-
# # get the login page
-
# get "/login"
-
# assert_equal 200, status
-
#
-
# # post the login and follow through to the home page
-
# post "/login", username: people(:jamis).username,
-
# password: people(:jamis).password
-
# follow_redirect!
-
# assert_equal 200, status
-
# assert_equal "/home", path
-
# end
-
# end
-
#
-
# However, you can also have multiple session instances open per test, and
-
# even extend those instances with assertions and methods to create a very
-
# powerful testing DSL that is specific for your application. You can even
-
# reference any named routes you happen to have defined.
-
#
-
# require "test_helper"
-
#
-
# class AdvancedTest < ActionDispatch::IntegrationTest
-
# fixtures :people, :rooms
-
#
-
# def test_login_and_speak
-
# jamis, david = login(:jamis), login(:david)
-
# room = rooms(:office)
-
#
-
# jamis.enter(room)
-
# jamis.speak(room, "anybody home?")
-
#
-
# david.enter(room)
-
# david.speak(room, "hello!")
-
# end
-
#
-
# private
-
#
-
# module CustomAssertions
-
# def enter(room)
-
# # reference a named route, for maximum internal consistency!
-
# get(room_url(id: room.id))
-
# assert(...)
-
# ...
-
# end
-
#
-
# def speak(room, message)
-
# xml_http_request "/say/#{room.id}", message: message
-
# assert(...)
-
# ...
-
# end
-
# end
-
#
-
# def login(who)
-
# open_session do |sess|
-
# sess.extend(CustomAssertions)
-
# who = people(who)
-
# sess.post "/login", username: who.username,
-
# password: who.password
-
# assert(...)
-
# end
-
# end
-
# end
-
1
class IntegrationTest < ActiveSupport::TestCase
-
1
include Integration::Runner
-
1
include ActionController::TemplateAssertions
-
1
include ActionDispatch::Routing::UrlFor
-
-
1
@@app = nil
-
-
1
def self.app
-
@@app || ActionDispatch.test_app
-
end
-
-
1
def self.app=(app)
-
@@app = app
-
end
-
-
1
def app
-
super || self.class.app
-
end
-
-
1
def url_options
-
reset! unless integration_session
-
integration_session.url_options
-
end
-
end
-
end
-
1
require 'action_dispatch/middleware/cookies'
-
1
require 'action_dispatch/middleware/flash'
-
1
require 'active_support/core_ext/hash/indifferent_access'
-
-
1
module ActionDispatch
-
1
module TestProcess
-
1
def assigns(key = nil)
-
assigns = {}.with_indifferent_access
-
@controller.view_assigns.each { |k, v| assigns.regular_writer(k, v) }
-
key.nil? ? assigns : assigns[key]
-
end
-
-
1
def session
-
@request.session
-
end
-
-
1
def flash
-
@request.flash
-
end
-
-
1
def cookies
-
@request.cookie_jar
-
end
-
-
1
def redirect_to_url
-
@response.redirect_url
-
end
-
-
# Shortcut for <tt>Rack::Test::UploadedFile.new(File.join(ActionController::TestCase.fixture_path, path), type)</tt>:
-
#
-
# post :change_avatar, avatar: fixture_file_upload('files/spongebob.png', 'image/png')
-
#
-
# To upload binary files on Windows, pass <tt>:binary</tt> as the last parameter.
-
# This will not affect other platforms:
-
#
-
# post :change_avatar, avatar: fixture_file_upload('files/spongebob.png', 'image/png', :binary)
-
1
def fixture_file_upload(path, mime_type = nil, binary = false)
-
if self.class.respond_to?(:fixture_path) && self.class.fixture_path
-
path = File.join(self.class.fixture_path, path)
-
end
-
Rack::Test::UploadedFile.new(path, mime_type, binary)
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/indifferent_access'
-
1
require 'rack/utils'
-
-
1
module ActionDispatch
-
1
class TestRequest < Request
-
1
DEFAULT_ENV = Rack::MockRequest.env_for('/',
-
'HTTP_HOST' => 'test.host',
-
'REMOTE_ADDR' => '0.0.0.0',
-
'HTTP_USER_AGENT' => 'Rails Testing'
-
)
-
-
1
def self.new(env = {})
-
super
-
end
-
-
1
def initialize(env = {})
-
env = Rails.application.env_config.merge(env) if defined?(Rails.application) && Rails.application
-
super(default_env.merge(env))
-
end
-
-
1
def request_method=(method)
-
@env['REQUEST_METHOD'] = method.to_s.upcase
-
end
-
-
1
def host=(host)
-
@env['HTTP_HOST'] = host
-
end
-
-
1
def port=(number)
-
@env['SERVER_PORT'] = number.to_i
-
end
-
-
1
def request_uri=(uri)
-
@env['REQUEST_URI'] = uri
-
end
-
-
1
def path=(path)
-
@env['PATH_INFO'] = path
-
end
-
-
1
def action=(action_name)
-
path_parameters["action"] = action_name.to_s
-
end
-
-
1
def if_modified_since=(last_modified)
-
@env['HTTP_IF_MODIFIED_SINCE'] = last_modified
-
end
-
-
1
def if_none_match=(etag)
-
@env['HTTP_IF_NONE_MATCH'] = etag
-
end
-
-
1
def remote_addr=(addr)
-
@env['REMOTE_ADDR'] = addr
-
end
-
-
1
def user_agent=(user_agent)
-
@env['HTTP_USER_AGENT'] = user_agent
-
end
-
-
1
def accept=(mime_types)
-
@env.delete('action_dispatch.request.accepts')
-
@env['HTTP_ACCEPT'] = Array(mime_types).collect { |mime_type| mime_type.to_s }.join(",")
-
end
-
-
1
alias :rack_cookies :cookies
-
-
1
def cookies
-
@cookies ||= {}.with_indifferent_access
-
end
-
-
1
private
-
-
1
def default_env
-
DEFAULT_ENV
-
end
-
end
-
end
-
1
module ActionDispatch
-
# Integration test methods such as ActionDispatch::Integration::Session#get
-
# and ActionDispatch::Integration::Session#post return objects of class
-
# TestResponse, which represent the HTTP response results of the requested
-
# controller actions.
-
#
-
# See Response for more information on controller response objects.
-
1
class TestResponse < Response
-
1
def self.from_response(response)
-
new.tap do |resp|
-
resp.status = response.status
-
resp.headers = response.headers
-
resp.body = response.body
-
end
-
end
-
-
# Was the response successful?
-
1
alias_method :success?, :successful?
-
-
# Was the URL not found?
-
1
alias_method :missing?, :not_found?
-
-
# Were we redirected?
-
1
alias_method :redirect?, :redirection?
-
-
# Was there a server-side error?
-
1
alias_method :error?, :server_error?
-
end
-
end
-
#--
-
# Copyright (c) 2004-2014 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
1
require 'action_pack/version'
-
1
module ActionPack
-
# Returns the version of the currently loaded ActionPack as a <tt>Gem::Version</tt>
-
1
def self.gem_version
-
Gem::Version.new VERSION::STRING
-
end
-
-
1
module VERSION
-
1
MAJOR = 4
-
1
MINOR = 1
-
1
TINY = 0
-
1
PRE = nil
-
-
1
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
-
end
-
end
-
1
require_relative 'gem_version'
-
-
1
module ActionPack
-
# Returns the version of the currently loaded ActionPack as a <tt>Gem::Version</tt>
-
1
def self.version
-
gem_version
-
end
-
end
-
#--
-
# Copyright (c) 2004-2014 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
1
require 'active_support'
-
1
require 'active_support/rails'
-
1
require 'action_view/version'
-
-
1
module ActionView
-
1
extend ActiveSupport::Autoload
-
-
1
ENCODING_FLAG = '#.*coding[:=]\s*(\S+)[ \t]*'
-
-
1
eager_autoload do
-
1
autoload :Base
-
1
autoload :Context
-
1
autoload :CompiledTemplates, "action_view/context"
-
1
autoload :Digestor
-
1
autoload :Helpers
-
1
autoload :LookupContext
-
1
autoload :Layouts
-
1
autoload :PathSet
-
1
autoload :RecordIdentifier
-
1
autoload :Rendering
-
1
autoload :RoutingUrlFor
-
1
autoload :Template
-
1
autoload :ViewPaths
-
-
1
autoload_under "renderer" do
-
1
autoload :Renderer
-
1
autoload :AbstractRenderer
-
1
autoload :PartialRenderer
-
1
autoload :TemplateRenderer
-
1
autoload :StreamingTemplateRenderer
-
end
-
-
1
autoload_at "action_view/template/resolver" do
-
1
autoload :Resolver
-
1
autoload :PathResolver
-
1
autoload :OptimizedFileSystemResolver
-
1
autoload :FallbackFileSystemResolver
-
end
-
-
1
autoload_at "action_view/buffers" do
-
1
autoload :OutputBuffer
-
1
autoload :StreamingBuffer
-
end
-
-
1
autoload_at "action_view/flows" do
-
1
autoload :OutputFlow
-
1
autoload :StreamingFlow
-
end
-
-
1
autoload_at "action_view/template/error" do
-
1
autoload :MissingTemplate
-
1
autoload :ActionViewError
-
1
autoload :EncodingError
-
1
autoload :MissingRequestError
-
1
autoload :TemplateError
-
1
autoload :WrongEncodingError
-
end
-
end
-
-
1
autoload :TestCase
-
-
1
def self.eager_load!
-
super
-
ActionView::Helpers.eager_load!
-
ActionView::Template.eager_load!
-
HTML.eager_load!
-
end
-
end
-
-
1
require 'active_support/core_ext/string/output_safety'
-
-
1
ActiveSupport.on_load(:i18n) do
-
1
I18n.load_path << "#{File.dirname(__FILE__)}/action_view/locale/en.yml"
-
end
-
1
require 'active_support/core_ext/module/attr_internal'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/ordered_options'
-
1
require 'action_view/log_subscriber'
-
1
require 'action_view/helpers'
-
1
require 'action_view/context'
-
1
require 'action_view/template'
-
1
require 'action_view/lookup_context'
-
-
1
module ActionView #:nodoc:
-
# = Action View Base
-
#
-
# Action View templates can be written in several ways. If the template file has a <tt>.erb</tt> extension then it uses a mixture of ERB
-
# (included in Ruby) and HTML. If the template file has a <tt>.builder</tt> extension then Jim Weirich's Builder::XmlMarkup library is used.
-
#
-
# == ERB
-
#
-
# You trigger ERB by using embeddings such as <% %>, <% -%>, and <%= %>. The <%= %> tag set is used when you want output. Consider the
-
# following loop for names:
-
#
-
# <b>Names of all the people</b>
-
# <% @people.each do |person| %>
-
# Name: <%= person.name %><br/>
-
# <% end %>
-
#
-
# The loop is setup in regular embedding tags <% %> and the name is written using the output embedding tag <%= %>. Note that this
-
# is not just a usage suggestion. Regular output functions like print or puts won't work with ERB templates. So this would be wrong:
-
#
-
# <%# WRONG %>
-
# Hi, Mr. <% puts "Frodo" %>
-
#
-
# If you absolutely must write from within a function use +concat+.
-
#
-
# <%- and -%> suppress leading and trailing whitespace, including the trailing newline, and can be used interchangeably with <% and %>.
-
#
-
# === Using sub templates
-
#
-
# Using sub templates allows you to sidestep tedious replication and extract common display structures in shared templates. The
-
# classic example is the use of a header and footer (even though the Action Pack-way would be to use Layouts):
-
#
-
# <%= render "shared/header" %>
-
# Something really specific and terrific
-
# <%= render "shared/footer" %>
-
#
-
# As you see, we use the output embeddings for the render methods. The render call itself will just return a string holding the
-
# result of the rendering. The output embedding writes it to the current template.
-
#
-
# But you don't have to restrict yourself to static includes. Templates can share variables amongst themselves by using instance
-
# variables defined using the regular embedding tags. Like this:
-
#
-
# <% @page_title = "A Wonderful Hello" %>
-
# <%= render "shared/header" %>
-
#
-
# Now the header can pick up on the <tt>@page_title</tt> variable and use it for outputting a title tag:
-
#
-
# <title><%= @page_title %></title>
-
#
-
# === Passing local variables to sub templates
-
#
-
# You can pass local variables to sub templates by using a hash with the variable names as keys and the objects as values:
-
#
-
# <%= render "shared/header", { headline: "Welcome", person: person } %>
-
#
-
# These can now be accessed in <tt>shared/header</tt> with:
-
#
-
# Headline: <%= headline %>
-
# First name: <%= person.first_name %>
-
#
-
# If you need to find out whether a certain local variable has been assigned a value in a particular render call,
-
# you need to use the following pattern:
-
#
-
# <% if local_assigns.has_key? :headline %>
-
# Headline: <%= headline %>
-
# <% end %>
-
#
-
# Testing using <tt>defined? headline</tt> will not work. This is an implementation restriction.
-
#
-
# === Template caching
-
#
-
# By default, Rails will compile each template to a method in order to render it. When you alter a template,
-
# Rails will check the file's modification time and recompile it in development mode.
-
#
-
# == Builder
-
#
-
# Builder templates are a more programmatic alternative to ERB. They are especially useful for generating XML content. An XmlMarkup object
-
# named +xml+ is automatically made available to templates with a <tt>.builder</tt> extension.
-
#
-
# Here are some basic examples:
-
#
-
# xml.em("emphasized") # => <em>emphasized</em>
-
# xml.em { xml.b("emph & bold") } # => <em><b>emph & bold</b></em>
-
# xml.a("A Link", "href" => "http://onestepback.org") # => <a href="http://onestepback.org">A Link</a>
-
# xml.target("name" => "compile", "option" => "fast") # => <target option="fast" name="compile"\>
-
# # NOTE: order of attributes is not specified.
-
#
-
# Any method with a block will be treated as an XML markup tag with nested markup in the block. For example, the following:
-
#
-
# xml.div do
-
# xml.h1(@person.name)
-
# xml.p(@person.bio)
-
# end
-
#
-
# would produce something like:
-
#
-
# <div>
-
# <h1>David Heinemeier Hansson</h1>
-
# <p>A product of Danish Design during the Winter of '79...</p>
-
# </div>
-
#
-
# A full-length RSS example actually used on Basecamp:
-
#
-
# xml.rss("version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/") do
-
# xml.channel do
-
# xml.title(@feed_title)
-
# xml.link(@url)
-
# xml.description "Basecamp: Recent items"
-
# xml.language "en-us"
-
# xml.ttl "40"
-
#
-
# @recent_items.each do |item|
-
# xml.item do
-
# xml.title(item_title(item))
-
# xml.description(item_description(item)) if item_description(item)
-
# xml.pubDate(item_pubDate(item))
-
# xml.guid(@person.firm.account.url + @recent_items.url(item))
-
# xml.link(@person.firm.account.url + @recent_items.url(item))
-
#
-
# xml.tag!("dc:creator", item.author_name) if item_has_creator?(item)
-
# end
-
# end
-
# end
-
# end
-
#
-
# More builder documentation can be found at http://builder.rubyforge.org.
-
1
class Base
-
1
include Helpers, ::ERB::Util, Context
-
-
# Specify the proc used to decorate input tags that refer to attributes with errors.
-
1
cattr_accessor :field_error_proc
-
1
@@field_error_proc = Proc.new{ |html_tag, instance| "<div class=\"field_with_errors\">#{html_tag}</div>".html_safe }
-
-
# How to complete the streaming when an exception occurs.
-
# This is our best guess: first try to close the attribute, then the tag.
-
1
cattr_accessor :streaming_completion_on_exception
-
1
@@streaming_completion_on_exception = %("><script>window.location = "/500.html"</script></html>)
-
-
# Specify whether rendering within namespaced controllers should prefix
-
# the partial paths for ActiveModel objects with the namespace.
-
# (e.g., an Admin::PostsController would render @post using /admin/posts/_post.erb)
-
1
cattr_accessor :prefix_partial_path_with_controller_namespace
-
1
@@prefix_partial_path_with_controller_namespace = true
-
-
# Specify default_formats that can be rendered.
-
1
cattr_accessor :default_formats
-
-
# Specify whether an error should be raised for missing translations
-
1
cattr_accessor :raise_on_missing_translations
-
1
@@raise_on_missing_translations = false
-
-
1
class_attribute :_routes
-
1
class_attribute :logger
-
-
1
class << self
-
1
delegate :erb_trim_mode=, :to => 'ActionView::Template::Handlers::ERB'
-
-
1
def cache_template_loading
-
ActionView::Resolver.caching?
-
end
-
-
1
def cache_template_loading=(value)
-
ActionView::Resolver.caching = value
-
end
-
-
1
def xss_safe? #:nodoc:
-
true
-
end
-
end
-
-
1
attr_accessor :view_renderer
-
1
attr_internal :config, :assigns
-
-
1
delegate :lookup_context, :to => :view_renderer
-
1
delegate :formats, :formats=, :locale, :locale=, :view_paths, :view_paths=, :to => :lookup_context
-
-
1
def assign(new_assigns) # :nodoc:
-
@_assigns = new_assigns.each { |key, value| instance_variable_set("@#{key}", value) }
-
end
-
-
1
def initialize(context = nil, assigns = {}, controller = nil, formats = nil) #:nodoc:
-
@_config = ActiveSupport::InheritableOptions.new
-
-
if context.is_a?(ActionView::Renderer)
-
@view_renderer = context
-
else
-
lookup_context = context.is_a?(ActionView::LookupContext) ?
-
context : ActionView::LookupContext.new(context)
-
lookup_context.formats = formats if formats
-
lookup_context.prefixes = controller._prefixes if controller
-
@view_renderer = ActionView::Renderer.new(lookup_context)
-
end
-
-
assign(assigns)
-
assign_controller(controller)
-
_prepare_context
-
end
-
-
1
ActiveSupport.run_load_hooks(:action_view, self)
-
end
-
end
-
1
module ActionView
-
1
module CompiledTemplates #:nodoc:
-
# holds compiled template code
-
end
-
-
# = Action View Context
-
#
-
# Action View contexts are supplied to Action Controller to render a template.
-
# The default Action View context is ActionView::Base.
-
#
-
# In order to work with ActionController, a Context must just include this module.
-
# The initialization of the variables used by the context (@output_buffer, @view_flow,
-
# and @virtual_path) is responsibility of the object that includes this module
-
# (although you can call _prepare_context defined below).
-
1
module Context
-
1
include CompiledTemplates
-
1
attr_accessor :output_buffer, :view_flow
-
-
# Prepares the context by setting the appropriate instance variables.
-
# :api: plugin
-
1
def _prepare_context
-
@view_flow = OutputFlow.new
-
@output_buffer = nil
-
@virtual_path = nil
-
end
-
-
# Encapsulates the interaction with the view flow so it
-
# returns the correct buffer on +yield+. This is usually
-
# overwritten by helpers to add more behavior.
-
# :api: plugin
-
1
def _layout_for(name=nil)
-
name ||= :layout
-
view_flow.get(name).html_safe
-
end
-
end
-
end
-
1
module ActionView
-
# Returns the version of the currently loaded ActionView as a <tt>Gem::Version</tt>
-
1
def self.gem_version
-
Gem::Version.new VERSION::STRING
-
end
-
-
1
module VERSION
-
1
MAJOR = 4
-
1
MINOR = 1
-
1
TINY = 0
-
1
PRE = nil
-
-
1
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
-
end
-
end
-
1
require 'active_support/benchmarkable'
-
-
1
module ActionView #:nodoc:
-
1
module Helpers #:nodoc:
-
1
extend ActiveSupport::Autoload
-
-
1
autoload :ActiveModelHelper
-
1
autoload :AssetTagHelper
-
1
autoload :AssetUrlHelper
-
1
autoload :AtomFeedHelper
-
1
autoload :CacheHelper
-
1
autoload :CaptureHelper
-
1
autoload :ControllerHelper
-
1
autoload :CsrfHelper
-
1
autoload :DateHelper
-
1
autoload :DebugHelper
-
1
autoload :FormHelper
-
1
autoload :FormOptionsHelper
-
1
autoload :FormTagHelper
-
1
autoload :JavaScriptHelper, "action_view/helpers/javascript_helper"
-
1
autoload :NumberHelper
-
1
autoload :OutputSafetyHelper
-
1
autoload :RecordTagHelper
-
1
autoload :RenderingHelper
-
1
autoload :SanitizeHelper
-
1
autoload :TagHelper
-
1
autoload :TextHelper
-
1
autoload :TranslationHelper
-
1
autoload :UrlHelper
-
1
autoload :Tags
-
-
1
def self.eager_load!
-
super
-
Tags.eager_load!
-
end
-
-
1
extend ActiveSupport::Concern
-
-
1
include ActiveSupport::Benchmarkable
-
1
include ActiveModelHelper
-
1
include AssetTagHelper
-
1
include AssetUrlHelper
-
1
include AtomFeedHelper
-
1
include CacheHelper
-
1
include CaptureHelper
-
1
include ControllerHelper
-
1
include CsrfHelper
-
1
include DateHelper
-
1
include DebugHelper
-
1
include FormHelper
-
1
include FormOptionsHelper
-
1
include FormTagHelper
-
1
include JavaScriptHelper
-
1
include NumberHelper
-
1
include OutputSafetyHelper
-
1
include RecordTagHelper
-
1
include RenderingHelper
-
1
include SanitizeHelper
-
1
include TagHelper
-
1
include TextHelper
-
1
include TranslationHelper
-
1
include UrlHelper
-
end
-
end
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/enumerable'
-
-
1
module ActionView
-
# = Active Model Helpers
-
1
module Helpers
-
1
module ActiveModelHelper
-
end
-
-
1
module ActiveModelInstanceTag
-
1
def object
-
@active_model_object ||= begin
-
object = super
-
object.respond_to?(:to_model) ? object.to_model : object
-
end
-
end
-
-
1
def content_tag(*)
-
error_wrapping(super)
-
end
-
-
1
def tag(type, options, *)
-
tag_generate_errors?(options) ? error_wrapping(super) : super
-
end
-
-
1
def error_wrapping(html_tag)
-
if object_has_errors?
-
Base.field_error_proc.call(html_tag, self)
-
else
-
html_tag
-
end
-
end
-
-
1
def error_message
-
object.errors[@method_name]
-
end
-
-
1
private
-
-
1
def object_has_errors?
-
object.respond_to?(:errors) && object.errors.respond_to?(:[]) && error_message.present?
-
end
-
-
1
def tag_generate_errors?(options)
-
options['type'] != 'hidden'
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'active_support/core_ext/hash/keys'
-
1
require 'action_view/helpers/asset_url_helper'
-
1
require 'action_view/helpers/tag_helper'
-
-
1
module ActionView
-
# = Action View Asset Tag Helpers
-
1
module Helpers #:nodoc:
-
# This module provides methods for generating HTML that links views to assets such
-
# as images, javascripts, stylesheets, and feeds. These methods do not verify
-
# the assets exist before linking to them:
-
#
-
# image_tag("rails.png")
-
# # => <img alt="Rails" src="/assets/rails.png" />
-
# stylesheet_link_tag("application")
-
# # => <link href="/assets/application.css?body=1" media="screen" rel="stylesheet" />
-
1
module AssetTagHelper
-
1
extend ActiveSupport::Concern
-
-
1
include AssetUrlHelper
-
1
include TagHelper
-
-
# Returns an HTML script tag for each of the +sources+ provided.
-
#
-
# Sources may be paths to JavaScript files. Relative paths are assumed to be relative
-
# to <tt>assets/javascripts</tt>, full paths are assumed to be relative to the document
-
# root. Relative paths are idiomatic, use absolute paths only when needed.
-
#
-
# When passing paths, the ".js" extension is optional. If you do not want ".js"
-
# appended to the path <tt>extname: false</tt> can be set on the options.
-
#
-
# You can modify the HTML attributes of the script tag by passing a hash as the
-
# last argument.
-
#
-
# When the Asset Pipeline is enabled, you can pass the name of your manifest as
-
# source, and include other JavaScript or CoffeeScript files inside the manifest.
-
#
-
# javascript_include_tag "xmlhr"
-
# # => <script src="/assets/xmlhr.js?1284139606"></script>
-
#
-
# javascript_include_tag "template.jst", extname: false
-
# # => <script src="/assets/template.jst?1284139606"></script>
-
#
-
# javascript_include_tag "xmlhr.js"
-
# # => <script src="/assets/xmlhr.js?1284139606"></script>
-
#
-
# javascript_include_tag "common.javascript", "/elsewhere/cools"
-
# # => <script src="/assets/common.javascript?1284139606"></script>
-
# # <script src="/elsewhere/cools.js?1423139606"></script>
-
#
-
# javascript_include_tag "http://www.example.com/xmlhr"
-
# # => <script src="http://www.example.com/xmlhr"></script>
-
#
-
# javascript_include_tag "http://www.example.com/xmlhr.js"
-
# # => <script src="http://www.example.com/xmlhr.js"></script>
-
1
def javascript_include_tag(*sources)
-
options = sources.extract_options!.stringify_keys
-
path_options = options.extract!('protocol', 'extname').symbolize_keys
-
sources.uniq.map { |source|
-
tag_options = {
-
"src" => path_to_javascript(source, path_options)
-
}.merge!(options)
-
content_tag(:script, "", tag_options)
-
}.join("\n").html_safe
-
end
-
-
# Returns a stylesheet link tag for the sources specified as arguments. If
-
# you don't specify an extension, <tt>.css</tt> will be appended automatically.
-
# You can modify the link attributes by passing a hash as the last argument.
-
# For historical reasons, the 'media' attribute will always be present and defaults
-
# to "screen", so you must explicitly set it to "all" for the stylesheet(s) to
-
# apply to all media types.
-
#
-
# stylesheet_link_tag "style"
-
# # => <link href="/assets/style.css" media="screen" rel="stylesheet" />
-
#
-
# stylesheet_link_tag "style.css"
-
# # => <link href="/assets/style.css" media="screen" rel="stylesheet" />
-
#
-
# stylesheet_link_tag "http://www.example.com/style.css"
-
# # => <link href="http://www.example.com/style.css" media="screen" rel="stylesheet" />
-
#
-
# stylesheet_link_tag "style", media: "all"
-
# # => <link href="/assets/style.css" media="all" rel="stylesheet" />
-
#
-
# stylesheet_link_tag "style", media: "print"
-
# # => <link href="/assets/style.css" media="print" rel="stylesheet" />
-
#
-
# stylesheet_link_tag "random.styles", "/css/stylish"
-
# # => <link href="/assets/random.styles" media="screen" rel="stylesheet" />
-
# # <link href="/css/stylish.css" media="screen" rel="stylesheet" />
-
1
def stylesheet_link_tag(*sources)
-
options = sources.extract_options!.stringify_keys
-
path_options = options.extract!('protocol').symbolize_keys
-
-
sources.uniq.map { |source|
-
tag_options = {
-
"rel" => "stylesheet",
-
"media" => "screen",
-
"href" => path_to_stylesheet(source, path_options)
-
}.merge!(options)
-
tag(:link, tag_options)
-
}.join("\n").html_safe
-
end
-
-
# Returns a link tag that browsers and feed readers can use to auto-detect
-
# an RSS or Atom feed. The +type+ can either be <tt>:rss</tt> (default) or
-
# <tt>:atom</tt>. Control the link options in url_for format using the
-
# +url_options+. You can modify the LINK tag itself in +tag_options+.
-
#
-
# ==== Options
-
#
-
# * <tt>:rel</tt> - Specify the relation of this link, defaults to "alternate"
-
# * <tt>:type</tt> - Override the auto-generated mime type
-
# * <tt>:title</tt> - Specify the title of the link, defaults to the +type+
-
#
-
# ==== Examples
-
#
-
# auto_discovery_link_tag
-
# # => <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/controller/action" />
-
# auto_discovery_link_tag(:atom)
-
# # => <link rel="alternate" type="application/atom+xml" title="ATOM" href="http://www.currenthost.com/controller/action" />
-
# auto_discovery_link_tag(:rss, {action: "feed"})
-
# # => <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/controller/feed" />
-
# auto_discovery_link_tag(:rss, {action: "feed"}, {title: "My RSS"})
-
# # => <link rel="alternate" type="application/rss+xml" title="My RSS" href="http://www.currenthost.com/controller/feed" />
-
# auto_discovery_link_tag(:rss, {controller: "news", action: "feed"})
-
# # => <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/news/feed" />
-
# auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {title: "Example RSS"})
-
# # => <link rel="alternate" type="application/rss+xml" title="Example RSS" href="http://www.example.com/feed" />
-
1
def auto_discovery_link_tag(type = :rss, url_options = {}, tag_options = {})
-
if !(type == :rss || type == :atom) && tag_options[:type].blank?
-
raise ArgumentError.new("You should pass :type tag_option key explicitly, because you have passed #{type} type other than :rss or :atom.")
-
end
-
-
tag(
-
"link",
-
"rel" => tag_options[:rel] || "alternate",
-
"type" => tag_options[:type] || Mime::Type.lookup_by_extension(type.to_s).to_s,
-
"title" => tag_options[:title] || type.to_s.upcase,
-
"href" => url_options.is_a?(Hash) ? url_for(url_options.merge(:only_path => false)) : url_options
-
)
-
end
-
-
# Returns a link loading a favicon file. You may specify a different file
-
# in the first argument. The helper accepts an additional options hash where
-
# you can override "rel" and "type".
-
#
-
# ==== Options
-
#
-
# * <tt>:rel</tt> - Specify the relation of this link, defaults to 'shortcut icon'
-
# * <tt>:type</tt> - Override the auto-generated mime type, defaults to 'image/vnd.microsoft.icon'
-
#
-
# ==== Examples
-
#
-
# favicon_link_tag 'myicon.ico'
-
# # => <link href="/assets/myicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon" />
-
#
-
# Mobile Safari looks for a different <link> tag, pointing to an image that
-
# will be used if you add the page to the home screen of an iPod Touch, iPhone, or iPad.
-
# The following call would generate such a tag:
-
#
-
# favicon_link_tag 'mb-icon.png', rel: 'apple-touch-icon', type: 'image/png'
-
# # => <link href="/assets/mb-icon.png" rel="apple-touch-icon" type="image/png" />
-
1
def favicon_link_tag(source='favicon.ico', options={})
-
tag('link', {
-
:rel => 'shortcut icon',
-
:type => 'image/vnd.microsoft.icon',
-
:href => path_to_image(source)
-
}.merge!(options.symbolize_keys))
-
end
-
-
# Returns an HTML image tag for the +source+. The +source+ can be a full
-
# path or a file.
-
#
-
# ==== Options
-
#
-
# You can add HTML attributes using the +options+. The +options+ supports
-
# two additional keys for convenience and conformance:
-
#
-
# * <tt>:alt</tt> - If no alt text is given, the file name part of the
-
# +source+ is used (capitalized and without the extension)
-
# * <tt>:size</tt> - Supplied as "{Width}x{Height}" or "{Number}", so "30x45" becomes
-
# width="30" and height="45", and "50" becomes width="50" and height="50".
-
# <tt>:size</tt> will be ignored if the value is not in the correct format.
-
#
-
# ==== Examples
-
#
-
# image_tag("icon")
-
# # => <img alt="Icon" src="/assets/icon" />
-
# image_tag("icon.png")
-
# # => <img alt="Icon" src="/assets/icon.png" />
-
# image_tag("icon.png", size: "16x10", alt: "Edit Entry")
-
# # => <img src="/assets/icon.png" width="16" height="10" alt="Edit Entry" />
-
# image_tag("/icons/icon.gif", size: "16")
-
# # => <img src="/icons/icon.gif" width="16" height="16" alt="Icon" />
-
# image_tag("/icons/icon.gif", height: '32', width: '32')
-
# # => <img alt="Icon" height="32" src="/icons/icon.gif" width="32" />
-
# image_tag("/icons/icon.gif", class: "menu_icon")
-
# # => <img alt="Icon" class="menu_icon" src="/icons/icon.gif" />
-
1
def image_tag(source, options={})
-
options = options.symbolize_keys
-
-
src = options[:src] = path_to_image(source)
-
-
unless src =~ /^(?:cid|data):/ || src.blank?
-
options[:alt] = options.fetch(:alt){ image_alt(src) }
-
end
-
-
options[:width], options[:height] = extract_dimensions(options.delete(:size)) if options[:size]
-
tag("img", options)
-
end
-
-
# Returns a string suitable for an html image tag alt attribute.
-
# The +src+ argument is meant to be an image file path.
-
# The method removes the basename of the file path and the digest,
-
# if any. It also removes hyphens and underscores from file names and
-
# replaces them with spaces, returning a space-separated, titleized
-
# string.
-
#
-
# ==== Examples
-
#
-
# image_alt('rails.png')
-
# # => Rails
-
#
-
# image_alt('hyphenated-file-name.png')
-
# # => Hyphenated file name
-
#
-
# image_alt('underscored_file_name.png')
-
# # => Underscored file name
-
1
def image_alt(src)
-
File.basename(src, '.*').sub(/-[[:xdigit:]]{32}\z/, '').tr('-_', ' ').capitalize
-
end
-
-
# Returns an html video tag for the +sources+. If +sources+ is a string,
-
# a single video tag will be returned. If +sources+ is an array, a video
-
# tag with nested source tags for each source will be returned. The
-
# +sources+ can be full paths or files that exists in your public videos
-
# directory.
-
#
-
# ==== Options
-
# You can add HTML attributes using the +options+. The +options+ supports
-
# two additional keys for convenience and conformance:
-
#
-
# * <tt>:poster</tt> - Set an image (like a screenshot) to be shown
-
# before the video loads. The path is calculated like the +src+ of +image_tag+.
-
# * <tt>:size</tt> - Supplied as "{Width}x{Height}" or "{Number}", so "30x45" becomes
-
# width="30" and height="45", and "50" becomes width="50" and height="50".
-
# <tt>:size</tt> will be ignored if the value is not in the correct format.
-
#
-
# ==== Examples
-
#
-
# video_tag("trailer")
-
# # => <video src="/videos/trailer" />
-
# video_tag("trailer.ogg")
-
# # => <video src="/videos/trailer.ogg" />
-
# video_tag("trailer.ogg", controls: true, autobuffer: true)
-
# # => <video autobuffer="autobuffer" controls="controls" src="/videos/trailer.ogg" />
-
# video_tag("trailer.m4v", size: "16x10", poster: "screenshot.png")
-
# # => <video src="/videos/trailer.m4v" width="16" height="10" poster="/assets/screenshot.png" />
-
# video_tag("/trailers/hd.avi", size: "16x16")
-
# # => <video src="/trailers/hd.avi" width="16" height="16" />
-
# video_tag("/trailers/hd.avi", size: "16")
-
# # => <video height="16" src="/trailers/hd.avi" width="16" />
-
# video_tag("/trailers/hd.avi", height: '32', width: '32')
-
# # => <video height="32" src="/trailers/hd.avi" width="32" />
-
# video_tag("trailer.ogg", "trailer.flv")
-
# # => <video><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
-
# video_tag(["trailer.ogg", "trailer.flv"])
-
# # => <video><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
-
# video_tag(["trailer.ogg", "trailer.flv"], size: "160x120")
-
# # => <video height="120" width="160"><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
-
1
def video_tag(*sources)
-
multiple_sources_tag('video', sources) do |options|
-
options[:poster] = path_to_image(options[:poster]) if options[:poster]
-
options[:width], options[:height] = extract_dimensions(options.delete(:size)) if options[:size]
-
end
-
end
-
-
# Returns an HTML audio tag for the +source+.
-
# The +source+ can be full path or file that exists in
-
# your public audios directory.
-
#
-
# audio_tag("sound")
-
# # => <audio src="/audios/sound" />
-
# audio_tag("sound.wav")
-
# # => <audio src="/audios/sound.wav" />
-
# audio_tag("sound.wav", autoplay: true, controls: true)
-
# # => <audio autoplay="autoplay" controls="controls" src="/audios/sound.wav" />
-
# audio_tag("sound.wav", "sound.mid")
-
# # => <audio><source src="/audios/sound.wav" /><source src="/audios/sound.mid" /></audio>
-
1
def audio_tag(*sources)
-
multiple_sources_tag('audio', sources)
-
end
-
-
1
private
-
1
def multiple_sources_tag(type, sources)
-
options = sources.extract_options!.symbolize_keys
-
sources.flatten!
-
-
yield options if block_given?
-
-
if sources.size > 1
-
content_tag(type, options) do
-
safe_join sources.map { |source| tag("source", :src => send("path_to_#{type}", source)) }
-
end
-
else
-
options[:src] = send("path_to_#{type}", sources.first)
-
content_tag(type, nil, options)
-
end
-
end
-
-
1
def extract_dimensions(size)
-
if size =~ %r{\A\d+x\d+\z}
-
size.split('x')
-
elsif size =~ %r{\A\d+\z}
-
[size, size]
-
end
-
end
-
end
-
end
-
end
-
1
require 'zlib'
-
-
1
module ActionView
-
# = Action View Asset URL Helpers
-
1
module Helpers
-
# This module provides methods for generating asset paths and
-
# urls.
-
#
-
# image_path("rails.png")
-
# # => "/assets/rails.png"
-
#
-
# image_url("rails.png")
-
# # => "http://www.example.com/assets/rails.png"
-
#
-
# === Using asset hosts
-
#
-
# By default, Rails links to these assets on the current host in the public
-
# folder, but you can direct Rails to link to assets from a dedicated asset
-
# server by setting <tt>ActionController::Base.asset_host</tt> in the application
-
# configuration, typically in <tt>config/environments/production.rb</tt>.
-
# For example, you'd define <tt>assets.example.com</tt> to be your asset
-
# host this way, inside the <tt>configure</tt> block of your environment-specific
-
# configuration files or <tt>config/application.rb</tt>:
-
#
-
# config.action_controller.asset_host = "assets.example.com"
-
#
-
# Helpers take that into account:
-
#
-
# image_tag("rails.png")
-
# # => <img alt="Rails" src="http://assets.example.com/assets/rails.png" />
-
# stylesheet_link_tag("application")
-
# # => <link href="http://assets.example.com/assets/application.css" media="screen" rel="stylesheet" />
-
#
-
# Browsers typically open at most two simultaneous connections to a single
-
# host, which means your assets often have to wait for other assets to finish
-
# downloading. You can alleviate this by using a <tt>%d</tt> wildcard in the
-
# +asset_host+. For example, "assets%d.example.com". If that wildcard is
-
# present Rails distributes asset requests among the corresponding four hosts
-
# "assets0.example.com", ..., "assets3.example.com". With this trick browsers
-
# will open eight simultaneous connections rather than two.
-
#
-
# image_tag("rails.png")
-
# # => <img alt="Rails" src="http://assets0.example.com/assets/rails.png" />
-
# stylesheet_link_tag("application")
-
# # => <link href="http://assets2.example.com/assets/application.css" media="screen" rel="stylesheet" />
-
#
-
# To do this, you can either setup four actual hosts, or you can use wildcard
-
# DNS to CNAME the wildcard to a single asset host. You can read more about
-
# setting up your DNS CNAME records from your ISP.
-
#
-
# Note: This is purely a browser performance optimization and is not meant
-
# for server load balancing. See http://www.die.net/musings/page_load_time/
-
# for background.
-
#
-
# Alternatively, you can exert more control over the asset host by setting
-
# +asset_host+ to a proc like this:
-
#
-
# ActionController::Base.asset_host = Proc.new { |source|
-
# "http://assets#{Digest::MD5.hexdigest(source).to_i(16) % 2 + 1}.example.com"
-
# }
-
# image_tag("rails.png")
-
# # => <img alt="Rails" src="http://assets1.example.com/assets/rails.png" />
-
# stylesheet_link_tag("application")
-
# # => <link href="http://assets2.example.com/assets/application.css" media="screen" rel="stylesheet" />
-
#
-
# The example above generates "http://assets1.example.com" and
-
# "http://assets2.example.com". This option is useful for example if
-
# you need fewer/more than four hosts, custom host names, etc.
-
#
-
# As you see the proc takes a +source+ parameter. That's a string with the
-
# absolute path of the asset, for example "/assets/rails.png".
-
#
-
# ActionController::Base.asset_host = Proc.new { |source|
-
# if source.ends_with?('.css')
-
# "http://stylesheets.example.com"
-
# else
-
# "http://assets.example.com"
-
# end
-
# }
-
# image_tag("rails.png")
-
# # => <img alt="Rails" src="http://assets.example.com/assets/rails.png" />
-
# stylesheet_link_tag("application")
-
# # => <link href="http://stylesheets.example.com/assets/application.css" media="screen" rel="stylesheet" />
-
#
-
# Alternatively you may ask for a second parameter +request+. That one is
-
# particularly useful for serving assets from an SSL-protected page. The
-
# example proc below disables asset hosting for HTTPS connections, while
-
# still sending assets for plain HTTP requests from asset hosts. If you don't
-
# have SSL certificates for each of the asset hosts this technique allows you
-
# to avoid warnings in the client about mixed media.
-
#
-
# config.action_controller.asset_host = Proc.new { |source, request|
-
# if request.ssl?
-
# "#{request.protocol}#{request.host_with_port}"
-
# else
-
# "#{request.protocol}assets.example.com"
-
# end
-
# }
-
#
-
# You can also implement a custom asset host object that responds to +call+
-
# and takes either one or two parameters just like the proc.
-
#
-
# config.action_controller.asset_host = AssetHostingWithMinimumSsl.new(
-
# "http://asset%d.example.com", "https://asset1.example.com"
-
# )
-
#
-
1
module AssetUrlHelper
-
1
URI_REGEXP = %r{^[-a-z]+://|^(?:cid|data):|^//}i
-
-
# Computes the path to asset in public directory. If :type
-
# options is set, a file extension will be appended and scoped
-
# to the corresponding public directory.
-
#
-
# All other asset *_path helpers delegate through this method.
-
#
-
# asset_path "application.js" # => /application.js
-
# asset_path "application", type: :javascript # => /javascripts/application.js
-
# asset_path "application", type: :stylesheet # => /stylesheets/application.css
-
# asset_path "http://www.example.com/js/xmlhr.js" # => http://www.example.com/js/xmlhr.js
-
1
def asset_path(source, options = {})
-
source = source.to_s
-
return "" unless source.present?
-
return source if source =~ URI_REGEXP
-
-
tail, source = source[/([\?#].+)$/], source.sub(/([\?#].+)$/, '')
-
-
if extname = compute_asset_extname(source, options)
-
source = "#{source}#{extname}"
-
end
-
-
if source[0] != ?/
-
source = compute_asset_path(source, options)
-
end
-
-
relative_url_root = defined?(config.relative_url_root) && config.relative_url_root
-
if relative_url_root
-
source = "#{relative_url_root}#{source}" unless source.starts_with?("#{relative_url_root}/")
-
end
-
-
if host = compute_asset_host(source, options)
-
source = "#{host}#{source}"
-
end
-
-
"#{source}#{tail}"
-
end
-
1
alias_method :path_to_asset, :asset_path # aliased to avoid conflicts with an asset_path named route
-
-
# Computes the full URL to an asset in the public directory. This
-
# will use +asset_path+ internally, so most of their behaviors
-
# will be the same.
-
1
def asset_url(source, options = {})
-
path_to_asset(source, options.merge(:protocol => :request))
-
end
-
1
alias_method :url_to_asset, :asset_url # aliased to avoid conflicts with an asset_url named route
-
-
1
ASSET_EXTENSIONS = {
-
javascript: '.js',
-
stylesheet: '.css'
-
}
-
-
# Compute extname to append to asset path. Returns nil if
-
# nothing should be added.
-
1
def compute_asset_extname(source, options = {})
-
return if options[:extname] == false
-
extname = options[:extname] || ASSET_EXTENSIONS[options[:type]]
-
extname if extname && File.extname(source) != extname
-
end
-
-
# Maps asset types to public directory.
-
1
ASSET_PUBLIC_DIRECTORIES = {
-
audio: '/audios',
-
font: '/fonts',
-
image: '/images',
-
javascript: '/javascripts',
-
stylesheet: '/stylesheets',
-
video: '/videos'
-
}
-
-
# Computes asset path to public directory. Plugins and
-
# extensions can override this method to point to custom assets
-
# or generate digested paths or query strings.
-
1
def compute_asset_path(source, options = {})
-
dir = ASSET_PUBLIC_DIRECTORIES[options[:type]] || ""
-
File.join(dir, source)
-
end
-
-
# Pick an asset host for this source. Returns +nil+ if no host is set,
-
# the host if no wildcard is set, the host interpolated with the
-
# numbers 0-3 if it contains <tt>%d</tt> (the number is the source hash mod 4),
-
# or the value returned from invoking call on an object responding to call
-
# (proc or otherwise).
-
1
def compute_asset_host(source = "", options = {})
-
request = self.request if respond_to?(:request)
-
host = config.asset_host if defined? config.asset_host
-
host ||= request.base_url if request && options[:protocol] == :request
-
-
if host.respond_to?(:call)
-
arity = host.respond_to?(:arity) ? host.arity : host.method(:call).arity
-
args = [source]
-
args << request if request && (arity > 1 || arity < 0)
-
host = host.call(*args)
-
elsif host =~ /%d/
-
host = host % (Zlib.crc32(source) % 4)
-
end
-
-
return unless host
-
-
if host =~ URI_REGEXP
-
host
-
else
-
protocol = options[:protocol] || config.default_asset_host_protocol || (request ? :request : :relative)
-
case protocol
-
when :relative
-
"//#{host}"
-
when :request
-
"#{request.protocol}#{host}"
-
else
-
"#{protocol}://#{host}"
-
end
-
end
-
end
-
-
# Computes the path to a javascript asset in the public javascripts directory.
-
# If the +source+ filename has no extension, .js will be appended (except for explicit URIs)
-
# Full paths from the document root will be passed through.
-
# Used internally by javascript_include_tag to build the script path.
-
#
-
# javascript_path "xmlhr" # => /javascripts/xmlhr.js
-
# javascript_path "dir/xmlhr.js" # => /javascripts/dir/xmlhr.js
-
# javascript_path "/dir/xmlhr" # => /dir/xmlhr.js
-
# javascript_path "http://www.example.com/js/xmlhr" # => http://www.example.com/js/xmlhr
-
# javascript_path "http://www.example.com/js/xmlhr.js" # => http://www.example.com/js/xmlhr.js
-
1
def javascript_path(source, options = {})
-
path_to_asset(source, {type: :javascript}.merge!(options))
-
end
-
1
alias_method :path_to_javascript, :javascript_path # aliased to avoid conflicts with a javascript_path named route
-
-
# Computes the full URL to a javascript asset in the public javascripts directory.
-
# This will use +javascript_path+ internally, so most of their behaviors will be the same.
-
1
def javascript_url(source, options = {})
-
url_to_asset(source, {type: :javascript}.merge!(options))
-
end
-
1
alias_method :url_to_javascript, :javascript_url # aliased to avoid conflicts with a javascript_url named route
-
-
# Computes the path to a stylesheet asset in the public stylesheets directory.
-
# If the +source+ filename has no extension, <tt>.css</tt> will be appended (except for explicit URIs).
-
# Full paths from the document root will be passed through.
-
# Used internally by +stylesheet_link_tag+ to build the stylesheet path.
-
#
-
# stylesheet_path "style" # => /stylesheets/style.css
-
# stylesheet_path "dir/style.css" # => /stylesheets/dir/style.css
-
# stylesheet_path "/dir/style.css" # => /dir/style.css
-
# stylesheet_path "http://www.example.com/css/style" # => http://www.example.com/css/style
-
# stylesheet_path "http://www.example.com/css/style.css" # => http://www.example.com/css/style.css
-
1
def stylesheet_path(source, options = {})
-
path_to_asset(source, {type: :stylesheet}.merge!(options))
-
end
-
1
alias_method :path_to_stylesheet, :stylesheet_path # aliased to avoid conflicts with a stylesheet_path named route
-
-
# Computes the full URL to a stylesheet asset in the public stylesheets directory.
-
# This will use +stylesheet_path+ internally, so most of their behaviors will be the same.
-
1
def stylesheet_url(source, options = {})
-
url_to_asset(source, {type: :stylesheet}.merge!(options))
-
end
-
1
alias_method :url_to_stylesheet, :stylesheet_url # aliased to avoid conflicts with a stylesheet_url named route
-
-
# Computes the path to an image asset.
-
# Full paths from the document root will be passed through.
-
# Used internally by +image_tag+ to build the image path:
-
#
-
# image_path("edit") # => "/assets/edit"
-
# image_path("edit.png") # => "/assets/edit.png"
-
# image_path("icons/edit.png") # => "/assets/icons/edit.png"
-
# image_path("/icons/edit.png") # => "/icons/edit.png"
-
# image_path("http://www.example.com/img/edit.png") # => "http://www.example.com/img/edit.png"
-
#
-
# If you have images as application resources this method may conflict with their named routes.
-
# The alias +path_to_image+ is provided to avoid that. Rails uses the alias internally, and
-
# plugin authors are encouraged to do so.
-
1
def image_path(source, options = {})
-
path_to_asset(source, {type: :image}.merge!(options))
-
end
-
1
alias_method :path_to_image, :image_path # aliased to avoid conflicts with an image_path named route
-
-
# Computes the full URL to an image asset.
-
# This will use +image_path+ internally, so most of their behaviors will be the same.
-
1
def image_url(source, options = {})
-
url_to_asset(source, {type: :image}.merge!(options))
-
end
-
1
alias_method :url_to_image, :image_url # aliased to avoid conflicts with an image_url named route
-
-
# Computes the path to a video asset in the public videos directory.
-
# Full paths from the document root will be passed through.
-
# Used internally by +video_tag+ to build the video path.
-
#
-
# video_path("hd") # => /videos/hd
-
# video_path("hd.avi") # => /videos/hd.avi
-
# video_path("trailers/hd.avi") # => /videos/trailers/hd.avi
-
# video_path("/trailers/hd.avi") # => /trailers/hd.avi
-
# video_path("http://www.example.com/vid/hd.avi") # => http://www.example.com/vid/hd.avi
-
1
def video_path(source, options = {})
-
path_to_asset(source, {type: :video}.merge!(options))
-
end
-
1
alias_method :path_to_video, :video_path # aliased to avoid conflicts with a video_path named route
-
-
# Computes the full URL to a video asset in the public videos directory.
-
# This will use +video_path+ internally, so most of their behaviors will be the same.
-
1
def video_url(source, options = {})
-
url_to_asset(source, {type: :video}.merge!(options))
-
end
-
1
alias_method :url_to_video, :video_url # aliased to avoid conflicts with an video_url named route
-
-
# Computes the path to an audio asset in the public audios directory.
-
# Full paths from the document root will be passed through.
-
# Used internally by +audio_tag+ to build the audio path.
-
#
-
# audio_path("horse") # => /audios/horse
-
# audio_path("horse.wav") # => /audios/horse.wav
-
# audio_path("sounds/horse.wav") # => /audios/sounds/horse.wav
-
# audio_path("/sounds/horse.wav") # => /sounds/horse.wav
-
# audio_path("http://www.example.com/sounds/horse.wav") # => http://www.example.com/sounds/horse.wav
-
1
def audio_path(source, options = {})
-
path_to_asset(source, {type: :audio}.merge!(options))
-
end
-
1
alias_method :path_to_audio, :audio_path # aliased to avoid conflicts with an audio_path named route
-
-
# Computes the full URL to an audio asset in the public audios directory.
-
# This will use +audio_path+ internally, so most of their behaviors will be the same.
-
1
def audio_url(source, options = {})
-
url_to_asset(source, {type: :audio}.merge!(options))
-
end
-
1
alias_method :url_to_audio, :audio_url # aliased to avoid conflicts with an audio_url named route
-
-
# Computes the path to a font asset.
-
# Full paths from the document root will be passed through.
-
#
-
# font_path("font") # => /assets/font
-
# font_path("font.ttf") # => /assets/font.ttf
-
# font_path("dir/font.ttf") # => /assets/dir/font.ttf
-
# font_path("/dir/font.ttf") # => /dir/font.ttf
-
# font_path("http://www.example.com/dir/font.ttf") # => http://www.example.com/dir/font.ttf
-
1
def font_path(source, options = {})
-
path_to_asset(source, {type: :font}.merge!(options))
-
end
-
1
alias_method :path_to_font, :font_path # aliased to avoid conflicts with an font_path named route
-
-
# Computes the full URL to a font asset.
-
# This will use +font_path+ internally, so most of their behaviors will be the same.
-
1
def font_url(source, options = {})
-
url_to_asset(source, {type: :font}.merge!(options))
-
end
-
1
alias_method :url_to_font, :font_url # aliased to avoid conflicts with an font_url named route
-
end
-
end
-
end
-
1
require 'set'
-
-
1
module ActionView
-
# = Action View Atom Feed Helpers
-
1
module Helpers
-
1
module AtomFeedHelper
-
# Adds easy defaults to writing Atom feeds with the Builder template engine (this does not work on ERB or any other
-
# template languages).
-
#
-
# Full usage example:
-
#
-
# config/routes.rb:
-
# Basecamp::Application.routes.draw do
-
# resources :posts
-
# root to: "posts#index"
-
# end
-
#
-
# app/controllers/posts_controller.rb:
-
# class PostsController < ApplicationController::Base
-
# # GET /posts.html
-
# # GET /posts.atom
-
# def index
-
# @posts = Post.all
-
#
-
# respond_to do |format|
-
# format.html
-
# format.atom
-
# end
-
# end
-
# end
-
#
-
# app/views/posts/index.atom.builder:
-
# atom_feed do |feed|
-
# feed.title("My great blog!")
-
# feed.updated(@posts[0].created_at) if @posts.length > 0
-
#
-
# @posts.each do |post|
-
# feed.entry(post) do |entry|
-
# entry.title(post.title)
-
# entry.content(post.body, type: 'html')
-
#
-
# entry.author do |author|
-
# author.name("DHH")
-
# end
-
# end
-
# end
-
# end
-
#
-
# The options for atom_feed are:
-
#
-
# * <tt>:language</tt>: Defaults to "en-US".
-
# * <tt>:root_url</tt>: The HTML alternative that this feed is doubling for. Defaults to / on the current host.
-
# * <tt>:url</tt>: The URL for this feed. Defaults to the current URL.
-
# * <tt>:id</tt>: The id for this feed. Defaults to "tag:#{request.host},#{options[:schema_date]}:#{request.fullpath.split(".")[0]}"
-
# * <tt>:schema_date</tt>: The date at which the tag scheme for the feed was first used. A good default is the year you
-
# created the feed. See http://feedvalidator.org/docs/error/InvalidTAG.html for more information. If not specified,
-
# 2005 is used (as an "I don't care" value).
-
# * <tt>:instruct</tt>: Hash of XML processing instructions in the form {target => {attribute => value, }} or {target => [{attribute => value, }, ]}
-
#
-
# Other namespaces can be added to the root element:
-
#
-
# app/views/posts/index.atom.builder:
-
# atom_feed({'xmlns:app' => 'http://www.w3.org/2007/app',
-
# 'xmlns:openSearch' => 'http://a9.com/-/spec/opensearch/1.1/'}) do |feed|
-
# feed.title("My great blog!")
-
# feed.updated((@posts.first.created_at))
-
# feed.tag!('openSearch:totalResults', 10)
-
#
-
# @posts.each do |post|
-
# feed.entry(post) do |entry|
-
# entry.title(post.title)
-
# entry.content(post.body, type: 'html')
-
# entry.tag!('app:edited', Time.now)
-
#
-
# entry.author do |author|
-
# author.name("DHH")
-
# end
-
# end
-
# end
-
# end
-
#
-
# The Atom spec defines five elements (content rights title subtitle
-
# summary) which may directly contain xhtml content if type: 'xhtml'
-
# is specified as an attribute. If so, this helper will take care of
-
# the enclosing div and xhtml namespace declaration. Example usage:
-
#
-
# entry.summary type: 'xhtml' do |xhtml|
-
# xhtml.p pluralize(order.line_items.count, "line item")
-
# xhtml.p "Shipped to #{order.address}"
-
# xhtml.p "Paid by #{order.pay_type}"
-
# end
-
#
-
#
-
# <tt>atom_feed</tt> yields an +AtomFeedBuilder+ instance. Nested elements yield
-
# an +AtomBuilder+ instance.
-
1
def atom_feed(options = {}, &block)
-
if options[:schema_date]
-
options[:schema_date] = options[:schema_date].strftime("%Y-%m-%d") if options[:schema_date].respond_to?(:strftime)
-
else
-
options[:schema_date] = "2005" # The Atom spec copyright date
-
end
-
-
xml = options.delete(:xml) || eval("xml", block.binding)
-
xml.instruct!
-
if options[:instruct]
-
options[:instruct].each do |target,attrs|
-
if attrs.respond_to?(:keys)
-
xml.instruct!(target, attrs)
-
elsif attrs.respond_to?(:each)
-
attrs.each { |attr_group| xml.instruct!(target, attr_group) }
-
end
-
end
-
end
-
-
feed_opts = {"xml:lang" => options[:language] || "en-US", "xmlns" => 'http://www.w3.org/2005/Atom'}
-
feed_opts.merge!(options).reject!{|k,v| !k.to_s.match(/^xml/)}
-
-
xml.feed(feed_opts) do
-
xml.id(options[:id] || "tag:#{request.host},#{options[:schema_date]}:#{request.fullpath.split(".")[0]}")
-
xml.link(:rel => 'alternate', :type => 'text/html', :href => options[:root_url] || (request.protocol + request.host_with_port))
-
xml.link(:rel => 'self', :type => 'application/atom+xml', :href => options[:url] || request.url)
-
-
yield AtomFeedBuilder.new(xml, self, options)
-
end
-
end
-
-
1
class AtomBuilder #:nodoc:
-
1
XHTML_TAG_NAMES = %w(content rights title subtitle summary).to_set
-
-
1
def initialize(xml)
-
@xml = xml
-
end
-
-
1
private
-
# Delegate to xml builder, first wrapping the element in a xhtml
-
# namespaced div element if the method and arguments indicate
-
# that an xhtml_block? is desired.
-
1
def method_missing(method, *arguments, &block)
-
if xhtml_block?(method, arguments)
-
@xml.__send__(method, *arguments) do
-
@xml.div(:xmlns => 'http://www.w3.org/1999/xhtml') do |xhtml|
-
block.call(xhtml)
-
end
-
end
-
else
-
@xml.__send__(method, *arguments, &block)
-
end
-
end
-
-
# True if the method name matches one of the five elements defined
-
# in the Atom spec as potentially containing XHTML content and
-
# if type: 'xhtml' is, in fact, specified.
-
1
def xhtml_block?(method, arguments)
-
if XHTML_TAG_NAMES.include?(method.to_s)
-
last = arguments.last
-
last.is_a?(Hash) && last[:type].to_s == 'xhtml'
-
end
-
end
-
end
-
-
1
class AtomFeedBuilder < AtomBuilder #:nodoc:
-
1
def initialize(xml, view, feed_options = {})
-
@xml, @view, @feed_options = xml, view, feed_options
-
end
-
-
# Accepts a Date or Time object and inserts it in the proper format. If nil is passed, current time in UTC is used.
-
1
def updated(date_or_time = nil)
-
@xml.updated((date_or_time || Time.now.utc).xmlschema)
-
end
-
-
# Creates an entry tag for a specific record and prefills the id using class and id.
-
#
-
# Options:
-
#
-
# * <tt>:published</tt>: Time first published. Defaults to the created_at attribute on the record if one such exists.
-
# * <tt>:updated</tt>: Time of update. Defaults to the updated_at attribute on the record if one such exists.
-
# * <tt>:url</tt>: The URL for this entry. Defaults to the polymorphic_url for the record.
-
# * <tt>:id</tt>: The ID for this entry. Defaults to "tag:#{@view.request.host},#{@feed_options[:schema_date]}:#{record.class}/#{record.id}"
-
# * <tt>:type</tt>: The TYPE for this entry. Defaults to "text/html".
-
1
def entry(record, options = {})
-
@xml.entry do
-
@xml.id(options[:id] || "tag:#{@view.request.host},#{@feed_options[:schema_date]}:#{record.class}/#{record.id}")
-
-
if options[:published] || (record.respond_to?(:created_at) && record.created_at)
-
@xml.published((options[:published] || record.created_at).xmlschema)
-
end
-
-
if options[:updated] || (record.respond_to?(:updated_at) && record.updated_at)
-
@xml.updated((options[:updated] || record.updated_at).xmlschema)
-
end
-
-
type = options.fetch(:type, 'text/html')
-
-
@xml.link(:rel => 'alternate', :type => type, :href => options[:url] || @view.polymorphic_url(record))
-
-
yield AtomBuilder.new(@xml)
-
end
-
end
-
end
-
-
end
-
end
-
end
-
1
module ActionView
-
# = Action View Cache Helper
-
1
module Helpers
-
1
module CacheHelper
-
# This helper exposes a method for caching fragments of a view
-
# rather than an entire action or page. This technique is useful
-
# caching pieces like menus, lists of new topics, static HTML
-
# fragments, and so on. This method takes a block that contains
-
# the content you wish to cache.
-
#
-
# The best way to use this is by doing key-based cache expiration
-
# on top of a cache store like Memcached that'll automatically
-
# kick out old entries. For more on key-based expiration, see:
-
# http://37signals.com/svn/posts/3113-how-key-based-cache-expiration-works
-
#
-
# When using this method, you list the cache dependency as the name of the cache, like so:
-
#
-
# <% cache project do %>
-
# <b>All the topics on this project</b>
-
# <%= render project.topics %>
-
# <% end %>
-
#
-
# This approach will assume that when a new topic is added, you'll touch
-
# the project. The cache key generated from this call will be something like:
-
#
-
# views/projects/123-20120806214154/7a1156131a6928cb0026877f8b749ac9
-
# ^class ^id ^updated_at ^template tree digest
-
#
-
# The cache is thus automatically bumped whenever the project updated_at is touched.
-
#
-
# If your template cache depends on multiple sources (try to avoid this to keep things simple),
-
# you can name all these dependencies as part of an array:
-
#
-
# <% cache [ project, current_user ] do %>
-
# <b>All the topics on this project</b>
-
# <%= render project.topics %>
-
# <% end %>
-
#
-
# This will include both records as part of the cache key and updating either of them will
-
# expire the cache.
-
#
-
# ==== Template digest
-
#
-
# The template digest that's added to the cache key is computed by taking an md5 of the
-
# contents of the entire template file. This ensures that your caches will automatically
-
# expire when you change the template file.
-
#
-
# Note that the md5 is taken of the entire template file, not just what's within the
-
# cache do/end call. So it's possible that changing something outside of that call will
-
# still expire the cache.
-
#
-
# Additionally, the digestor will automatically look through your template file for
-
# explicit and implicit dependencies, and include those as part of the digest.
-
#
-
# The digestor can be bypassed by passing skip_digest: true as an option to the cache call:
-
#
-
# <% cache project, skip_digest: true do %>
-
# <b>All the topics on this project</b>
-
# <%= render project.topics %>
-
# <% end %>
-
#
-
# ==== Implicit dependencies
-
#
-
# Most template dependencies can be derived from calls to render in the template itself.
-
# Here are some examples of render calls that Cache Digests knows how to decode:
-
#
-
# render partial: "comments/comment", collection: commentable.comments
-
# render "comments/comments"
-
# render 'comments/comments'
-
# render('comments/comments')
-
#
-
# render "header" => render("comments/header")
-
#
-
# render(@topic) => render("topics/topic")
-
# render(topics) => render("topics/topic")
-
# render(message.topics) => render("topics/topic")
-
#
-
# It's not possible to derive all render calls like that, though. Here are a few examples of things that can't be derived:
-
#
-
# render group_of_attachments
-
# render @project.documents.where(published: true).order('created_at')
-
#
-
# You will have to rewrite those to the explicit form:
-
#
-
# render partial: 'attachments/attachment', collection: group_of_attachments
-
# render partial: 'documents/document', collection: @project.documents.where(published: true).order('created_at')
-
#
-
# === Explicit dependencies
-
#
-
# Some times you'll have template dependencies that can't be derived at all. This is typically
-
# the case when you have template rendering that happens in helpers. Here's an example:
-
#
-
# <%= render_sortable_todolists @project.todolists %>
-
#
-
# You'll need to use a special comment format to call those out:
-
#
-
# <%# Template Dependency: todolists/todolist %>
-
# <%= render_sortable_todolists @project.todolists %>
-
#
-
# The pattern used to match these is /# Template Dependency: ([^ ]+)/, so it's important that you type it out just so.
-
# You can only declare one template dependency per line.
-
#
-
# === External dependencies
-
#
-
# If you use a helper method, for example, inside of a cached block and you then update that helper,
-
# you'll have to bump the cache as well. It doesn't really matter how you do it, but the md5 of the template file
-
# must change. One recommendation is to simply be explicit in a comment, like:
-
#
-
# <%# Helper Dependency Updated: May 6, 2012 at 6pm %>
-
# <%= some_helper_method(person) %>
-
#
-
# Now all you'll have to do is change that timestamp when the helper method changes.
-
1
def cache(name = {}, options = nil, &block)
-
if controller.perform_caching
-
safe_concat(fragment_for(cache_fragment_name(name, options), options, &block))
-
else
-
yield
-
end
-
-
nil
-
end
-
-
# Cache fragments of a view if +condition+ is true
-
#
-
# <%= cache_if admin?, project do %>
-
# <b>All the topics on this project</b>
-
# <%= render project.topics %>
-
# <% end %>
-
1
def cache_if(condition, name = {}, options = nil, &block)
-
if condition
-
cache(name, options, &block)
-
else
-
yield
-
end
-
-
nil
-
end
-
-
# Cache fragments of a view unless +condition+ is true
-
#
-
# <%= cache_unless admin?, project do %>
-
# <b>All the topics on this project</b>
-
# <%= render project.topics %>
-
# <% end %>
-
1
def cache_unless(condition, name = {}, options = nil, &block)
-
cache_if !condition, name, options, &block
-
end
-
-
# This helper returns the name of a cache key for a given fragment cache
-
# call. By supplying skip_digest: true to cache, the digestion of cache
-
# fragments can be manually bypassed. This is useful when cache fragments
-
# cannot be manually expired unless you know the exact key which is the
-
# case when using memcached.
-
1
def cache_fragment_name(name = {}, options = nil)
-
skip_digest = options && options[:skip_digest]
-
-
if skip_digest
-
name
-
else
-
fragment_name_with_digest(name)
-
end
-
end
-
-
1
private
-
-
1
def fragment_name_with_digest(name) #:nodoc:
-
if @virtual_path
-
names = Array(name.is_a?(Hash) ? controller.url_for(name).split("://").last : name)
-
digest = Digestor.digest name: @virtual_path, finder: lookup_context, dependencies: view_cache_dependencies
-
-
[ *names, digest ]
-
else
-
name
-
end
-
end
-
-
# TODO: Create an object that has caching read/write on it
-
1
def fragment_for(name = {}, options = nil, &block) #:nodoc:
-
read_fragment_for(name, options) || write_fragment_for(name, options, &block)
-
end
-
-
1
def read_fragment_for(name, options) #:nodoc:
-
controller.read_fragment(name, options)
-
end
-
-
1
def write_fragment_for(name, options) #:nodoc:
-
# VIEW TODO: Make #capture usable outside of ERB
-
# This dance is needed because Builder can't use capture
-
pos = output_buffer.length
-
yield
-
output_safe = output_buffer.html_safe?
-
fragment = output_buffer.slice!(pos..-1)
-
if output_safe
-
self.output_buffer = output_buffer.class.new(output_buffer)
-
end
-
controller.write_fragment(name, fragment, options)
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/string/output_safety'
-
-
1
module ActionView
-
# = Action View Capture Helper
-
1
module Helpers
-
# CaptureHelper exposes methods to let you extract generated markup which
-
# can be used in other parts of a template or layout file.
-
#
-
# It provides a method to capture blocks into variables through capture and
-
# a way to capture a block of markup for use in a layout through content_for.
-
1
module CaptureHelper
-
# The capture method allows you to extract part of a template into a
-
# variable. You can then use this variable anywhere in your templates or layout.
-
#
-
# The capture method can be used in ERB templates...
-
#
-
# <% @greeting = capture do %>
-
# Welcome to my shiny new web page! The date and time is
-
# <%= Time.now %>
-
# <% end %>
-
#
-
# ...and Builder (RXML) templates.
-
#
-
# @timestamp = capture do
-
# "The current timestamp is #{Time.now}."
-
# end
-
#
-
# You can then use that variable anywhere else. For example:
-
#
-
# <html>
-
# <head><title><%= @greeting %></title></head>
-
# <body>
-
# <b><%= @greeting %></b>
-
# </body></html>
-
#
-
1
def capture(*args)
-
value = nil
-
buffer = with_output_buffer { value = yield(*args) }
-
if string = buffer.presence || value and string.is_a?(String)
-
ERB::Util.html_escape string
-
end
-
end
-
-
# Calling content_for stores a block of markup in an identifier for later use.
-
# In order to access this stored content in other templates, helper modules
-
# or the layout, you would pass the identifier as an argument to <tt>content_for</tt>.
-
#
-
# Note: <tt>yield</tt> can still be used to retrieve the stored content, but calling
-
# <tt>yield</tt> doesn't work in helper modules, while <tt>content_for</tt> does.
-
#
-
# <% content_for :not_authorized do %>
-
# alert('You are not authorized to do that!')
-
# <% end %>
-
#
-
# You can then use <tt>content_for :not_authorized</tt> anywhere in your templates.
-
#
-
# <%= content_for :not_authorized if current_user.nil? %>
-
#
-
# This is equivalent to:
-
#
-
# <%= yield :not_authorized if current_user.nil? %>
-
#
-
# <tt>content_for</tt>, however, can also be used in helper modules.
-
#
-
# module StorageHelper
-
# def stored_content
-
# content_for(:storage) || "Your storage is empty"
-
# end
-
# end
-
#
-
# This helper works just like normal helpers.
-
#
-
# <%= stored_content %>
-
#
-
# You can also use the <tt>yield</tt> syntax alongside an existing call to
-
# <tt>yield</tt> in a layout. For example:
-
#
-
# <%# This is the layout %>
-
# <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
-
# <head>
-
# <title>My Website</title>
-
# <%= yield :script %>
-
# </head>
-
# <body>
-
# <%= yield %>
-
# </body>
-
# </html>
-
#
-
# And now, we'll create a view that has a <tt>content_for</tt> call that
-
# creates the <tt>script</tt> identifier.
-
#
-
# <%# This is our view %>
-
# Please login!
-
#
-
# <% content_for :script do %>
-
# <script>alert('You are not authorized to view this page!')</script>
-
# <% end %>
-
#
-
# Then, in another view, you could to do something like this:
-
#
-
# <%= link_to 'Logout', action: 'logout', remote: true %>
-
#
-
# <% content_for :script do %>
-
# <%= javascript_include_tag :defaults %>
-
# <% end %>
-
#
-
# That will place +script+ tags for your default set of JavaScript files on the page;
-
# this technique is useful if you'll only be using these scripts in a few views.
-
#
-
# Note that content_for concatenates (default) the blocks it is given for a particular
-
# identifier in order. For example:
-
#
-
# <% content_for :navigation do %>
-
# <li><%= link_to 'Home', action: 'index' %></li>
-
# <% end %>
-
#
-
# And in other place:
-
#
-
# <% content_for :navigation do %>
-
# <li><%= link_to 'Login', action: 'login' %></li>
-
# <% end %>
-
#
-
# Then, in another template or layout, this code would render both links in order:
-
#
-
# <ul><%= content_for :navigation %></ul>
-
#
-
# If the flush parameter is true content_for replaces the blocks it is given. For example:
-
#
-
# <% content_for :navigation do %>
-
# <li><%= link_to 'Home', action: 'index' %></li>
-
# <% end %>
-
#
-
# <%# Add some other content, or use a different template: %>
-
#
-
# <% content_for :navigation, flush: true do %>
-
# <li><%= link_to 'Login', action: 'login' %></li>
-
# <% end %>
-
#
-
# Then, in another template or layout, this code would render only the last link:
-
#
-
# <ul><%= content_for :navigation %></ul>
-
#
-
# Lastly, simple content can be passed as a parameter:
-
#
-
# <% content_for :script, javascript_include_tag(:defaults) %>
-
#
-
# WARNING: content_for is ignored in caches. So you shouldn't use it for elements that will be fragment cached.
-
1
def content_for(name, content = nil, options = {}, &block)
-
if content || block_given?
-
if block_given?
-
options = content if content
-
content = capture(&block)
-
end
-
if content
-
options[:flush] ? @view_flow.set(name, content) : @view_flow.append(name, content)
-
end
-
nil
-
else
-
@view_flow.get(name).presence
-
end
-
end
-
-
# The same as +content_for+ but when used with streaming flushes
-
# straight back to the layout. In other words, if you want to
-
# concatenate several times to the same buffer when rendering a given
-
# template, you should use +content_for+, if not, use +provide+ to tell
-
# the layout to stop looking for more contents.
-
1
def provide(name, content = nil, &block)
-
content = capture(&block) if block_given?
-
result = @view_flow.append!(name, content) if content
-
result unless content
-
end
-
-
# content_for? checks whether any content has been captured yet using `content_for`.
-
# Useful to render parts of your layout differently based on what is in your views.
-
#
-
# <%# This is the layout %>
-
# <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
-
# <head>
-
# <title>My Website</title>
-
# <%= yield :script %>
-
# </head>
-
# <body class="<%= content_for?(:right_col) ? 'two-column' : 'one-column' %>">
-
# <%= yield %>
-
# <%= yield :right_col %>
-
# </body>
-
# </html>
-
1
def content_for?(name)
-
@view_flow.get(name).present?
-
end
-
-
# Use an alternate output buffer for the duration of the block.
-
# Defaults to a new empty string.
-
1
def with_output_buffer(buf = nil) #:nodoc:
-
unless buf
-
buf = ActionView::OutputBuffer.new
-
buf.force_encoding(output_buffer.encoding) if output_buffer
-
end
-
self.output_buffer, old_buffer = buf, output_buffer
-
yield
-
output_buffer
-
ensure
-
self.output_buffer = old_buffer
-
end
-
-
# Add the output buffer to the response body and start a new one.
-
1
def flush_output_buffer #:nodoc:
-
if output_buffer && !output_buffer.empty?
-
response.stream.write output_buffer
-
self.output_buffer = output_buffer.respond_to?(:clone_empty) ? output_buffer.clone_empty : output_buffer[0, 0]
-
nil
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/attr_internal'
-
-
1
module ActionView
-
1
module Helpers
-
# This module keeps all methods and behavior in ActionView
-
# that simply delegates to the controller.
-
1
module ControllerHelper #:nodoc:
-
1
attr_internal :controller, :request
-
-
1
delegate :request_forgery_protection_token, :params, :session, :cookies, :response, :headers,
-
:flash, :action_name, :controller_name, :controller_path, :to => :controller
-
-
1
def assign_controller(controller)
-
if @_controller = controller
-
@_request = controller.request if controller.respond_to?(:request)
-
@_config = controller.config.inheritable_copy if controller.respond_to?(:config)
-
end
-
end
-
-
1
def logger
-
controller.logger if controller.respond_to?(:logger)
-
end
-
end
-
end
-
end
-
1
module ActionView
-
# = Action View CSRF Helper
-
1
module Helpers
-
1
module CsrfHelper
-
# Returns meta tags "csrf-param" and "csrf-token" with the name of the cross-site
-
# request forgery protection parameter and token, respectively.
-
#
-
# <head>
-
# <%= csrf_meta_tags %>
-
# </head>
-
#
-
# These are used to generate the dynamic forms that implement non-remote links with
-
# <tt>:method</tt>.
-
#
-
# You don't need to use these tags for regular forms as they generate their own hidden fields.
-
#
-
# For AJAX requests other than GETs, extract the "csrf-token" from the meta-tag and send as the
-
# "X-CSRF-Token" HTTP header. If you are using jQuery with jquery-rails this happens automatically.
-
#
-
1
def csrf_meta_tags
-
if protect_against_forgery?
-
[
-
tag('meta', :name => 'csrf-param', :content => request_forgery_protection_token),
-
tag('meta', :name => 'csrf-token', :content => form_authenticity_token)
-
].join("\n").html_safe
-
end
-
end
-
-
# For backwards compatibility.
-
1
alias csrf_meta_tag csrf_meta_tags
-
end
-
end
-
end
-
1
require 'date'
-
1
require 'action_view/helpers/tag_helper'
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'active_support/core_ext/date/conversions'
-
1
require 'active_support/core_ext/hash/slice'
-
1
require 'active_support/core_ext/object/with_options'
-
-
1
module ActionView
-
1
module Helpers
-
# = Action View Date Helpers
-
#
-
# The Date Helper primarily creates select/option tags for different kinds of dates and times or date and time
-
# elements. All of the select-type methods share a number of common options that are as follows:
-
#
-
# * <tt>:prefix</tt> - overwrites the default prefix of "date" used for the select names. So specifying "birthday"
-
# would give \birthday[month] instead of \date[month] if passed to the <tt>select_month</tt> method.
-
# * <tt>:include_blank</tt> - set to true if it should be possible to set an empty date.
-
# * <tt>:discard_type</tt> - set to true if you want to discard the type part of the select name. If set to true,
-
# the <tt>select_month</tt> method would use simply "date" (which can be overwritten using <tt>:prefix</tt>) instead
-
# of \date[month].
-
1
module DateHelper
-
# Reports the approximate distance in time between two Time, Date or DateTime objects or integers as seconds.
-
# Pass <tt>include_seconds: true</tt> if you want more detailed approximations when distance < 1 min, 29 secs.
-
# Distances are reported based on the following table:
-
#
-
# 0 <-> 29 secs # => less than a minute
-
# 30 secs <-> 1 min, 29 secs # => 1 minute
-
# 1 min, 30 secs <-> 44 mins, 29 secs # => [2..44] minutes
-
# 44 mins, 30 secs <-> 89 mins, 29 secs # => about 1 hour
-
# 89 mins, 30 secs <-> 23 hrs, 59 mins, 29 secs # => about [2..24] hours
-
# 23 hrs, 59 mins, 30 secs <-> 41 hrs, 59 mins, 29 secs # => 1 day
-
# 41 hrs, 59 mins, 30 secs <-> 29 days, 23 hrs, 59 mins, 29 secs # => [2..29] days
-
# 29 days, 23 hrs, 59 mins, 30 secs <-> 44 days, 23 hrs, 59 mins, 29 secs # => about 1 month
-
# 44 days, 23 hrs, 59 mins, 30 secs <-> 59 days, 23 hrs, 59 mins, 29 secs # => about 2 months
-
# 59 days, 23 hrs, 59 mins, 30 secs <-> 1 yr minus 1 sec # => [2..12] months
-
# 1 yr <-> 1 yr, 3 months # => about 1 year
-
# 1 yr, 3 months <-> 1 yr, 9 months # => over 1 year
-
# 1 yr, 9 months <-> 2 yr minus 1 sec # => almost 2 years
-
# 2 yrs <-> max time or date # => (same rules as 1 yr)
-
#
-
# With <tt>include_seconds: true</tt> and the difference < 1 minute 29 seconds:
-
# 0-4 secs # => less than 5 seconds
-
# 5-9 secs # => less than 10 seconds
-
# 10-19 secs # => less than 20 seconds
-
# 20-39 secs # => half a minute
-
# 40-59 secs # => less than a minute
-
# 60-89 secs # => 1 minute
-
#
-
# from_time = Time.now
-
# distance_of_time_in_words(from_time, from_time + 50.minutes) # => about 1 hour
-
# distance_of_time_in_words(from_time, 50.minutes.from_now) # => about 1 hour
-
# distance_of_time_in_words(from_time, from_time + 15.seconds) # => less than a minute
-
# distance_of_time_in_words(from_time, from_time + 15.seconds, include_seconds: true) # => less than 20 seconds
-
# distance_of_time_in_words(from_time, 3.years.from_now) # => about 3 years
-
# distance_of_time_in_words(from_time, from_time + 60.hours) # => 3 days
-
# distance_of_time_in_words(from_time, from_time + 45.seconds, include_seconds: true) # => less than a minute
-
# distance_of_time_in_words(from_time, from_time - 45.seconds, include_seconds: true) # => less than a minute
-
# distance_of_time_in_words(from_time, 76.seconds.from_now) # => 1 minute
-
# distance_of_time_in_words(from_time, from_time + 1.year + 3.days) # => about 1 year
-
# distance_of_time_in_words(from_time, from_time + 3.years + 6.months) # => over 3 years
-
# distance_of_time_in_words(from_time, from_time + 4.years + 9.days + 30.minutes + 5.seconds) # => about 4 years
-
#
-
# to_time = Time.now + 6.years + 19.days
-
# distance_of_time_in_words(from_time, to_time, include_seconds: true) # => about 6 years
-
# distance_of_time_in_words(to_time, from_time, include_seconds: true) # => about 6 years
-
# distance_of_time_in_words(Time.now, Time.now) # => less than a minute
-
1
def distance_of_time_in_words(from_time, to_time = 0, options = {})
-
options = {
-
scope: :'datetime.distance_in_words'
-
}.merge!(options)
-
-
from_time = from_time.to_time if from_time.respond_to?(:to_time)
-
to_time = to_time.to_time if to_time.respond_to?(:to_time)
-
from_time, to_time = to_time, from_time if from_time > to_time
-
distance_in_minutes = ((to_time - from_time)/60.0).round
-
distance_in_seconds = (to_time - from_time).round
-
-
I18n.with_options :locale => options[:locale], :scope => options[:scope] do |locale|
-
case distance_in_minutes
-
when 0..1
-
return distance_in_minutes == 0 ?
-
locale.t(:less_than_x_minutes, :count => 1) :
-
locale.t(:x_minutes, :count => distance_in_minutes) unless options[:include_seconds]
-
-
case distance_in_seconds
-
when 0..4 then locale.t :less_than_x_seconds, :count => 5
-
when 5..9 then locale.t :less_than_x_seconds, :count => 10
-
when 10..19 then locale.t :less_than_x_seconds, :count => 20
-
when 20..39 then locale.t :half_a_minute
-
when 40..59 then locale.t :less_than_x_minutes, :count => 1
-
else locale.t :x_minutes, :count => 1
-
end
-
-
when 2...45 then locale.t :x_minutes, :count => distance_in_minutes
-
when 45...90 then locale.t :about_x_hours, :count => 1
-
# 90 mins up to 24 hours
-
when 90...1440 then locale.t :about_x_hours, :count => (distance_in_minutes.to_f / 60.0).round
-
# 24 hours up to 42 hours
-
when 1440...2520 then locale.t :x_days, :count => 1
-
# 42 hours up to 30 days
-
when 2520...43200 then locale.t :x_days, :count => (distance_in_minutes.to_f / 1440.0).round
-
# 30 days up to 60 days
-
when 43200...86400 then locale.t :about_x_months, :count => (distance_in_minutes.to_f / 43200.0).round
-
# 60 days up to 365 days
-
when 86400...525600 then locale.t :x_months, :count => (distance_in_minutes.to_f / 43200.0).round
-
else
-
if from_time.acts_like?(:time) && to_time.acts_like?(:time)
-
fyear = from_time.year
-
fyear += 1 if from_time.month >= 3
-
tyear = to_time.year
-
tyear -= 1 if to_time.month < 3
-
leap_years = (fyear > tyear) ? 0 : (fyear..tyear).count{|x| Date.leap?(x)}
-
minute_offset_for_leap_year = leap_years * 1440
-
# Discount the leap year days when calculating year distance.
-
# e.g. if there are 20 leap year days between 2 dates having the same day
-
# and month then the based on 365 days calculation
-
# the distance in years will come out to over 80 years when in written
-
# English it would read better as about 80 years.
-
minutes_with_offset = distance_in_minutes - minute_offset_for_leap_year
-
else
-
minutes_with_offset = distance_in_minutes
-
end
-
remainder = (minutes_with_offset % 525600)
-
distance_in_years = (minutes_with_offset.div 525600)
-
if remainder < 131400
-
locale.t(:about_x_years, :count => distance_in_years)
-
elsif remainder < 394200
-
locale.t(:over_x_years, :count => distance_in_years)
-
else
-
locale.t(:almost_x_years, :count => distance_in_years + 1)
-
end
-
end
-
end
-
end
-
-
# Like <tt>distance_of_time_in_words</tt>, but where <tt>to_time</tt> is fixed to <tt>Time.now</tt>.
-
#
-
# time_ago_in_words(3.minutes.from_now) # => 3 minutes
-
# time_ago_in_words(3.minutes.ago) # => 3 minutes
-
# time_ago_in_words(Time.now - 15.hours) # => about 15 hours
-
# time_ago_in_words(Time.now) # => less than a minute
-
# time_ago_in_words(Time.now, include_seconds: true) # => less than 5 seconds
-
#
-
# from_time = Time.now - 3.days - 14.minutes - 25.seconds
-
# time_ago_in_words(from_time) # => 3 days
-
#
-
# from_time = (3.days + 14.minutes + 25.seconds).ago
-
# time_ago_in_words(from_time) # => 3 days
-
#
-
# Note that you cannot pass a <tt>Numeric</tt> value to <tt>time_ago_in_words</tt>.
-
#
-
1
def time_ago_in_words(from_time, include_seconds_or_options = {})
-
distance_of_time_in_words(from_time, Time.now, include_seconds_or_options)
-
end
-
-
1
alias_method :distance_of_time_in_words_to_now, :time_ago_in_words
-
-
# Returns a set of select tags (one for year, month, and day) pre-selected for accessing a specified date-based
-
# attribute (identified by +method+) on an object assigned to the template (identified by +object+).
-
#
-
# ==== Options
-
# * <tt>:use_month_numbers</tt> - Set to true if you want to use month numbers rather than month names (e.g.
-
# "2" instead of "February").
-
# * <tt>:use_two_digit_numbers</tt> - Set to true if you want to display two digit month and day numbers (e.g.
-
# "02" instead of "February" and "08" instead of "8").
-
# * <tt>:use_short_month</tt> - Set to true if you want to use abbreviated month names instead of full
-
# month names (e.g. "Feb" instead of "February").
-
# * <tt>:add_month_numbers</tt> - Set to true if you want to use both month numbers and month names (e.g.
-
# "2 - February" instead of "February").
-
# * <tt>:use_month_names</tt> - Set to an array with 12 month names if you want to customize month names.
-
# Note: You can also use Rails' i18n functionality for this.
-
# * <tt>:month_format_string</tt> - Set to a format string. The string gets passed keys +:number+ (integer)
-
# and +:name+ (string). A format string would be something like "%{name} (%<number>02d)" for example.
-
# See <tt>Kernel.sprintf</tt> for documentation on format sequences.
-
# * <tt>:date_separator</tt> - Specifies a string to separate the date fields. Default is "" (i.e. nothing).
-
# * <tt>:start_year</tt> - Set the start year for the year select. Default is <tt>Date.today.year - 5</tt>if
-
# you are creating new record. While editing existing record, <tt>:start_year</tt> defaults to
-
# the current selected year minus 5.
-
# * <tt>:end_year</tt> - Set the end year for the year select. Default is <tt>Date.today.year + 5</tt> if
-
# you are creating new record. While editing existing record, <tt>:end_year</tt> defaults to
-
# the current selected year plus 5.
-
# * <tt>:discard_day</tt> - Set to true if you don't want to show a day select. This includes the day
-
# as a hidden field instead of showing a select field. Also note that this implicitly sets the day to be the
-
# first of the given month in order to not create invalid dates like 31 February.
-
# * <tt>:discard_month</tt> - Set to true if you don't want to show a month select. This includes the month
-
# as a hidden field instead of showing a select field. Also note that this implicitly sets :discard_day to true.
-
# * <tt>:discard_year</tt> - Set to true if you don't want to show a year select. This includes the year
-
# as a hidden field instead of showing a select field.
-
# * <tt>:order</tt> - Set to an array containing <tt>:day</tt>, <tt>:month</tt> and <tt>:year</tt> to
-
# customize the order in which the select fields are shown. If you leave out any of the symbols, the respective
-
# select will not be shown (like when you set <tt>discard_xxx: true</tt>. Defaults to the order defined in
-
# the respective locale (e.g. [:year, :month, :day] in the en locale that ships with Rails).
-
# * <tt>:include_blank</tt> - Include a blank option in every select field so it's possible to set empty
-
# dates.
-
# * <tt>:default</tt> - Set a default date if the affected date isn't set or is nil.
-
# * <tt>:selected</tt> - Set a date that overrides the actual value.
-
# * <tt>:disabled</tt> - Set to true if you want show the select fields as disabled.
-
# * <tt>:prompt</tt> - Set to true (for a generic prompt), a prompt string or a hash of prompt strings
-
# for <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>, <tt>:hour</tt>, <tt>:minute</tt> and <tt>:second</tt>.
-
# Setting this option prepends a select option with a generic prompt (Day, Month, Year, Hour, Minute, Seconds)
-
# or the given prompt string.
-
# * <tt>:with_css_classes</tt> - Set to true if you want assign different styles for 'select' tags. This option
-
# automatically set classes 'year', 'month', 'day', 'hour', 'minute' and 'second' for your 'select' tags.
-
#
-
# If anything is passed in the +html_options+ hash it will be applied to every select tag in the set.
-
#
-
# NOTE: Discarded selects will default to 1. So if no month select is available, January will be assumed.
-
#
-
# # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute.
-
# date_select("article", "written_on")
-
#
-
# # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute,
-
# # with the year in the year drop down box starting at 1995.
-
# date_select("article", "written_on", start_year: 1995)
-
#
-
# # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute,
-
# # with the year in the year drop down box starting at 1995, numbers used for months instead of words,
-
# # and without a day select box.
-
# date_select("article", "written_on", start_year: 1995, use_month_numbers: true,
-
# discard_day: true, include_blank: true)
-
#
-
# # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute,
-
# # with two digit numbers used for months and days.
-
# date_select("article", "written_on", use_two_digit_numbers: true)
-
#
-
# # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute
-
# # with the fields ordered as day, month, year rather than month, day, year.
-
# date_select("article", "written_on", order: [:day, :month, :year])
-
#
-
# # Generates a date select that when POSTed is stored in the user variable, in the birthday attribute
-
# # lacking a year field.
-
# date_select("user", "birthday", order: [:month, :day])
-
#
-
# # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute
-
# # which is initially set to the date 3 days from the current date
-
# date_select("article", "written_on", default: 3.days.from_now)
-
#
-
# # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute
-
# # which is set in the form with todays date, regardless of the value in the Active Record object.
-
# date_select("article", "written_on", selected: Date.today)
-
#
-
# # Generates a date select that when POSTed is stored in the credit_card variable, in the bill_due attribute
-
# # that will have a default day of 20.
-
# date_select("credit_card", "bill_due", default: { day: 20 })
-
#
-
# # Generates a date select with custom prompts.
-
# date_select("article", "written_on", prompt: { day: 'Select day', month: 'Select month', year: 'Select year' })
-
#
-
# The selects are prepared for multi-parameter assignment to an Active Record object.
-
#
-
# Note: If the day is not included as an option but the month is, the day will be set to the 1st to ensure that
-
# all month choices are valid.
-
1
def date_select(object_name, method, options = {}, html_options = {})
-
Tags::DateSelect.new(object_name, method, self, options, html_options).render
-
end
-
-
# Returns a set of select tags (one for hour, minute and optionally second) pre-selected for accessing a
-
# specified time-based attribute (identified by +method+) on an object assigned to the template (identified by
-
# +object+). You can include the seconds with <tt>:include_seconds</tt>. You can get hours in the AM/PM format
-
# with <tt>:ampm</tt> option.
-
#
-
# This method will also generate 3 input hidden tags, for the actual year, month and day unless the option
-
# <tt>:ignore_date</tt> is set to +true+. If you set the <tt>:ignore_date</tt> to +true+, you must have a
-
# +date_select+ on the same method within the form otherwise an exception will be raised.
-
#
-
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
-
#
-
# # Creates a time select tag that, when POSTed, will be stored in the article variable in the sunrise attribute.
-
# time_select("article", "sunrise")
-
#
-
# # Creates a time select tag with a seconds field that, when POSTed, will be stored in the article variables in
-
# # the sunrise attribute.
-
# time_select("article", "start_time", include_seconds: true)
-
#
-
# # You can set the <tt>:minute_step</tt> to 15 which will give you: 00, 15, 30 and 45.
-
# time_select 'game', 'game_time', {minute_step: 15}
-
#
-
# # Creates a time select tag with a custom prompt. Use <tt>prompt: true</tt> for generic prompts.
-
# time_select("article", "written_on", prompt: {hour: 'Choose hour', minute: 'Choose minute', second: 'Choose seconds'})
-
# time_select("article", "written_on", prompt: {hour: true}) # generic prompt for hours
-
# time_select("article", "written_on", prompt: true) # generic prompts for all
-
#
-
# # You can set :ampm option to true which will show the hours as: 12 PM, 01 AM .. 11 PM.
-
# time_select 'game', 'game_time', {ampm: true}
-
#
-
# The selects are prepared for multi-parameter assignment to an Active Record object.
-
#
-
# Note: If the day is not included as an option but the month is, the day will be set to the 1st to ensure that
-
# all month choices are valid.
-
1
def time_select(object_name, method, options = {}, html_options = {})
-
Tags::TimeSelect.new(object_name, method, self, options, html_options).render
-
end
-
-
# Returns a set of select tags (one for year, month, day, hour, and minute) pre-selected for accessing a
-
# specified datetime-based attribute (identified by +method+) on an object assigned to the template (identified
-
# by +object+).
-
#
-
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
-
#
-
# # Generates a datetime select that, when POSTed, will be stored in the article variable in the written_on
-
# # attribute.
-
# datetime_select("article", "written_on")
-
#
-
# # Generates a datetime select with a year select that starts at 1995 that, when POSTed, will be stored in the
-
# # article variable in the written_on attribute.
-
# datetime_select("article", "written_on", start_year: 1995)
-
#
-
# # Generates a datetime select with a default value of 3 days from the current time that, when POSTed, will
-
# # be stored in the trip variable in the departing attribute.
-
# datetime_select("trip", "departing", default: 3.days.from_now)
-
#
-
# # Generate a datetime select with hours in the AM/PM format
-
# datetime_select("article", "written_on", ampm: true)
-
#
-
# # Generates a datetime select that discards the type that, when POSTed, will be stored in the article variable
-
# # as the written_on attribute.
-
# datetime_select("article", "written_on", discard_type: true)
-
#
-
# # Generates a datetime select with a custom prompt. Use <tt>prompt: true</tt> for generic prompts.
-
# datetime_select("article", "written_on", prompt: {day: 'Choose day', month: 'Choose month', year: 'Choose year'})
-
# datetime_select("article", "written_on", prompt: {hour: true}) # generic prompt for hours
-
# datetime_select("article", "written_on", prompt: true) # generic prompts for all
-
#
-
# The selects are prepared for multi-parameter assignment to an Active Record object.
-
1
def datetime_select(object_name, method, options = {}, html_options = {})
-
Tags::DatetimeSelect.new(object_name, method, self, options, html_options).render
-
end
-
-
# Returns a set of html select-tags (one for year, month, day, hour, minute, and second) pre-selected with the
-
# +datetime+. It's also possible to explicitly set the order of the tags using the <tt>:order</tt> option with
-
# an array of symbols <tt>:year</tt>, <tt>:month</tt> and <tt>:day</tt> in the desired order. If you do not
-
# supply a Symbol, it will be appended onto the <tt>:order</tt> passed in. You can also add
-
# <tt>:date_separator</tt>, <tt>:datetime_separator</tt> and <tt>:time_separator</tt> keys to the +options+ to
-
# control visual display of the elements.
-
#
-
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
-
#
-
# my_date_time = Time.now + 4.days
-
#
-
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today).
-
# select_datetime(my_date_time)
-
#
-
# # Generates a datetime select that defaults to today (no specified datetime)
-
# select_datetime()
-
#
-
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
-
# # with the fields ordered year, month, day rather than month, day, year.
-
# select_datetime(my_date_time, order: [:year, :month, :day])
-
#
-
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
-
# # with a '/' between each date field.
-
# select_datetime(my_date_time, date_separator: '/')
-
#
-
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
-
# # with a date fields separated by '/', time fields separated by '' and the date and time fields
-
# # separated by a comma (',').
-
# select_datetime(my_date_time, date_separator: '/', time_separator: '', datetime_separator: ',')
-
#
-
# # Generates a datetime select that discards the type of the field and defaults to the datetime in
-
# # my_date_time (four days after today)
-
# select_datetime(my_date_time, discard_type: true)
-
#
-
# # Generate a datetime field with hours in the AM/PM format
-
# select_datetime(my_date_time, ampm: true)
-
#
-
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
-
# # prefixed with 'payday' rather than 'date'
-
# select_datetime(my_date_time, prefix: 'payday')
-
#
-
# # Generates a datetime select with a custom prompt. Use <tt>prompt: true</tt> for generic prompts.
-
# select_datetime(my_date_time, prompt: {day: 'Choose day', month: 'Choose month', year: 'Choose year'})
-
# select_datetime(my_date_time, prompt: {hour: true}) # generic prompt for hours
-
# select_datetime(my_date_time, prompt: true) # generic prompts for all
-
1
def select_datetime(datetime = Time.current, options = {}, html_options = {})
-
DateTimeSelector.new(datetime, options, html_options).select_datetime
-
end
-
-
# Returns a set of html select-tags (one for year, month, and day) pre-selected with the +date+.
-
# It's possible to explicitly set the order of the tags using the <tt>:order</tt> option with an array of
-
# symbols <tt>:year</tt>, <tt>:month</tt> and <tt>:day</tt> in the desired order.
-
# If the array passed to the <tt>:order</tt> option does not contain all the three symbols, all tags will be hidden.
-
#
-
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
-
#
-
# my_date = Time.now + 6.days
-
#
-
# # Generates a date select that defaults to the date in my_date (six days after today).
-
# select_date(my_date)
-
#
-
# # Generates a date select that defaults to today (no specified date).
-
# select_date()
-
#
-
# # Generates a date select that defaults to the date in my_date (six days after today)
-
# # with the fields ordered year, month, day rather than month, day, year.
-
# select_date(my_date, order: [:year, :month, :day])
-
#
-
# # Generates a date select that discards the type of the field and defaults to the date in
-
# # my_date (six days after today).
-
# select_date(my_date, discard_type: true)
-
#
-
# # Generates a date select that defaults to the date in my_date,
-
# # which has fields separated by '/'.
-
# select_date(my_date, date_separator: '/')
-
#
-
# # Generates a date select that defaults to the datetime in my_date (six days after today)
-
# # prefixed with 'payday' rather than 'date'.
-
# select_date(my_date, prefix: 'payday')
-
#
-
# # Generates a date select with a custom prompt. Use <tt>prompt: true</tt> for generic prompts.
-
# select_date(my_date, prompt: {day: 'Choose day', month: 'Choose month', year: 'Choose year'})
-
# select_date(my_date, prompt: {hour: true}) # generic prompt for hours
-
# select_date(my_date, prompt: true) # generic prompts for all
-
1
def select_date(date = Date.current, options = {}, html_options = {})
-
DateTimeSelector.new(date, options, html_options).select_date
-
end
-
-
# Returns a set of html select-tags (one for hour and minute).
-
# You can set <tt>:time_separator</tt> key to format the output, and
-
# the <tt>:include_seconds</tt> option to include an input for seconds.
-
#
-
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
-
#
-
# my_time = Time.now + 5.days + 7.hours + 3.minutes + 14.seconds
-
#
-
# # Generates a time select that defaults to the time in my_time.
-
# select_time(my_time)
-
#
-
# # Generates a time select that defaults to the current time (no specified time).
-
# select_time()
-
#
-
# # Generates a time select that defaults to the time in my_time,
-
# # which has fields separated by ':'.
-
# select_time(my_time, time_separator: ':')
-
#
-
# # Generates a time select that defaults to the time in my_time,
-
# # that also includes an input for seconds.
-
# select_time(my_time, include_seconds: true)
-
#
-
# # Generates a time select that defaults to the time in my_time, that has fields
-
# # separated by ':' and includes an input for seconds.
-
# select_time(my_time, time_separator: ':', include_seconds: true)
-
#
-
# # Generate a time select field with hours in the AM/PM format
-
# select_time(my_time, ampm: true)
-
#
-
# # Generates a time select field with hours that range from 2 to 14
-
# select_time(my_time, start_hour: 2, end_hour: 14)
-
#
-
# # Generates a time select with a custom prompt. Use <tt>:prompt</tt> to true for generic prompts.
-
# select_time(my_time, prompt: {day: 'Choose day', month: 'Choose month', year: 'Choose year'})
-
# select_time(my_time, prompt: {hour: true}) # generic prompt for hours
-
# select_time(my_time, prompt: true) # generic prompts for all
-
1
def select_time(datetime = Time.current, options = {}, html_options = {})
-
DateTimeSelector.new(datetime, options, html_options).select_time
-
end
-
-
# Returns a select tag with options for each of the seconds 0 through 59 with the current second selected.
-
# The <tt>datetime</tt> can be either a +Time+ or +DateTime+ object or an integer.
-
# Override the field name using the <tt>:field_name</tt> option, 'second' by default.
-
#
-
# my_time = Time.now + 16.minutes
-
#
-
# # Generates a select field for seconds that defaults to the seconds for the time in my_time.
-
# select_second(my_time)
-
#
-
# # Generates a select field for seconds that defaults to the number given.
-
# select_second(33)
-
#
-
# # Generates a select field for seconds that defaults to the seconds for the time in my_time
-
# # that is named 'interval' rather than 'second'.
-
# select_second(my_time, field_name: 'interval')
-
#
-
# # Generates a select field for seconds with a custom prompt. Use <tt>prompt: true</tt> for a
-
# # generic prompt.
-
# select_second(14, prompt: 'Choose seconds')
-
1
def select_second(datetime, options = {}, html_options = {})
-
DateTimeSelector.new(datetime, options, html_options).select_second
-
end
-
-
# Returns a select tag with options for each of the minutes 0 through 59 with the current minute selected.
-
# Also can return a select tag with options by <tt>minute_step</tt> from 0 through 59 with the 00 minute
-
# selected. The <tt>datetime</tt> can be either a +Time+ or +DateTime+ object or an integer.
-
# Override the field name using the <tt>:field_name</tt> option, 'minute' by default.
-
#
-
# my_time = Time.now + 6.hours
-
#
-
# # Generates a select field for minutes that defaults to the minutes for the time in my_time.
-
# select_minute(my_time)
-
#
-
# # Generates a select field for minutes that defaults to the number given.
-
# select_minute(14)
-
#
-
# # Generates a select field for minutes that defaults to the minutes for the time in my_time
-
# # that is named 'moment' rather than 'minute'.
-
# select_minute(my_time, field_name: 'moment')
-
#
-
# # Generates a select field for minutes with a custom prompt. Use <tt>prompt: true</tt> for a
-
# # generic prompt.
-
# select_minute(14, prompt: 'Choose minutes')
-
1
def select_minute(datetime, options = {}, html_options = {})
-
DateTimeSelector.new(datetime, options, html_options).select_minute
-
end
-
-
# Returns a select tag with options for each of the hours 0 through 23 with the current hour selected.
-
# The <tt>datetime</tt> can be either a +Time+ or +DateTime+ object or an integer.
-
# Override the field name using the <tt>:field_name</tt> option, 'hour' by default.
-
#
-
# my_time = Time.now + 6.hours
-
#
-
# # Generates a select field for hours that defaults to the hour for the time in my_time.
-
# select_hour(my_time)
-
#
-
# # Generates a select field for hours that defaults to the number given.
-
# select_hour(13)
-
#
-
# # Generates a select field for hours that defaults to the hour for the time in my_time
-
# # that is named 'stride' rather than 'hour'.
-
# select_hour(my_time, field_name: 'stride')
-
#
-
# # Generates a select field for hours with a custom prompt. Use <tt>prompt: true</tt> for a
-
# # generic prompt.
-
# select_hour(13, prompt: 'Choose hour')
-
#
-
# # Generate a select field for hours in the AM/PM format
-
# select_hour(my_time, ampm: true)
-
#
-
# # Generates a select field that includes options for hours from 2 to 14.
-
# select_hour(my_time, start_hour: 2, end_hour: 14)
-
1
def select_hour(datetime, options = {}, html_options = {})
-
DateTimeSelector.new(datetime, options, html_options).select_hour
-
end
-
-
# Returns a select tag with options for each of the days 1 through 31 with the current day selected.
-
# The <tt>date</tt> can also be substituted for a day number.
-
# If you want to display days with a leading zero set the <tt>:use_two_digit_numbers</tt> key in +options+ to true.
-
# Override the field name using the <tt>:field_name</tt> option, 'day' by default.
-
#
-
# my_date = Time.now + 2.days
-
#
-
# # Generates a select field for days that defaults to the day for the date in my_date.
-
# select_day(my_date)
-
#
-
# # Generates a select field for days that defaults to the number given.
-
# select_day(5)
-
#
-
# # Generates a select field for days that defaults to the number given, but displays it with two digits.
-
# select_day(5, use_two_digit_numbers: true)
-
#
-
# # Generates a select field for days that defaults to the day for the date in my_date
-
# # that is named 'due' rather than 'day'.
-
# select_day(my_date, field_name: 'due')
-
#
-
# # Generates a select field for days with a custom prompt. Use <tt>prompt: true</tt> for a
-
# # generic prompt.
-
# select_day(5, prompt: 'Choose day')
-
1
def select_day(date, options = {}, html_options = {})
-
DateTimeSelector.new(date, options, html_options).select_day
-
end
-
-
# Returns a select tag with options for each of the months January through December with the current month
-
# selected. The month names are presented as keys (what's shown to the user) and the month numbers (1-12) are
-
# used as values (what's submitted to the server). It's also possible to use month numbers for the presentation
-
# instead of names -- set the <tt>:use_month_numbers</tt> key in +options+ to true for this to happen. If you
-
# want both numbers and names, set the <tt>:add_month_numbers</tt> key in +options+ to true. If you would prefer
-
# to show month names as abbreviations, set the <tt>:use_short_month</tt> key in +options+ to true. If you want
-
# to use your own month names, set the <tt>:use_month_names</tt> key in +options+ to an array of 12 month names.
-
# If you want to display months with a leading zero set the <tt>:use_two_digit_numbers</tt> key in +options+ to true.
-
# Override the field name using the <tt>:field_name</tt> option, 'month' by default.
-
#
-
# # Generates a select field for months that defaults to the current month that
-
# # will use keys like "January", "March".
-
# select_month(Date.today)
-
#
-
# # Generates a select field for months that defaults to the current month that
-
# # is named "start" rather than "month".
-
# select_month(Date.today, field_name: 'start')
-
#
-
# # Generates a select field for months that defaults to the current month that
-
# # will use keys like "1", "3".
-
# select_month(Date.today, use_month_numbers: true)
-
#
-
# # Generates a select field for months that defaults to the current month that
-
# # will use keys like "1 - January", "3 - March".
-
# select_month(Date.today, add_month_numbers: true)
-
#
-
# # Generates a select field for months that defaults to the current month that
-
# # will use keys like "Jan", "Mar".
-
# select_month(Date.today, use_short_month: true)
-
#
-
# # Generates a select field for months that defaults to the current month that
-
# # will use keys like "Januar", "Marts."
-
# select_month(Date.today, use_month_names: %w(Januar Februar Marts ...))
-
#
-
# # Generates a select field for months that defaults to the current month that
-
# # will use keys with two digit numbers like "01", "03".
-
# select_month(Date.today, use_two_digit_numbers: true)
-
#
-
# # Generates a select field for months with a custom prompt. Use <tt>prompt: true</tt> for a
-
# # generic prompt.
-
# select_month(14, prompt: 'Choose month')
-
1
def select_month(date, options = {}, html_options = {})
-
DateTimeSelector.new(date, options, html_options).select_month
-
end
-
-
# Returns a select tag with options for each of the five years on each side of the current, which is selected.
-
# The five year radius can be changed using the <tt>:start_year</tt> and <tt>:end_year</tt> keys in the
-
# +options+. Both ascending and descending year lists are supported by making <tt>:start_year</tt> less than or
-
# greater than <tt>:end_year</tt>. The <tt>date</tt> can also be substituted for a year given as a number.
-
# Override the field name using the <tt>:field_name</tt> option, 'year' by default.
-
#
-
# # Generates a select field for years that defaults to the current year that
-
# # has ascending year values.
-
# select_year(Date.today, start_year: 1992, end_year: 2007)
-
#
-
# # Generates a select field for years that defaults to the current year that
-
# # is named 'birth' rather than 'year'.
-
# select_year(Date.today, field_name: 'birth')
-
#
-
# # Generates a select field for years that defaults to the current year that
-
# # has descending year values.
-
# select_year(Date.today, start_year: 2005, end_year: 1900)
-
#
-
# # Generates a select field for years that defaults to the year 2006 that
-
# # has ascending year values.
-
# select_year(2006, start_year: 2000, end_year: 2010)
-
#
-
# # Generates a select field for years with a custom prompt. Use <tt>prompt: true</tt> for a
-
# # generic prompt.
-
# select_year(14, prompt: 'Choose year')
-
1
def select_year(date, options = {}, html_options = {})
-
DateTimeSelector.new(date, options, html_options).select_year
-
end
-
-
# Returns an html time tag for the given date or time.
-
#
-
# time_tag Date.today # =>
-
# <time datetime="2010-11-04">November 04, 2010</time>
-
# time_tag Time.now # =>
-
# <time datetime="2010-11-04T17:55:45+01:00">November 04, 2010 17:55</time>
-
# time_tag Date.yesterday, 'Yesterday' # =>
-
# <time datetime="2010-11-03">Yesterday</time>
-
# time_tag Date.today, pubdate: true # =>
-
# <time datetime="2010-11-04" pubdate="pubdate">November 04, 2010</time>
-
# time_tag Date.today, datetime: Date.today.strftime('%G-W%V') # =>
-
# <time datetime="2010-W44">November 04, 2010</time>
-
#
-
# <%= time_tag Time.now do %>
-
# <span>Right now</span>
-
# <% end %>
-
# # => <time datetime="2010-11-04T17:55:45+01:00"><span>Right now</span></time>
-
1
def time_tag(date_or_time, *args, &block)
-
options = args.extract_options!
-
format = options.delete(:format) || :long
-
content = args.first || I18n.l(date_or_time, :format => format)
-
datetime = date_or_time.acts_like?(:time) ? date_or_time.xmlschema : date_or_time.iso8601
-
-
content_tag(:time, content, options.reverse_merge(:datetime => datetime), &block)
-
end
-
end
-
-
1
class DateTimeSelector #:nodoc:
-
1
include ActionView::Helpers::TagHelper
-
-
1
DEFAULT_PREFIX = 'date'.freeze
-
1
POSITION = {
-
:year => 1, :month => 2, :day => 3, :hour => 4, :minute => 5, :second => 6
-
}.freeze
-
-
1
AMPM_TRANSLATION = Hash[
-
[[0, "12 AM"], [1, "01 AM"], [2, "02 AM"], [3, "03 AM"],
-
[4, "04 AM"], [5, "05 AM"], [6, "06 AM"], [7, "07 AM"],
-
[8, "08 AM"], [9, "09 AM"], [10, "10 AM"], [11, "11 AM"],
-
[12, "12 PM"], [13, "01 PM"], [14, "02 PM"], [15, "03 PM"],
-
[16, "04 PM"], [17, "05 PM"], [18, "06 PM"], [19, "07 PM"],
-
[20, "08 PM"], [21, "09 PM"], [22, "10 PM"], [23, "11 PM"]]
-
].freeze
-
-
1
def initialize(datetime, options = {}, html_options = {})
-
@options = options.dup
-
@html_options = html_options.dup
-
@datetime = datetime
-
@options[:datetime_separator] ||= ' — '
-
@options[:time_separator] ||= ' : '
-
end
-
-
1
def select_datetime
-
order = date_order.dup
-
order -= [:hour, :minute, :second]
-
@options[:discard_year] ||= true unless order.include?(:year)
-
@options[:discard_month] ||= true unless order.include?(:month)
-
@options[:discard_day] ||= true if @options[:discard_month] || !order.include?(:day)
-
@options[:discard_minute] ||= true if @options[:discard_hour]
-
@options[:discard_second] ||= true unless @options[:include_seconds] && !@options[:discard_minute]
-
-
set_day_if_discarded
-
-
if @options[:tag] && @options[:ignore_date]
-
select_time
-
else
-
[:day, :month, :year].each { |o| order.unshift(o) unless order.include?(o) }
-
order += [:hour, :minute, :second] unless @options[:discard_hour]
-
-
build_selects_from_types(order)
-
end
-
end
-
-
1
def select_date
-
order = date_order.dup
-
-
@options[:discard_hour] = true
-
@options[:discard_minute] = true
-
@options[:discard_second] = true
-
-
@options[:discard_year] ||= true unless order.include?(:year)
-
@options[:discard_month] ||= true unless order.include?(:month)
-
@options[:discard_day] ||= true if @options[:discard_month] || !order.include?(:day)
-
-
set_day_if_discarded
-
-
[:day, :month, :year].each { |o| order.unshift(o) unless order.include?(o) }
-
-
build_selects_from_types(order)
-
end
-
-
1
def select_time
-
order = []
-
-
@options[:discard_month] = true
-
@options[:discard_year] = true
-
@options[:discard_day] = true
-
@options[:discard_second] ||= true unless @options[:include_seconds]
-
-
order += [:year, :month, :day] unless @options[:ignore_date]
-
-
order += [:hour, :minute]
-
order << :second if @options[:include_seconds]
-
-
build_selects_from_types(order)
-
end
-
-
1
def select_second
-
if @options[:use_hidden] || @options[:discard_second]
-
build_hidden(:second, sec) if @options[:include_seconds]
-
else
-
build_options_and_select(:second, sec)
-
end
-
end
-
-
1
def select_minute
-
if @options[:use_hidden] || @options[:discard_minute]
-
build_hidden(:minute, min)
-
else
-
build_options_and_select(:minute, min, :step => @options[:minute_step])
-
end
-
end
-
-
1
def select_hour
-
if @options[:use_hidden] || @options[:discard_hour]
-
build_hidden(:hour, hour)
-
else
-
options = {}
-
options[:ampm] = @options[:ampm] || false
-
options[:start] = @options[:start_hour] || 0
-
options[:end] = @options[:end_hour] || 23
-
build_options_and_select(:hour, hour, options)
-
end
-
end
-
-
1
def select_day
-
if @options[:use_hidden] || @options[:discard_day]
-
build_hidden(:day, day || 1)
-
else
-
build_options_and_select(:day, day, :start => 1, :end => 31, :leading_zeros => false, :use_two_digit_numbers => @options[:use_two_digit_numbers])
-
end
-
end
-
-
1
def select_month
-
if @options[:use_hidden] || @options[:discard_month]
-
build_hidden(:month, month || 1)
-
else
-
month_options = []
-
1.upto(12) do |month_number|
-
options = { :value => month_number }
-
options[:selected] = "selected" if month == month_number
-
month_options << content_tag(:option, month_name(month_number), options) + "\n"
-
end
-
build_select(:month, month_options.join)
-
end
-
end
-
-
1
def select_year
-
if !@datetime || @datetime == 0
-
val = '1'
-
middle_year = Date.today.year
-
else
-
val = middle_year = year
-
end
-
-
if @options[:use_hidden] || @options[:discard_year]
-
build_hidden(:year, val)
-
else
-
options = {}
-
options[:start] = @options[:start_year] || middle_year - 5
-
options[:end] = @options[:end_year] || middle_year + 5
-
options[:step] = options[:start] < options[:end] ? 1 : -1
-
options[:leading_zeros] = false
-
options[:max_years_allowed] = @options[:max_years_allowed] || 1000
-
-
if (options[:end] - options[:start]).abs > options[:max_years_allowed]
-
raise ArgumentError, "There are too many years options to be built. Are you sure you haven't mistyped something? You can provide the :max_years_allowed parameter."
-
end
-
-
build_options_and_select(:year, val, options)
-
end
-
end
-
-
1
private
-
1
%w( sec min hour day month year ).each do |method|
-
6
define_method(method) do
-
@datetime.kind_of?(Numeric) ? @datetime : @datetime.send(method) if @datetime
-
end
-
end
-
-
# If the day is hidden, the day should be set to the 1st so all month and year choices are
-
# valid. Otherwise, February 31st or February 29th, 2011 can be selected, which are invalid.
-
1
def set_day_if_discarded
-
if @datetime && @options[:discard_day]
-
@datetime = @datetime.change(:day => 1)
-
end
-
end
-
-
# Returns translated month names, but also ensures that a custom month
-
# name array has a leading nil element.
-
1
def month_names
-
@month_names ||= begin
-
month_names = @options[:use_month_names] || translated_month_names
-
month_names.unshift(nil) if month_names.size < 13
-
month_names
-
end
-
end
-
-
# Returns translated month names.
-
# => [nil, "January", "February", "March",
-
# "April", "May", "June", "July",
-
# "August", "September", "October",
-
# "November", "December"]
-
#
-
# If <tt>:use_short_month</tt> option is set
-
# => [nil, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
-
# "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
-
1
def translated_month_names
-
key = @options[:use_short_month] ? :'date.abbr_month_names' : :'date.month_names'
-
I18n.translate(key, :locale => @options[:locale])
-
end
-
-
# Looks up month names by number (1-based):
-
#
-
# month_name(1) # => "January"
-
#
-
# If the <tt>:use_month_numbers</tt> option is passed:
-
#
-
# month_name(1) # => 1
-
#
-
# If the <tt>:use_two_month_numbers</tt> option is passed:
-
#
-
# month_name(1) # => '01'
-
#
-
# If the <tt>:add_month_numbers</tt> option is passed:
-
#
-
# month_name(1) # => "1 - January"
-
#
-
# If the <tt>:month_format_string</tt> option is passed:
-
#
-
# month_name(1) # => "January (01)"
-
#
-
# depending on the format string.
-
1
def month_name(number)
-
if @options[:use_month_numbers]
-
number
-
elsif @options[:use_two_digit_numbers]
-
'%02d' % number
-
elsif @options[:add_month_numbers]
-
"#{number} - #{month_names[number]}"
-
elsif format_string = @options[:month_format_string]
-
format_string % {number: number, name: month_names[number]}
-
else
-
month_names[number]
-
end
-
end
-
-
1
def date_order
-
@date_order ||= @options[:order] || translated_date_order
-
end
-
-
1
def translated_date_order
-
date_order = I18n.translate(:'date.order', :locale => @options[:locale], :default => [])
-
date_order = date_order.map { |element| element.to_sym }
-
-
forbidden_elements = date_order - [:year, :month, :day]
-
if forbidden_elements.any?
-
raise StandardError,
-
"#{@options[:locale]}.date.order only accepts :year, :month and :day"
-
end
-
-
date_order
-
end
-
-
# Build full select tag from date type and options.
-
1
def build_options_and_select(type, selected, options = {})
-
build_select(type, build_options(selected, options))
-
end
-
-
# Build select option html from date value and options.
-
# build_options(15, start: 1, end: 31)
-
# => "<option value="1">1</option>
-
# <option value="2">2</option>
-
# <option value="3">3</option>..."
-
#
-
# If <tt>use_two_digit_numbers: true</tt> option is passed
-
# build_options(15, start: 1, end: 31, use_two_digit_numbers: true)
-
# => "<option value="1">01</option>
-
# <option value="2">02</option>
-
# <option value="3">03</option>..."
-
#
-
# If <tt>:step</tt> options is passed
-
# build_options(15, start: 1, end: 31, step: 2)
-
# => "<option value="1">1</option>
-
# <option value="3">3</option>
-
# <option value="5">5</option>..."
-
1
def build_options(selected, options = {})
-
options = {
-
leading_zeros: true, ampm: false, use_two_digit_numbers: false
-
}.merge!(options)
-
-
start = options.delete(:start) || 0
-
stop = options.delete(:end) || 59
-
step = options.delete(:step) || 1
-
leading_zeros = options.delete(:leading_zeros)
-
-
select_options = []
-
start.step(stop, step) do |i|
-
value = leading_zeros ? sprintf("%02d", i) : i
-
tag_options = { :value => value }
-
tag_options[:selected] = "selected" if selected == i
-
text = options[:use_two_digit_numbers] ? sprintf("%02d", i) : value
-
text = options[:ampm] ? AMPM_TRANSLATION[i] : text
-
select_options << content_tag(:option, text, tag_options)
-
end
-
-
(select_options.join("\n") + "\n").html_safe
-
end
-
-
# Builds select tag from date type and html select options.
-
# build_select(:month, "<option value="1">January</option>...")
-
# => "<select id="post_written_on_2i" name="post[written_on(2i)]">
-
# <option value="1">January</option>...
-
# </select>"
-
1
def build_select(type, select_options_as_html)
-
select_options = {
-
:id => input_id_from_type(type),
-
:name => input_name_from_type(type)
-
}.merge!(@html_options)
-
select_options[:disabled] = 'disabled' if @options[:disabled]
-
select_options[:class] = type if @options[:with_css_classes]
-
-
select_html = "\n"
-
select_html << content_tag(:option, '', :value => '') + "\n" if @options[:include_blank]
-
select_html << prompt_option_tag(type, @options[:prompt]) + "\n" if @options[:prompt]
-
select_html << select_options_as_html
-
-
(content_tag(:select, select_html.html_safe, select_options) + "\n").html_safe
-
end
-
-
# Builds a prompt option tag with supplied options or from default options.
-
# prompt_option_tag(:month, prompt: 'Select month')
-
# => "<option value="">Select month</option>"
-
1
def prompt_option_tag(type, options)
-
prompt = case options
-
when Hash
-
default_options = {:year => false, :month => false, :day => false, :hour => false, :minute => false, :second => false}
-
default_options.merge!(options)[type.to_sym]
-
when String
-
options
-
else
-
I18n.translate(:"datetime.prompts.#{type}", :locale => @options[:locale])
-
end
-
-
prompt ? content_tag(:option, prompt, :value => '') : ''
-
end
-
-
# Builds hidden input tag for date part and value.
-
# build_hidden(:year, 2008)
-
# => "<input id="post_written_on_1i" name="post[written_on(1i)]" type="hidden" value="2008" />"
-
1
def build_hidden(type, value)
-
select_options = {
-
:type => "hidden",
-
:id => input_id_from_type(type),
-
:name => input_name_from_type(type),
-
:value => value
-
}.merge!(@html_options.slice(:disabled))
-
select_options[:disabled] = 'disabled' if @options[:disabled]
-
-
tag(:input, select_options) + "\n".html_safe
-
end
-
-
# Returns the name attribute for the input tag.
-
# => post[written_on(1i)]
-
1
def input_name_from_type(type)
-
prefix = @options[:prefix] || ActionView::Helpers::DateTimeSelector::DEFAULT_PREFIX
-
prefix += "[#{@options[:index]}]" if @options.has_key?(:index)
-
-
field_name = @options[:field_name] || type
-
if @options[:include_position]
-
field_name += "(#{ActionView::Helpers::DateTimeSelector::POSITION[type]}i)"
-
end
-
-
@options[:discard_type] ? prefix : "#{prefix}[#{field_name}]"
-
end
-
-
# Returns the id attribute for the input tag.
-
# => "post_written_on_1i"
-
1
def input_id_from_type(type)
-
id = input_name_from_type(type).gsub(/([\[\(])|(\]\[)/, '_').gsub(/[\]\)]/, '')
-
id = @options[:namespace] + '_' + id if @options[:namespace]
-
-
id
-
end
-
-
# Given an ordering of datetime components, create the selection HTML
-
# and join them with their appropriate separators.
-
1
def build_selects_from_types(order)
-
select = ''
-
first_visible = order.find { |type| !@options[:"discard_#{type}"] }
-
order.reverse.each do |type|
-
separator = separator(type) unless type == first_visible # don't add before first visible field
-
select.insert(0, separator.to_s + send("select_#{type}").to_s)
-
end
-
select.html_safe
-
end
-
-
# Returns the separator for a given datetime component.
-
1
def separator(type)
-
return "" if @options[:use_hidden]
-
-
case type
-
when :year, :month, :day
-
@options[:"discard_#{type}"] ? "" : @options[:date_separator]
-
when :hour
-
(@options[:discard_year] && @options[:discard_day]) ? "" : @options[:datetime_separator]
-
when :minute, :second
-
@options[:"discard_#{type}"] ? "" : @options[:time_separator]
-
end
-
end
-
end
-
-
1
class FormBuilder
-
# Wraps ActionView::Helpers::DateHelper#date_select for form builders:
-
#
-
# <%= form_for @person do |f| %>
-
# <%= f.date_select :birth_date %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# Please refer to the documentation of the base helper for details.
-
1
def date_select(method, options = {}, html_options = {})
-
@template.date_select(@object_name, method, objectify_options(options), html_options)
-
end
-
-
# Wraps ActionView::Helpers::DateHelper#time_select for form builders:
-
#
-
# <%= form_for @race do |f| %>
-
# <%= f.time_select :average_lap %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# Please refer to the documentation of the base helper for details.
-
1
def time_select(method, options = {}, html_options = {})
-
@template.time_select(@object_name, method, objectify_options(options), html_options)
-
end
-
-
# Wraps ActionView::Helpers::DateHelper#datetime_select for form builders:
-
#
-
# <%= form_for @person do |f| %>
-
# <%= f.datetime_select :last_request_at %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# Please refer to the documentation of the base helper for details.
-
1
def datetime_select(method, options = {}, html_options = {})
-
@template.datetime_select(@object_name, method, objectify_options(options), html_options)
-
end
-
end
-
end
-
end
-
1
module ActionView
-
# = Action View Debug Helper
-
#
-
# Provides a set of methods for making it easier to debug Rails objects.
-
1
module Helpers
-
1
module DebugHelper
-
-
1
include TagHelper
-
-
# Returns a YAML representation of +object+ wrapped with <pre> and </pre>.
-
# If the object cannot be converted to YAML using +to_yaml+, +inspect+ will be called instead.
-
# Useful for inspecting an object at the time of rendering.
-
#
-
# @user = User.new({ username: 'testing', password: 'xyz', age: 42}) %>
-
# debug(@user)
-
# # =>
-
# <pre class='debug_dump'>--- !ruby/object:User
-
# attributes:
-
# updated_at:
-
# username: testing
-
#
-
# age: 42
-
# password: xyz
-
# created_at:
-
# attributes_cache: {}
-
#
-
# new_record: true
-
# </pre>
-
1
def debug(object)
-
Marshal::dump(object)
-
object = ERB::Util.html_escape(object.to_yaml).gsub(" ", " ").html_safe
-
content_tag(:pre, object, :class => "debug_dump")
-
rescue Exception # errors from Marshal or YAML
-
# Object couldn't be dumped, perhaps because of singleton methods -- this is the fallback
-
content_tag(:code, object.inspect, :class => "debug_dump")
-
end
-
end
-
end
-
end
-
1
require 'cgi'
-
1
require 'action_view/helpers/date_helper'
-
1
require 'action_view/helpers/tag_helper'
-
1
require 'action_view/helpers/form_tag_helper'
-
1
require 'action_view/helpers/active_model_helper'
-
1
require 'action_view/model_naming'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/hash/slice'
-
1
require 'active_support/core_ext/string/output_safety'
-
1
require 'active_support/core_ext/string/inflections'
-
-
1
module ActionView
-
# = Action View Form Helpers
-
1
module Helpers
-
# Form helpers are designed to make working with resources much easier
-
# compared to using vanilla HTML.
-
#
-
# Typically, a form designed to create or update a resource reflects the
-
# identity of the resource in several ways: (i) the url that the form is
-
# sent to (the form element's +action+ attribute) should result in a request
-
# being routed to the appropriate controller action (with the appropriate <tt>:id</tt>
-
# parameter in the case of an existing resource), (ii) input fields should
-
# be named in such a way that in the controller their values appear in the
-
# appropriate places within the +params+ hash, and (iii) for an existing record,
-
# when the form is initially displayed, input fields corresponding to attributes
-
# of the resource should show the current values of those attributes.
-
#
-
# In Rails, this is usually achieved by creating the form using +form_for+ and
-
# a number of related helper methods. +form_for+ generates an appropriate <tt>form</tt>
-
# tag and yields a form builder object that knows the model the form is about.
-
# Input fields are created by calling methods defined on the form builder, which
-
# means they are able to generate the appropriate names and default values
-
# corresponding to the model attributes, as well as convenient IDs, etc.
-
# Conventions in the generated field names allow controllers to receive form data
-
# nicely structured in +params+ with no effort on your side.
-
#
-
# For example, to create a new person you typically set up a new instance of
-
# +Person+ in the <tt>PeopleController#new</tt> action, <tt>@person</tt>, and
-
# in the view template pass that object to +form_for+:
-
#
-
# <%= form_for @person do |f| %>
-
# <%= f.label :first_name %>:
-
# <%= f.text_field :first_name %><br />
-
#
-
# <%= f.label :last_name %>:
-
# <%= f.text_field :last_name %><br />
-
#
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# The HTML generated for this would be (modulus formatting):
-
#
-
# <form action="/people" class="new_person" id="new_person" method="post">
-
# <div style="display:none">
-
# <input name="authenticity_token" type="hidden" value="NrOp5bsjoLRuK8IW5+dQEYjKGUJDe7TQoZVvq95Wteg=" />
-
# </div>
-
# <label for="person_first_name">First name</label>:
-
# <input id="person_first_name" name="person[first_name]" type="text" /><br />
-
#
-
# <label for="person_last_name">Last name</label>:
-
# <input id="person_last_name" name="person[last_name]" type="text" /><br />
-
#
-
# <input name="commit" type="submit" value="Create Person" />
-
# </form>
-
#
-
# As you see, the HTML reflects knowledge about the resource in several spots,
-
# like the path the form should be submitted to, or the names of the input fields.
-
#
-
# In particular, thanks to the conventions followed in the generated field names, the
-
# controller gets a nested hash <tt>params[:person]</tt> with the person attributes
-
# set in the form. That hash is ready to be passed to <tt>Person.create</tt>:
-
#
-
# if @person = Person.create(params[:person])
-
# # success
-
# else
-
# # error handling
-
# end
-
#
-
# Interestingly, the exact same view code in the previous example can be used to edit
-
# a person. If <tt>@person</tt> is an existing record with name "John Smith" and ID 256,
-
# the code above as is would yield instead:
-
#
-
# <form action="/people/256" class="edit_person" id="edit_person_256" method="post">
-
# <div style="display:none">
-
# <input name="_method" type="hidden" value="patch" />
-
# <input name="authenticity_token" type="hidden" value="NrOp5bsjoLRuK8IW5+dQEYjKGUJDe7TQoZVvq95Wteg=" />
-
# </div>
-
# <label for="person_first_name">First name</label>:
-
# <input id="person_first_name" name="person[first_name]" type="text" value="John" /><br />
-
#
-
# <label for="person_last_name">Last name</label>:
-
# <input id="person_last_name" name="person[last_name]" type="text" value="Smith" /><br />
-
#
-
# <input name="commit" type="submit" value="Update Person" />
-
# </form>
-
#
-
# Note that the endpoint, default values, and submit button label are tailored for <tt>@person</tt>.
-
# That works that way because the involved helpers know whether the resource is a new record or not,
-
# and generate HTML accordingly.
-
#
-
# The controller would receive the form data again in <tt>params[:person]</tt>, ready to be
-
# passed to <tt>Person#update</tt>:
-
#
-
# if @person.update(params[:person])
-
# # success
-
# else
-
# # error handling
-
# end
-
#
-
# That's how you typically work with resources.
-
1
module FormHelper
-
1
extend ActiveSupport::Concern
-
-
1
include FormTagHelper
-
1
include UrlHelper
-
1
include ModelNaming
-
-
# Creates a form that allows the user to create or update the attributes
-
# of a specific model object.
-
#
-
# The method can be used in several slightly different ways, depending on
-
# how much you wish to rely on Rails to infer automatically from the model
-
# how the form should be constructed. For a generic model object, a form
-
# can be created by passing +form_for+ a string or symbol representing
-
# the object we are concerned with:
-
#
-
# <%= form_for :person do |f| %>
-
# First name: <%= f.text_field :first_name %><br />
-
# Last name : <%= f.text_field :last_name %><br />
-
# Biography : <%= f.text_area :biography %><br />
-
# Admin? : <%= f.check_box :admin %><br />
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# The variable +f+ yielded to the block is a FormBuilder object that
-
# incorporates the knowledge about the model object represented by
-
# <tt>:person</tt> passed to +form_for+. Methods defined on the FormBuilder
-
# are used to generate fields bound to this model. Thus, for example,
-
#
-
# <%= f.text_field :first_name %>
-
#
-
# will get expanded to
-
#
-
# <%= text_field :person, :first_name %>
-
# which results in an html <tt><input></tt> tag whose +name+ attribute is
-
# <tt>person[first_name]</tt>. This means that when the form is submitted,
-
# the value entered by the user will be available in the controller as
-
# <tt>params[:person][:first_name]</tt>.
-
#
-
# For fields generated in this way using the FormBuilder,
-
# if <tt>:person</tt> also happens to be the name of an instance variable
-
# <tt>@person</tt>, the default value of the field shown when the form is
-
# initially displayed (e.g. in the situation where you are editing an
-
# existing record) will be the value of the corresponding attribute of
-
# <tt>@person</tt>.
-
#
-
# The rightmost argument to +form_for+ is an
-
# optional hash of options -
-
#
-
# * <tt>:url</tt> - The URL the form is to be submitted to. This may be
-
# represented in the same way as values passed to +url_for+ or +link_to+.
-
# So for example you may use a named route directly. When the model is
-
# represented by a string or symbol, as in the example above, if the
-
# <tt>:url</tt> option is not specified, by default the form will be
-
# sent back to the current url (We will describe below an alternative
-
# resource-oriented usage of +form_for+ in which the URL does not need
-
# to be specified explicitly).
-
# * <tt>:namespace</tt> - A namespace for your form to ensure uniqueness of
-
# id attributes on form elements. The namespace attribute will be prefixed
-
# with underscore on the generated HTML id.
-
# * <tt>:html</tt> - Optional HTML attributes for the form tag.
-
#
-
# Also note that +form_for+ doesn't create an exclusive scope. It's still
-
# possible to use both the stand-alone FormHelper methods and methods
-
# from FormTagHelper. For example:
-
#
-
# <%= form_for :person do |f| %>
-
# First name: <%= f.text_field :first_name %>
-
# Last name : <%= f.text_field :last_name %>
-
# Biography : <%= text_area :person, :biography %>
-
# Admin? : <%= check_box_tag "person[admin]", "1", @person.company.admin? %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# This also works for the methods in FormOptionHelper and DateHelper that
-
# are designed to work with an object as base, like
-
# FormOptionHelper#collection_select and DateHelper#datetime_select.
-
#
-
# === #form_for with a model object
-
#
-
# In the examples above, the object to be created or edited was
-
# represented by a symbol passed to +form_for+, and we noted that
-
# a string can also be used equivalently. It is also possible, however,
-
# to pass a model object itself to +form_for+. For example, if <tt>@post</tt>
-
# is an existing record you wish to edit, you can create the form using
-
#
-
# <%= form_for @post do |f| %>
-
# ...
-
# <% end %>
-
#
-
# This behaves in almost the same way as outlined previously, with a
-
# couple of small exceptions. First, the prefix used to name the input
-
# elements within the form (hence the key that denotes them in the +params+
-
# hash) is actually derived from the object's _class_, e.g. <tt>params[:post]</tt>
-
# if the object's class is +Post+. However, this can be overwritten using
-
# the <tt>:as</tt> option, e.g. -
-
#
-
# <%= form_for(@person, as: :client) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# would result in <tt>params[:client]</tt>.
-
#
-
# Secondly, the field values shown when the form is initially displayed
-
# are taken from the attributes of the object passed to +form_for+,
-
# regardless of whether the object is an instance
-
# variable. So, for example, if we had a _local_ variable +post+
-
# representing an existing record,
-
#
-
# <%= form_for post do |f| %>
-
# ...
-
# <% end %>
-
#
-
# would produce a form with fields whose initial state reflect the current
-
# values of the attributes of +post+.
-
#
-
# === Resource-oriented style
-
#
-
# In the examples just shown, although not indicated explicitly, we still
-
# need to use the <tt>:url</tt> option in order to specify where the
-
# form is going to be sent. However, further simplification is possible
-
# if the record passed to +form_for+ is a _resource_, i.e. it corresponds
-
# to a set of RESTful routes, e.g. defined using the +resources+ method
-
# in <tt>config/routes.rb</tt>. In this case Rails will simply infer the
-
# appropriate URL from the record itself. For example,
-
#
-
# <%= form_for @post do |f| %>
-
# ...
-
# <% end %>
-
#
-
# is then equivalent to something like:
-
#
-
# <%= form_for @post, as: :post, url: post_path(@post), method: :patch, html: { class: "edit_post", id: "edit_post_45" } do |f| %>
-
# ...
-
# <% end %>
-
#
-
# And for a new record
-
#
-
# <%= form_for(Post.new) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# is equivalent to something like:
-
#
-
# <%= form_for @post, as: :post, url: posts_path, html: { class: "new_post", id: "new_post" } do |f| %>
-
# ...
-
# <% end %>
-
#
-
# However you can still overwrite individual conventions, such as:
-
#
-
# <%= form_for(@post, url: super_posts_path) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# You can also set the answer format, like this:
-
#
-
# <%= form_for(@post, format: :json) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# For namespaced routes, like +admin_post_url+:
-
#
-
# <%= form_for([:admin, @post]) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# If your resource has associations defined, for example, you want to add comments
-
# to the document given that the routes are set correctly:
-
#
-
# <%= form_for([@document, @comment]) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# Where <tt>@document = Document.find(params[:id])</tt> and
-
# <tt>@comment = Comment.new</tt>.
-
#
-
# === Setting the method
-
#
-
# You can force the form to use the full array of HTTP verbs by setting
-
#
-
# method: (:get|:post|:patch|:put|:delete)
-
#
-
# in the options hash. If the verb is not GET or POST, which are natively
-
# supported by HTML forms, the form will be set to POST and a hidden input
-
# called _method will carry the intended verb for the server to interpret.
-
#
-
# === Unobtrusive JavaScript
-
#
-
# Specifying:
-
#
-
# remote: true
-
#
-
# in the options hash creates a form that will allow the unobtrusive JavaScript drivers to modify its
-
# behavior. The expected default behavior is an XMLHttpRequest in the background instead of the regular
-
# POST arrangement, but ultimately the behavior is the choice of the JavaScript driver implementor.
-
# Even though it's using JavaScript to serialize the form elements, the form submission will work just like
-
# a regular submission as viewed by the receiving side (all elements available in <tt>params</tt>).
-
#
-
# Example:
-
#
-
# <%= form_for(@post, remote: true) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# The HTML generated for this would be:
-
#
-
# <form action='http://www.example.com' method='post' data-remote='true'>
-
# <div style='display:none'>
-
# <input name='_method' type='hidden' value='patch' />
-
# </div>
-
# ...
-
# </form>
-
#
-
# === Setting HTML options
-
#
-
# You can set data attributes directly by passing in a data hash, but all other HTML options must be wrapped in
-
# the HTML key. Example:
-
#
-
# <%= form_for(@post, data: { behavior: "autosave" }, html: { name: "go" }) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# The HTML generated for this would be:
-
#
-
# <form action='http://www.example.com' method='post' data-behavior='autosave' name='go'>
-
# <div style='display:none'>
-
# <input name='_method' type='hidden' value='patch' />
-
# </div>
-
# ...
-
# </form>
-
#
-
# === Removing hidden model id's
-
#
-
# The form_for method automatically includes the model id as a hidden field in the form.
-
# This is used to maintain the correlation between the form data and its associated model.
-
# Some ORM systems do not use IDs on nested models so in this case you want to be able
-
# to disable the hidden id.
-
#
-
# In the following example the Post model has many Comments stored within it in a NoSQL database,
-
# thus there is no primary key for comments.
-
#
-
# Example:
-
#
-
# <%= form_for(@post) do |f| %>
-
# <%= f.fields_for(:comments, include_id: false) do |cf| %>
-
# ...
-
# <% end %>
-
# <% end %>
-
#
-
# === Customized form builders
-
#
-
# You can also build forms using a customized FormBuilder class. Subclass
-
# FormBuilder and override or define some more helpers, then use your
-
# custom builder. For example, let's say you made a helper to
-
# automatically add labels to form inputs.
-
#
-
# <%= form_for @person, url: { action: "create" }, builder: LabellingFormBuilder do |f| %>
-
# <%= f.text_field :first_name %>
-
# <%= f.text_field :last_name %>
-
# <%= f.text_area :biography %>
-
# <%= f.check_box :admin %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# In this case, if you use this:
-
#
-
# <%= render f %>
-
#
-
# The rendered template is <tt>people/_labelling_form</tt> and the local
-
# variable referencing the form builder is called
-
# <tt>labelling_form</tt>.
-
#
-
# The custom FormBuilder class is automatically merged with the options
-
# of a nested fields_for call, unless it's explicitly set.
-
#
-
# In many cases you will want to wrap the above in another helper, so you
-
# could do something like the following:
-
#
-
# def labelled_form_for(record_or_name_or_array, *args, &block)
-
# options = args.extract_options!
-
# form_for(record_or_name_or_array, *(args << options.merge(builder: LabellingFormBuilder)), &block)
-
# end
-
#
-
# If you don't need to attach a form to a model instance, then check out
-
# FormTagHelper#form_tag.
-
#
-
# === Form to external resources
-
#
-
# When you build forms to external resources sometimes you need to set an authenticity token or just render a form
-
# without it, for example when you submit data to a payment gateway number and types of fields could be limited.
-
#
-
# To set an authenticity token you need to pass an <tt>:authenticity_token</tt> parameter
-
#
-
# <%= form_for @invoice, url: external_url, authenticity_token: 'external_token' do |f|
-
# ...
-
# <% end %>
-
#
-
# If you don't want to an authenticity token field be rendered at all just pass <tt>false</tt>:
-
#
-
# <%= form_for @invoice, url: external_url, authenticity_token: false do |f|
-
# ...
-
# <% end %>
-
1
def form_for(record, options = {}, &block)
-
raise ArgumentError, "Missing block" unless block_given?
-
html_options = options[:html] ||= {}
-
-
case record
-
when String, Symbol
-
object_name = record
-
object = nil
-
else
-
object = record.is_a?(Array) ? record.last : record
-
raise ArgumentError, "First argument in form cannot contain nil or be empty" unless object
-
object_name = options[:as] || model_name_from_record_or_class(object).param_key
-
apply_form_for_options!(record, object, options)
-
end
-
-
html_options[:data] = options.delete(:data) if options.has_key?(:data)
-
html_options[:remote] = options.delete(:remote) if options.has_key?(:remote)
-
html_options[:method] = options.delete(:method) if options.has_key?(:method)
-
html_options[:authenticity_token] = options.delete(:authenticity_token)
-
-
builder = instantiate_builder(object_name, object, options)
-
output = capture(builder, &block)
-
html_options[:multipart] ||= builder.multipart?
-
-
form_tag(options[:url] || {}, html_options) { output }
-
end
-
-
1
def apply_form_for_options!(record, object, options) #:nodoc:
-
object = convert_to_model(object)
-
-
as = options[:as]
-
namespace = options[:namespace]
-
action, method = object.respond_to?(:persisted?) && object.persisted? ? [:edit, :patch] : [:new, :post]
-
options[:html].reverse_merge!(
-
class: as ? "#{action}_#{as}" : dom_class(object, action),
-
id: (as ? [namespace, action, as] : [namespace, dom_id(object, action)]).compact.join("_").presence,
-
method: method
-
)
-
-
options[:url] ||= polymorphic_path(record, format: options.delete(:format))
-
end
-
1
private :apply_form_for_options!
-
-
# Creates a scope around a specific model object like form_for, but
-
# doesn't create the form tags themselves. This makes fields_for suitable
-
# for specifying additional model objects in the same form.
-
#
-
# Although the usage and purpose of +field_for+ is similar to +form_for+'s,
-
# its method signature is slightly different. Like +form_for+, it yields
-
# a FormBuilder object associated with a particular model object to a block,
-
# and within the block allows methods to be called on the builder to
-
# generate fields associated with the model object. Fields may reflect
-
# a model object in two ways - how they are named (hence how submitted
-
# values appear within the +params+ hash in the controller) and what
-
# default values are shown when the form the fields appear in is first
-
# displayed. In order for both of these features to be specified independently,
-
# both an object name (represented by either a symbol or string) and the
-
# object itself can be passed to the method separately -
-
#
-
# <%= form_for @person do |person_form| %>
-
# First name: <%= person_form.text_field :first_name %>
-
# Last name : <%= person_form.text_field :last_name %>
-
#
-
# <%= fields_for :permission, @person.permission do |permission_fields| %>
-
# Admin? : <%= permission_fields.check_box :admin %>
-
# <% end %>
-
#
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# In this case, the checkbox field will be represented by an HTML +input+
-
# tag with the +name+ attribute <tt>permission[admin]</tt>, and the submitted
-
# value will appear in the controller as <tt>params[:permission][:admin]</tt>.
-
# If <tt>@person.permission</tt> is an existing record with an attribute
-
# +admin+, the initial state of the checkbox when first displayed will
-
# reflect the value of <tt>@person.permission.admin</tt>.
-
#
-
# Often this can be simplified by passing just the name of the model
-
# object to +fields_for+ -
-
#
-
# <%= fields_for :permission do |permission_fields| %>
-
# Admin?: <%= permission_fields.check_box :admin %>
-
# <% end %>
-
#
-
# ...in which case, if <tt>:permission</tt> also happens to be the name of an
-
# instance variable <tt>@permission</tt>, the initial state of the input
-
# field will reflect the value of that variable's attribute <tt>@permission.admin</tt>.
-
#
-
# Alternatively, you can pass just the model object itself (if the first
-
# argument isn't a string or symbol +fields_for+ will realize that the
-
# name has been omitted) -
-
#
-
# <%= fields_for @person.permission do |permission_fields| %>
-
# Admin?: <%= permission_fields.check_box :admin %>
-
# <% end %>
-
#
-
# and +fields_for+ will derive the required name of the field from the
-
# _class_ of the model object, e.g. if <tt>@person.permission</tt>, is
-
# of class +Permission+, the field will still be named <tt>permission[admin]</tt>.
-
#
-
# Note: This also works for the methods in FormOptionHelper and
-
# DateHelper that are designed to work with an object as base, like
-
# FormOptionHelper#collection_select and DateHelper#datetime_select.
-
#
-
# === Nested Attributes Examples
-
#
-
# When the object belonging to the current scope has a nested attribute
-
# writer for a certain attribute, fields_for will yield a new scope
-
# for that attribute. This allows you to create forms that set or change
-
# the attributes of a parent object and its associations in one go.
-
#
-
# Nested attribute writers are normal setter methods named after an
-
# association. The most common way of defining these writers is either
-
# with +accepts_nested_attributes_for+ in a model definition or by
-
# defining a method with the proper name. For example: the attribute
-
# writer for the association <tt>:address</tt> is called
-
# <tt>address_attributes=</tt>.
-
#
-
# Whether a one-to-one or one-to-many style form builder will be yielded
-
# depends on whether the normal reader method returns a _single_ object
-
# or an _array_ of objects.
-
#
-
# ==== One-to-one
-
#
-
# Consider a Person class which returns a _single_ Address from the
-
# <tt>address</tt> reader method and responds to the
-
# <tt>address_attributes=</tt> writer method:
-
#
-
# class Person
-
# def address
-
# @address
-
# end
-
#
-
# def address_attributes=(attributes)
-
# # Process the attributes hash
-
# end
-
# end
-
#
-
# This model can now be used with a nested fields_for, like so:
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :address do |address_fields| %>
-
# Street : <%= address_fields.text_field :street %>
-
# Zip code: <%= address_fields.text_field :zip_code %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# When address is already an association on a Person you can use
-
# +accepts_nested_attributes_for+ to define the writer method for you:
-
#
-
# class Person < ActiveRecord::Base
-
# has_one :address
-
# accepts_nested_attributes_for :address
-
# end
-
#
-
# If you want to destroy the associated model through the form, you have
-
# to enable it first using the <tt>:allow_destroy</tt> option for
-
# +accepts_nested_attributes_for+:
-
#
-
# class Person < ActiveRecord::Base
-
# has_one :address
-
# accepts_nested_attributes_for :address, allow_destroy: true
-
# end
-
#
-
# Now, when you use a form element with the <tt>_destroy</tt> parameter,
-
# with a value that evaluates to +true+, you will destroy the associated
-
# model (eg. 1, '1', true, or 'true'):
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :address do |address_fields| %>
-
# ...
-
# Delete: <%= address_fields.check_box :_destroy %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# ==== One-to-many
-
#
-
# Consider a Person class which returns an _array_ of Project instances
-
# from the <tt>projects</tt> reader method and responds to the
-
# <tt>projects_attributes=</tt> writer method:
-
#
-
# class Person
-
# def projects
-
# [@project1, @project2]
-
# end
-
#
-
# def projects_attributes=(attributes)
-
# # Process the attributes hash
-
# end
-
# end
-
#
-
# Note that the <tt>projects_attributes=</tt> writer method is in fact
-
# required for fields_for to correctly identify <tt>:projects</tt> as a
-
# collection, and the correct indices to be set in the form markup.
-
#
-
# When projects is already an association on Person you can use
-
# +accepts_nested_attributes_for+ to define the writer method for you:
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :projects
-
# accepts_nested_attributes_for :projects
-
# end
-
#
-
# This model can now be used with a nested fields_for. The block given to
-
# the nested fields_for call will be repeated for each instance in the
-
# collection:
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :projects do |project_fields| %>
-
# <% if project_fields.object.active? %>
-
# Name: <%= project_fields.text_field :name %>
-
# <% end %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# It's also possible to specify the instance to be used:
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <% @person.projects.each do |project| %>
-
# <% if project.active? %>
-
# <%= person_form.fields_for :projects, project do |project_fields| %>
-
# Name: <%= project_fields.text_field :name %>
-
# <% end %>
-
# <% end %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# Or a collection to be used:
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :projects, @active_projects do |project_fields| %>
-
# Name: <%= project_fields.text_field :name %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# If you want to destroy any of the associated models through the
-
# form, you have to enable it first using the <tt>:allow_destroy</tt>
-
# option for +accepts_nested_attributes_for+:
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :projects
-
# accepts_nested_attributes_for :projects, allow_destroy: true
-
# end
-
#
-
# This will allow you to specify which models to destroy in the
-
# attributes hash by adding a form element for the <tt>_destroy</tt>
-
# parameter with a value that evaluates to +true+
-
# (eg. 1, '1', true, or 'true'):
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :projects do |project_fields| %>
-
# Delete: <%= project_fields.check_box :_destroy %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# When a collection is used you might want to know the index of each
-
# object into the array. For this purpose, the <tt>index</tt> method
-
# is available in the FormBuilder object.
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :projects do |project_fields| %>
-
# Project #<%= project_fields.index %>
-
# ...
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# Note that fields_for will automatically generate a hidden field
-
# to store the ID of the record. There are circumstances where this
-
# hidden field is not needed and you can pass <tt>include_id: false</tt>
-
# to prevent fields_for from rendering it automatically.
-
1
def fields_for(record_name, record_object = nil, options = {}, &block)
-
builder = instantiate_builder(record_name, record_object, options)
-
capture(builder, &block)
-
end
-
-
# Returns a label tag tailored for labelling an input field for a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). The text of label will default to the attribute name unless a translation
-
# is found in the current I18n locale (through helpers.label.<modelname>.<attribute>) or you specify it explicitly.
-
# Additional options on the label tag can be passed as a hash with +options+. These options will be tagged
-
# onto the HTML as an HTML element attribute as in the example shown, except for the <tt>:value</tt> option, which is designed to
-
# target labels for radio_button tags (where the value is used in the ID of the input tag).
-
#
-
# ==== Examples
-
# label(:post, :title)
-
# # => <label for="post_title">Title</label>
-
#
-
# You can localize your labels based on model and attribute names.
-
# For example you can define the following in your locale (e.g. en.yml)
-
#
-
# helpers:
-
# label:
-
# post:
-
# body: "Write your entire text here"
-
#
-
# Which then will result in
-
#
-
# label(:post, :body)
-
# # => <label for="post_body">Write your entire text here</label>
-
#
-
# Localization can also be based purely on the translation of the attribute-name
-
# (if you are using ActiveRecord):
-
#
-
# activerecord:
-
# attributes:
-
# post:
-
# cost: "Total cost"
-
#
-
# label(:post, :cost)
-
# # => <label for="post_cost">Total cost</label>
-
#
-
# label(:post, :title, "A short title")
-
# # => <label for="post_title">A short title</label>
-
#
-
# label(:post, :title, "A short title", class: "title_label")
-
# # => <label for="post_title" class="title_label">A short title</label>
-
#
-
# label(:post, :privacy, "Public Post", value: "public")
-
# # => <label for="post_privacy_public">Public Post</label>
-
#
-
# label(:post, :terms) do
-
# 'Accept <a href="/terms">Terms</a>.'.html_safe
-
# end
-
1
def label(object_name, method, content_or_options = nil, options = nil, &block)
-
Tags::Label.new(object_name, method, self, content_or_options, options).render(&block)
-
end
-
-
# Returns an input tag of the "text" type tailored for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
-
# hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
-
# shown.
-
#
-
# ==== Examples
-
# text_field(:post, :title, size: 20)
-
# # => <input type="text" id="post_title" name="post[title]" size="20" value="#{@post.title}" />
-
#
-
# text_field(:post, :title, class: "create_input")
-
# # => <input type="text" id="post_title" name="post[title]" value="#{@post.title}" class="create_input" />
-
#
-
# text_field(:session, :user, onchange: "if ($('#session_user').val() === 'admin') { alert('Your login cannot be admin!'); }")
-
# # => <input type="text" id="session_user" name="session[user]" value="#{@session.user}" onchange="if ($('#session_user').val() === 'admin') { alert('Your login cannot be admin!'); }"/>
-
#
-
# text_field(:snippet, :code, size: 20, class: 'code_input')
-
# # => <input type="text" id="snippet_code" name="snippet[code]" size="20" value="#{@snippet.code}" class="code_input" />
-
1
def text_field(object_name, method, options = {})
-
Tags::TextField.new(object_name, method, self, options).render
-
end
-
-
# Returns an input tag of the "password" type tailored for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
-
# hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
-
# shown. For security reasons this field is blank by default; pass in a value via +options+ if this is not desired.
-
#
-
# ==== Examples
-
# password_field(:login, :pass, size: 20)
-
# # => <input type="password" id="login_pass" name="login[pass]" size="20" />
-
#
-
# password_field(:account, :secret, class: "form_input", value: @account.secret)
-
# # => <input type="password" id="account_secret" name="account[secret]" value="#{@account.secret}" class="form_input" />
-
#
-
# password_field(:user, :password, onchange: "if ($('#user_password').val().length > 30) { alert('Your password needs to be shorter!'); }")
-
# # => <input type="password" id="user_password" name="user[password]" onchange="if ($('#user_password').val().length > 30) { alert('Your password needs to be shorter!'); }"/>
-
#
-
# password_field(:account, :pin, size: 20, class: 'form_input')
-
# # => <input type="password" id="account_pin" name="account[pin]" size="20" class="form_input" />
-
1
def password_field(object_name, method, options = {})
-
Tags::PasswordField.new(object_name, method, self, options).render
-
end
-
-
# Returns a hidden input tag tailored for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
-
# hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
-
# shown.
-
#
-
# ==== Examples
-
# hidden_field(:signup, :pass_confirm)
-
# # => <input type="hidden" id="signup_pass_confirm" name="signup[pass_confirm]" value="#{@signup.pass_confirm}" />
-
#
-
# hidden_field(:post, :tag_list)
-
# # => <input type="hidden" id="post_tag_list" name="post[tag_list]" value="#{@post.tag_list}" />
-
#
-
# hidden_field(:user, :token)
-
# # => <input type="hidden" id="user_token" name="user[token]" value="#{@user.token}" />
-
1
def hidden_field(object_name, method, options = {})
-
Tags::HiddenField.new(object_name, method, self, options).render
-
end
-
-
# Returns a file upload input tag tailored for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
-
# hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
-
# shown.
-
#
-
# Using this method inside a +form_for+ block will set the enclosing form's encoding to <tt>multipart/form-data</tt>.
-
#
-
# ==== Options
-
# * Creates standard HTML attributes for the tag.
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * <tt>:multiple</tt> - If set to true, *in most updated browsers* the user will be allowed to select multiple files.
-
# * <tt>:accept</tt> - If set to one or multiple mime-types, the user will be suggested a filter when choosing a file. You still need to set up model validations.
-
#
-
# ==== Examples
-
# file_field(:user, :avatar)
-
# # => <input type="file" id="user_avatar" name="user[avatar]" />
-
#
-
# file_field(:post, :image, :multiple => true)
-
# # => <input type="file" id="post_image" name="post[image]" multiple="true" />
-
#
-
# file_field(:post, :attached, accept: 'text/html')
-
# # => <input accept="text/html" type="file" id="post_attached" name="post[attached]" />
-
#
-
# file_field(:post, :image, accept: 'image/png,image/gif,image/jpeg')
-
# # => <input type="file" id="post_image" name="post[image]" accept="image/png,image/gif,image/jpeg" />
-
#
-
# file_field(:attachment, :file, class: 'file_input')
-
# # => <input type="file" id="attachment_file" name="attachment[file]" class="file_input" />
-
1
def file_field(object_name, method, options = {})
-
Tags::FileField.new(object_name, method, self, options).render
-
end
-
-
# Returns a textarea opening and closing tag set tailored for accessing a specified attribute (identified by +method+)
-
# on an object assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
-
# hash with +options+.
-
#
-
# ==== Examples
-
# text_area(:post, :body, cols: 20, rows: 40)
-
# # => <textarea cols="20" rows="40" id="post_body" name="post[body]">
-
# # #{@post.body}
-
# # </textarea>
-
#
-
# text_area(:comment, :text, size: "20x30")
-
# # => <textarea cols="20" rows="30" id="comment_text" name="comment[text]">
-
# # #{@comment.text}
-
# # </textarea>
-
#
-
# text_area(:application, :notes, cols: 40, rows: 15, class: 'app_input')
-
# # => <textarea cols="40" rows="15" id="application_notes" name="application[notes]" class="app_input">
-
# # #{@application.notes}
-
# # </textarea>
-
#
-
# text_area(:entry, :body, size: "20x20", disabled: 'disabled')
-
# # => <textarea cols="20" rows="20" id="entry_body" name="entry[body]" disabled="disabled">
-
# # #{@entry.body}
-
# # </textarea>
-
1
def text_area(object_name, method, options = {})
-
Tags::TextArea.new(object_name, method, self, options).render
-
end
-
-
# Returns a checkbox tag tailored for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). This object must be an instance object (@object) and not a local object.
-
# It's intended that +method+ returns an integer and if that integer is above zero, then the checkbox is checked.
-
# Additional options on the input tag can be passed as a hash with +options+. The +checked_value+ defaults to 1
-
# while the default +unchecked_value+ is set to 0 which is convenient for boolean values.
-
#
-
# ==== Gotcha
-
#
-
# The HTML specification says unchecked check boxes are not successful, and
-
# thus web browsers do not send them. Unfortunately this introduces a gotcha:
-
# if an +Invoice+ model has a +paid+ flag, and in the form that edits a paid
-
# invoice the user unchecks its check box, no +paid+ parameter is sent. So,
-
# any mass-assignment idiom like
-
#
-
# @invoice.update(params[:invoice])
-
#
-
# wouldn't update the flag.
-
#
-
# To prevent this the helper generates an auxiliary hidden field before
-
# the very check box. The hidden field has the same name and its
-
# attributes mimic an unchecked check box.
-
#
-
# This way, the client either sends only the hidden field (representing
-
# the check box is unchecked), or both fields. Since the HTML specification
-
# says key/value pairs have to be sent in the same order they appear in the
-
# form, and parameters extraction gets the last occurrence of any repeated
-
# key in the query string, that works for ordinary forms.
-
#
-
# Unfortunately that workaround does not work when the check box goes
-
# within an array-like parameter, as in
-
#
-
# <%= fields_for "project[invoice_attributes][]", invoice, index: nil do |form| %>
-
# <%= form.check_box :paid %>
-
# ...
-
# <% end %>
-
#
-
# because parameter name repetition is precisely what Rails seeks to distinguish
-
# the elements of the array. For each item with a checked check box you
-
# get an extra ghost item with only that attribute, assigned to "0".
-
#
-
# In that case it is preferable to either use +check_box_tag+ or to use
-
# hashes instead of arrays.
-
#
-
# # Let's say that @post.validated? is 1:
-
# check_box("post", "validated")
-
# # => <input name="post[validated]" type="hidden" value="0" />
-
# # <input checked="checked" type="checkbox" id="post_validated" name="post[validated]" value="1" />
-
#
-
# # Let's say that @puppy.gooddog is "no":
-
# check_box("puppy", "gooddog", {}, "yes", "no")
-
# # => <input name="puppy[gooddog]" type="hidden" value="no" />
-
# # <input type="checkbox" id="puppy_gooddog" name="puppy[gooddog]" value="yes" />
-
#
-
# check_box("eula", "accepted", { class: 'eula_check' }, "yes", "no")
-
# # => <input name="eula[accepted]" type="hidden" value="no" />
-
# # <input type="checkbox" class="eula_check" id="eula_accepted" name="eula[accepted]" value="yes" />
-
1
def check_box(object_name, method, options = {}, checked_value = "1", unchecked_value = "0")
-
Tags::CheckBox.new(object_name, method, self, checked_value, unchecked_value, options).render
-
end
-
-
# Returns a radio button tag for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). If the current value of +method+ is +tag_value+ the
-
# radio button will be checked.
-
#
-
# To force the radio button to be checked pass <tt>checked: true</tt> in the
-
# +options+ hash. You may pass HTML options there as well.
-
#
-
# # Let's say that @post.category returns "rails":
-
# radio_button("post", "category", "rails")
-
# radio_button("post", "category", "java")
-
# # => <input type="radio" id="post_category_rails" name="post[category]" value="rails" checked="checked" />
-
# # <input type="radio" id="post_category_java" name="post[category]" value="java" />
-
#
-
# radio_button("user", "receive_newsletter", "yes")
-
# radio_button("user", "receive_newsletter", "no")
-
# # => <input type="radio" id="user_receive_newsletter_yes" name="user[receive_newsletter]" value="yes" />
-
# # <input type="radio" id="user_receive_newsletter_no" name="user[receive_newsletter]" value="no" checked="checked" />
-
1
def radio_button(object_name, method, tag_value, options = {})
-
Tags::RadioButton.new(object_name, method, self, tag_value, options).render
-
end
-
-
# Returns a text_field of type "color".
-
#
-
# color_field("car", "color")
-
# # => <input id="car_color" name="car[color]" type="color" value="#000000" />
-
1
def color_field(object_name, method, options = {})
-
Tags::ColorField.new(object_name, method, self, options).render
-
end
-
-
# Returns an input of type "search" for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object_name+). Inputs of type "search" may be styled differently by
-
# some browsers.
-
#
-
# search_field(:user, :name)
-
# # => <input id="user_name" name="user[name]" type="search" />
-
# search_field(:user, :name, autosave: false)
-
# # => <input autosave="false" id="user_name" name="user[name]" type="search" />
-
# search_field(:user, :name, results: 3)
-
# # => <input id="user_name" name="user[name]" results="3" type="search" />
-
# # Assume request.host returns "www.example.com"
-
# search_field(:user, :name, autosave: true)
-
# # => <input autosave="com.example.www" id="user_name" name="user[name]" results="10" type="search" />
-
# search_field(:user, :name, onsearch: true)
-
# # => <input id="user_name" incremental="true" name="user[name]" onsearch="true" type="search" />
-
# search_field(:user, :name, autosave: false, onsearch: true)
-
# # => <input autosave="false" id="user_name" incremental="true" name="user[name]" onsearch="true" type="search" />
-
# search_field(:user, :name, autosave: true, onsearch: true)
-
# # => <input autosave="com.example.www" id="user_name" incremental="true" name="user[name]" onsearch="true" results="10" type="search" />
-
1
def search_field(object_name, method, options = {})
-
Tags::SearchField.new(object_name, method, self, options).render
-
end
-
-
# Returns a text_field of type "tel".
-
#
-
# telephone_field("user", "phone")
-
# # => <input id="user_phone" name="user[phone]" type="tel" />
-
#
-
1
def telephone_field(object_name, method, options = {})
-
Tags::TelField.new(object_name, method, self, options).render
-
end
-
# aliases telephone_field
-
1
alias phone_field telephone_field
-
-
# Returns a text_field of type "date".
-
#
-
# date_field("user", "born_on")
-
# # => <input id="user_born_on" name="user[born_on]" type="date" />
-
#
-
# The default value is generated by trying to call "to_date"
-
# on the object's value, which makes it behave as expected for instances
-
# of DateTime and ActiveSupport::TimeWithZone. You can still override that
-
# by passing the "value" option explicitly, e.g.
-
#
-
# @user.born_on = Date.new(1984, 1, 27)
-
# date_field("user", "born_on", value: "1984-05-12")
-
# # => <input id="user_born_on" name="user[born_on]" type="date" value="1984-05-12" />
-
#
-
1
def date_field(object_name, method, options = {})
-
Tags::DateField.new(object_name, method, self, options).render
-
end
-
-
# Returns a text_field of type "time".
-
#
-
# The default value is generated by trying to call +strftime+ with "%T.%L"
-
# on the objects's value. It is still possible to override that
-
# by passing the "value" option.
-
#
-
# === Options
-
# * Accepts same options as time_field_tag
-
#
-
# === Example
-
# time_field("task", "started_at")
-
# # => <input id="task_started_at" name="task[started_at]" type="time" />
-
#
-
1
def time_field(object_name, method, options = {})
-
Tags::TimeField.new(object_name, method, self, options).render
-
end
-
-
# Returns a text_field of type "datetime".
-
#
-
# datetime_field("user", "born_on")
-
# # => <input id="user_born_on" name="user[born_on]" type="datetime" />
-
#
-
# The default value is generated by trying to call +strftime+ with "%Y-%m-%dT%T.%L%z"
-
# on the object's value, which makes it behave as expected for instances
-
# of DateTime and ActiveSupport::TimeWithZone.
-
#
-
# @user.born_on = Date.new(1984, 1, 12)
-
# datetime_field("user", "born_on")
-
# # => <input id="user_born_on" name="user[born_on]" type="datetime" value="1984-01-12T00:00:00.000+0000" />
-
#
-
1
def datetime_field(object_name, method, options = {})
-
Tags::DatetimeField.new(object_name, method, self, options).render
-
end
-
-
# Returns a text_field of type "datetime-local".
-
#
-
# datetime_local_field("user", "born_on")
-
# # => <input id="user_born_on" name="user[born_on]" type="datetime-local" />
-
#
-
# The default value is generated by trying to call +strftime+ with "%Y-%m-%dT%T"
-
# on the object's value, which makes it behave as expected for instances
-
# of DateTime and ActiveSupport::TimeWithZone.
-
#
-
# @user.born_on = Date.new(1984, 1, 12)
-
# datetime_local_field("user", "born_on")
-
# # => <input id="user_born_on" name="user[born_on]" type="datetime-local" value="1984-01-12T00:00:00" />
-
#
-
1
def datetime_local_field(object_name, method, options = {})
-
Tags::DatetimeLocalField.new(object_name, method, self, options).render
-
end
-
-
# Returns a text_field of type "month".
-
#
-
# month_field("user", "born_on")
-
# # => <input id="user_born_on" name="user[born_on]" type="month" />
-
#
-
# The default value is generated by trying to call +strftime+ with "%Y-%m"
-
# on the object's value, which makes it behave as expected for instances
-
# of DateTime and ActiveSupport::TimeWithZone.
-
#
-
# @user.born_on = Date.new(1984, 1, 27)
-
# month_field("user", "born_on")
-
# # => <input id="user_born_on" name="user[born_on]" type="date" value="1984-01" />
-
#
-
1
def month_field(object_name, method, options = {})
-
Tags::MonthField.new(object_name, method, self, options).render
-
end
-
-
# Returns a text_field of type "week".
-
#
-
# week_field("user", "born_on")
-
# # => <input id="user_born_on" name="user[born_on]" type="week" />
-
#
-
# The default value is generated by trying to call +strftime+ with "%Y-W%W"
-
# on the object's value, which makes it behave as expected for instances
-
# of DateTime and ActiveSupport::TimeWithZone.
-
#
-
# @user.born_on = Date.new(1984, 5, 12)
-
# week_field("user", "born_on")
-
# # => <input id="user_born_on" name="user[born_on]" type="date" value="1984-W19" />
-
#
-
1
def week_field(object_name, method, options = {})
-
Tags::WeekField.new(object_name, method, self, options).render
-
end
-
-
# Returns a text_field of type "url".
-
#
-
# url_field("user", "homepage")
-
# # => <input id="user_homepage" name="user[homepage]" type="url" />
-
#
-
1
def url_field(object_name, method, options = {})
-
Tags::UrlField.new(object_name, method, self, options).render
-
end
-
-
# Returns a text_field of type "email".
-
#
-
# email_field("user", "address")
-
# # => <input id="user_address" name="user[address]" type="email" />
-
#
-
1
def email_field(object_name, method, options = {})
-
Tags::EmailField.new(object_name, method, self, options).render
-
end
-
-
# Returns an input tag of type "number".
-
#
-
# ==== Options
-
# * Accepts same options as number_field_tag
-
1
def number_field(object_name, method, options = {})
-
Tags::NumberField.new(object_name, method, self, options).render
-
end
-
-
# Returns an input tag of type "range".
-
#
-
# ==== Options
-
# * Accepts same options as range_field_tag
-
1
def range_field(object_name, method, options = {})
-
Tags::RangeField.new(object_name, method, self, options).render
-
end
-
-
1
private
-
-
1
def instantiate_builder(record_name, record_object, options)
-
case record_name
-
when String, Symbol
-
object = record_object
-
object_name = record_name
-
else
-
object = record_name
-
object_name = model_name_from_record_or_class(object).param_key
-
end
-
-
builder = options[:builder] || default_form_builder
-
builder.new(object_name, object, self, options)
-
end
-
-
1
def default_form_builder
-
builder = ActionView::Base.default_form_builder
-
builder.respond_to?(:constantize) ? builder.constantize : builder
-
end
-
end
-
-
# A +FormBuilder+ object is associated with a particular model object and
-
# allows you to generate fields associated with the model object. The
-
# +FormBuilder+ object is yielded when using +form_for+ or +fields_for+.
-
# For example:
-
#
-
# <%= form_for @person do |person_form| %>
-
# Name: <%= person_form.text_field :name %>
-
# Admin: <%= person_form.check_box :admin %>
-
# <% end %>
-
#
-
# In the above block, the a +FormBuilder+ object is yielded as the
-
# +person_form+ variable. This allows you to generate the +text_field+
-
# and +check_box+ fields by specifying their eponymous methods, which
-
# modify the underlying template and associates the +@person+ model object
-
# with the form.
-
#
-
# The +FormBuilder+ object can be thought of as serving as a proxy for the
-
# methods in the +FormHelper+ module. This class, however, allows you to
-
# call methods with the model object you are building the form for.
-
#
-
# You can create your own custom FormBuilder templates by subclassing this
-
# class. For example:
-
#
-
# class MyFormBuilder < ActionView::Helpers::FormBuilder
-
# def div_radio_button(method, tag_value, options = {})
-
# @template.content_tag(:div,
-
# @template.radio_button(
-
# @object_name, method, tag_value, objectify_options(options)
-
# )
-
# )
-
# end
-
#
-
# The above code creates a new method +div_radio_button+ which wraps a div
-
# around the a new radio button. Note that when options are passed in, you
-
# must called +objectify_options+ in order for the model object to get
-
# correctly passed to the method. If +objectify_options+ is not called,
-
# then the newly created helper will not be linked back to the model.
-
#
-
# The +div_radio_button+ code from above can now be used as follows:
-
#
-
# <%= form_for @person, :builder => MyFormBuilder do |f| %>
-
# I am a child: <%= f.div_radio_button(:admin, "child") %>
-
# I am an adult: <%= f.div_radio_button(:admin, "adult") %>
-
# <% end -%>
-
#
-
# The standard set of helper methods for form building are located in the
-
# +field_helpers+ class attribute.
-
1
class FormBuilder
-
1
include ModelNaming
-
-
# The methods which wrap a form helper call.
-
1
class_attribute :field_helpers
-
1
self.field_helpers = [:fields_for, :label, :text_field, :password_field,
-
:hidden_field, :file_field, :text_area, :check_box,
-
:radio_button, :color_field, :search_field,
-
:telephone_field, :phone_field, :date_field,
-
:time_field, :datetime_field, :datetime_local_field,
-
:month_field, :week_field, :url_field, :email_field,
-
:number_field, :range_field]
-
-
1
attr_accessor :object_name, :object, :options
-
-
1
attr_reader :multipart, :index
-
1
alias :multipart? :multipart
-
-
1
def multipart=(multipart)
-
@multipart = multipart
-
-
if parent_builder = @options[:parent_builder]
-
parent_builder.multipart = multipart
-
end
-
end
-
-
1
def self._to_partial_path
-
@_to_partial_path ||= name.demodulize.underscore.sub!(/_builder$/, '')
-
end
-
-
1
def to_partial_path
-
self.class._to_partial_path
-
end
-
-
1
def to_model
-
self
-
end
-
-
1
def initialize(object_name, object, template, options)
-
@nested_child_index = {}
-
@object_name, @object, @template, @options = object_name, object, template, options
-
@default_options = @options ? @options.slice(:index, :namespace) : {}
-
if @object_name.to_s.match(/\[\]$/)
-
if object ||= @template.instance_variable_get("@#{Regexp.last_match.pre_match}") and object.respond_to?(:to_param)
-
@auto_index = object.to_param
-
else
-
raise ArgumentError, "object[] naming but object param and @object var don't exist or don't respond to to_param: #{object.inspect}"
-
end
-
end
-
@multipart = nil
-
@index = options[:index] || options[:child_index]
-
end
-
-
1
(field_helpers - [:label, :check_box, :radio_button, :fields_for, :hidden_field, :file_field]).each do |selector|
-
17
class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
-
def #{selector}(method, options = {}) # def text_field(method, options = {})
-
@template.send( # @template.send(
-
#{selector.inspect}, # "text_field",
-
@object_name, # @object_name,
-
method, # method,
-
objectify_options(options)) # objectify_options(options))
-
end # end
-
RUBY_EVAL
-
end
-
-
# Creates a scope around a specific model object like form_for, but
-
# doesn't create the form tags themselves. This makes fields_for suitable
-
# for specifying additional model objects in the same form.
-
#
-
# Although the usage and purpose of +field_for+ is similar to +form_for+'s,
-
# its method signature is slightly different. Like +form_for+, it yields
-
# a FormBuilder object associated with a particular model object to a block,
-
# and within the block allows methods to be called on the builder to
-
# generate fields associated with the model object. Fields may reflect
-
# a model object in two ways - how they are named (hence how submitted
-
# values appear within the +params+ hash in the controller) and what
-
# default values are shown when the form the fields appear in is first
-
# displayed. In order for both of these features to be specified independently,
-
# both an object name (represented by either a symbol or string) and the
-
# object itself can be passed to the method separately -
-
#
-
# <%= form_for @person do |person_form| %>
-
# First name: <%= person_form.text_field :first_name %>
-
# Last name : <%= person_form.text_field :last_name %>
-
#
-
# <%= fields_for :permission, @person.permission do |permission_fields| %>
-
# Admin? : <%= permission_fields.check_box :admin %>
-
# <% end %>
-
#
-
# <%= person_form.submit %>
-
# <% end %>
-
#
-
# In this case, the checkbox field will be represented by an HTML +input+
-
# tag with the +name+ attribute <tt>permission[admin]</tt>, and the submitted
-
# value will appear in the controller as <tt>params[:permission][:admin]</tt>.
-
# If <tt>@person.permission</tt> is an existing record with an attribute
-
# +admin+, the initial state of the checkbox when first displayed will
-
# reflect the value of <tt>@person.permission.admin</tt>.
-
#
-
# Often this can be simplified by passing just the name of the model
-
# object to +fields_for+ -
-
#
-
# <%= fields_for :permission do |permission_fields| %>
-
# Admin?: <%= permission_fields.check_box :admin %>
-
# <% end %>
-
#
-
# ...in which case, if <tt>:permission</tt> also happens to be the name of an
-
# instance variable <tt>@permission</tt>, the initial state of the input
-
# field will reflect the value of that variable's attribute <tt>@permission.admin</tt>.
-
#
-
# Alternatively, you can pass just the model object itself (if the first
-
# argument isn't a string or symbol +fields_for+ will realize that the
-
# name has been omitted) -
-
#
-
# <%= fields_for @person.permission do |permission_fields| %>
-
# Admin?: <%= permission_fields.check_box :admin %>
-
# <% end %>
-
#
-
# and +fields_for+ will derive the required name of the field from the
-
# _class_ of the model object, e.g. if <tt>@person.permission</tt>, is
-
# of class +Permission+, the field will still be named <tt>permission[admin]</tt>.
-
#
-
# Note: This also works for the methods in FormOptionHelper and
-
# DateHelper that are designed to work with an object as base, like
-
# FormOptionHelper#collection_select and DateHelper#datetime_select.
-
#
-
# === Nested Attributes Examples
-
#
-
# When the object belonging to the current scope has a nested attribute
-
# writer for a certain attribute, fields_for will yield a new scope
-
# for that attribute. This allows you to create forms that set or change
-
# the attributes of a parent object and its associations in one go.
-
#
-
# Nested attribute writers are normal setter methods named after an
-
# association. The most common way of defining these writers is either
-
# with +accepts_nested_attributes_for+ in a model definition or by
-
# defining a method with the proper name. For example: the attribute
-
# writer for the association <tt>:address</tt> is called
-
# <tt>address_attributes=</tt>.
-
#
-
# Whether a one-to-one or one-to-many style form builder will be yielded
-
# depends on whether the normal reader method returns a _single_ object
-
# or an _array_ of objects.
-
#
-
# ==== One-to-one
-
#
-
# Consider a Person class which returns a _single_ Address from the
-
# <tt>address</tt> reader method and responds to the
-
# <tt>address_attributes=</tt> writer method:
-
#
-
# class Person
-
# def address
-
# @address
-
# end
-
#
-
# def address_attributes=(attributes)
-
# # Process the attributes hash
-
# end
-
# end
-
#
-
# This model can now be used with a nested fields_for, like so:
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :address do |address_fields| %>
-
# Street : <%= address_fields.text_field :street %>
-
# Zip code: <%= address_fields.text_field :zip_code %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# When address is already an association on a Person you can use
-
# +accepts_nested_attributes_for+ to define the writer method for you:
-
#
-
# class Person < ActiveRecord::Base
-
# has_one :address
-
# accepts_nested_attributes_for :address
-
# end
-
#
-
# If you want to destroy the associated model through the form, you have
-
# to enable it first using the <tt>:allow_destroy</tt> option for
-
# +accepts_nested_attributes_for+:
-
#
-
# class Person < ActiveRecord::Base
-
# has_one :address
-
# accepts_nested_attributes_for :address, allow_destroy: true
-
# end
-
#
-
# Now, when you use a form element with the <tt>_destroy</tt> parameter,
-
# with a value that evaluates to +true+, you will destroy the associated
-
# model (eg. 1, '1', true, or 'true'):
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :address do |address_fields| %>
-
# ...
-
# Delete: <%= address_fields.check_box :_destroy %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# ==== One-to-many
-
#
-
# Consider a Person class which returns an _array_ of Project instances
-
# from the <tt>projects</tt> reader method and responds to the
-
# <tt>projects_attributes=</tt> writer method:
-
#
-
# class Person
-
# def projects
-
# [@project1, @project2]
-
# end
-
#
-
# def projects_attributes=(attributes)
-
# # Process the attributes hash
-
# end
-
# end
-
#
-
# Note that the <tt>projects_attributes=</tt> writer method is in fact
-
# required for fields_for to correctly identify <tt>:projects</tt> as a
-
# collection, and the correct indices to be set in the form markup.
-
#
-
# When projects is already an association on Person you can use
-
# +accepts_nested_attributes_for+ to define the writer method for you:
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :projects
-
# accepts_nested_attributes_for :projects
-
# end
-
#
-
# This model can now be used with a nested fields_for. The block given to
-
# the nested fields_for call will be repeated for each instance in the
-
# collection:
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :projects do |project_fields| %>
-
# <% if project_fields.object.active? %>
-
# Name: <%= project_fields.text_field :name %>
-
# <% end %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# It's also possible to specify the instance to be used:
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <% @person.projects.each do |project| %>
-
# <% if project.active? %>
-
# <%= person_form.fields_for :projects, project do |project_fields| %>
-
# Name: <%= project_fields.text_field :name %>
-
# <% end %>
-
# <% end %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# Or a collection to be used:
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :projects, @active_projects do |project_fields| %>
-
# Name: <%= project_fields.text_field :name %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# If you want to destroy any of the associated models through the
-
# form, you have to enable it first using the <tt>:allow_destroy</tt>
-
# option for +accepts_nested_attributes_for+:
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :projects
-
# accepts_nested_attributes_for :projects, allow_destroy: true
-
# end
-
#
-
# This will allow you to specify which models to destroy in the
-
# attributes hash by adding a form element for the <tt>_destroy</tt>
-
# parameter with a value that evaluates to +true+
-
# (eg. 1, '1', true, or 'true'):
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :projects do |project_fields| %>
-
# Delete: <%= project_fields.check_box :_destroy %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# When a collection is used you might want to know the index of each
-
# object into the array. For this purpose, the <tt>index</tt> method
-
# is available in the FormBuilder object.
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :projects do |project_fields| %>
-
# Project #<%= project_fields.index %>
-
# ...
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# Note that fields_for will automatically generate a hidden field
-
# to store the ID of the record. There are circumstances where this
-
# hidden field is not needed and you can pass <tt>include_id: false</tt>
-
# to prevent fields_for from rendering it automatically.
-
1
def fields_for(record_name, record_object = nil, fields_options = {}, &block)
-
fields_options, record_object = record_object, nil if record_object.is_a?(Hash) && record_object.extractable_options?
-
fields_options[:builder] ||= options[:builder]
-
fields_options[:namespace] = options[:namespace]
-
fields_options[:parent_builder] = self
-
-
case record_name
-
when String, Symbol
-
if nested_attributes_association?(record_name)
-
return fields_for_with_nested_attributes(record_name, record_object, fields_options, block)
-
end
-
else
-
record_object = record_name.is_a?(Array) ? record_name.last : record_name
-
record_name = model_name_from_record_or_class(record_object).param_key
-
end
-
-
index = if options.has_key?(:index)
-
options[:index]
-
elsif defined?(@auto_index)
-
self.object_name = @object_name.to_s.sub(/\[\]$/,"")
-
@auto_index
-
end
-
-
record_name = index ? "#{object_name}[#{index}][#{record_name}]" : "#{object_name}[#{record_name}]"
-
fields_options[:child_index] = index
-
-
@template.fields_for(record_name, record_object, fields_options, &block)
-
end
-
-
# Returns a label tag tailored for labelling an input field for a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). The text of label will default to the attribute name unless a translation
-
# is found in the current I18n locale (through helpers.label.<modelname>.<attribute>) or you specify it explicitly.
-
# Additional options on the label tag can be passed as a hash with +options+. These options will be tagged
-
# onto the HTML as an HTML element attribute as in the example shown, except for the <tt>:value</tt> option, which is designed to
-
# target labels for radio_button tags (where the value is used in the ID of the input tag).
-
#
-
# ==== Examples
-
# label(:post, :title)
-
# # => <label for="post_title">Title</label>
-
#
-
# You can localize your labels based on model and attribute names.
-
# For example you can define the following in your locale (e.g. en.yml)
-
#
-
# helpers:
-
# label:
-
# post:
-
# body: "Write your entire text here"
-
#
-
# Which then will result in
-
#
-
# label(:post, :body)
-
# # => <label for="post_body">Write your entire text here</label>
-
#
-
# Localization can also be based purely on the translation of the attribute-name
-
# (if you are using ActiveRecord):
-
#
-
# activerecord:
-
# attributes:
-
# post:
-
# cost: "Total cost"
-
#
-
# label(:post, :cost)
-
# # => <label for="post_cost">Total cost</label>
-
#
-
# label(:post, :title, "A short title")
-
# # => <label for="post_title">A short title</label>
-
#
-
# label(:post, :title, "A short title", class: "title_label")
-
# # => <label for="post_title" class="title_label">A short title</label>
-
#
-
# label(:post, :privacy, "Public Post", value: "public")
-
# # => <label for="post_privacy_public">Public Post</label>
-
#
-
# label(:post, :terms) do
-
# 'Accept <a href="/terms">Terms</a>.'.html_safe
-
# end
-
1
def label(method, text = nil, options = {}, &block)
-
@template.label(@object_name, method, text, objectify_options(options), &block)
-
end
-
-
# Returns a checkbox tag tailored for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). This object must be an instance object (@object) and not a local object.
-
# It's intended that +method+ returns an integer and if that integer is above zero, then the checkbox is checked.
-
# Additional options on the input tag can be passed as a hash with +options+. The +checked_value+ defaults to 1
-
# while the default +unchecked_value+ is set to 0 which is convenient for boolean values.
-
#
-
# ==== Gotcha
-
#
-
# The HTML specification says unchecked check boxes are not successful, and
-
# thus web browsers do not send them. Unfortunately this introduces a gotcha:
-
# if an +Invoice+ model has a +paid+ flag, and in the form that edits a paid
-
# invoice the user unchecks its check box, no +paid+ parameter is sent. So,
-
# any mass-assignment idiom like
-
#
-
# @invoice.update(params[:invoice])
-
#
-
# wouldn't update the flag.
-
#
-
# To prevent this the helper generates an auxiliary hidden field before
-
# the very check box. The hidden field has the same name and its
-
# attributes mimic an unchecked check box.
-
#
-
# This way, the client either sends only the hidden field (representing
-
# the check box is unchecked), or both fields. Since the HTML specification
-
# says key/value pairs have to be sent in the same order they appear in the
-
# form, and parameters extraction gets the last occurrence of any repeated
-
# key in the query string, that works for ordinary forms.
-
#
-
# Unfortunately that workaround does not work when the check box goes
-
# within an array-like parameter, as in
-
#
-
# <%= fields_for "project[invoice_attributes][]", invoice, index: nil do |form| %>
-
# <%= form.check_box :paid %>
-
# ...
-
# <% end %>
-
#
-
# because parameter name repetition is precisely what Rails seeks to distinguish
-
# the elements of the array. For each item with a checked check box you
-
# get an extra ghost item with only that attribute, assigned to "0".
-
#
-
# In that case it is preferable to either use +check_box_tag+ or to use
-
# hashes instead of arrays.
-
#
-
# # Let's say that @post.validated? is 1:
-
# check_box("post", "validated")
-
# # => <input name="post[validated]" type="hidden" value="0" />
-
# # <input checked="checked" type="checkbox" id="post_validated" name="post[validated]" value="1" />
-
#
-
# # Let's say that @puppy.gooddog is "no":
-
# check_box("puppy", "gooddog", {}, "yes", "no")
-
# # => <input name="puppy[gooddog]" type="hidden" value="no" />
-
# # <input type="checkbox" id="puppy_gooddog" name="puppy[gooddog]" value="yes" />
-
#
-
# check_box("eula", "accepted", { class: 'eula_check' }, "yes", "no")
-
# # => <input name="eula[accepted]" type="hidden" value="no" />
-
# # <input type="checkbox" class="eula_check" id="eula_accepted" name="eula[accepted]" value="yes" />
-
1
def check_box(method, options = {}, checked_value = "1", unchecked_value = "0")
-
@template.check_box(@object_name, method, objectify_options(options), checked_value, unchecked_value)
-
end
-
-
# Returns a radio button tag for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). If the current value of +method+ is +tag_value+ the
-
# radio button will be checked.
-
#
-
# To force the radio button to be checked pass <tt>checked: true</tt> in the
-
# +options+ hash. You may pass HTML options there as well.
-
#
-
# # Let's say that @post.category returns "rails":
-
# radio_button("post", "category", "rails")
-
# radio_button("post", "category", "java")
-
# # => <input type="radio" id="post_category_rails" name="post[category]" value="rails" checked="checked" />
-
# # <input type="radio" id="post_category_java" name="post[category]" value="java" />
-
#
-
# radio_button("user", "receive_newsletter", "yes")
-
# radio_button("user", "receive_newsletter", "no")
-
# # => <input type="radio" id="user_receive_newsletter_yes" name="user[receive_newsletter]" value="yes" />
-
# # <input type="radio" id="user_receive_newsletter_no" name="user[receive_newsletter]" value="no" checked="checked" />
-
1
def radio_button(method, tag_value, options = {})
-
@template.radio_button(@object_name, method, tag_value, objectify_options(options))
-
end
-
-
# Returns a hidden input tag tailored for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
-
# hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
-
# shown.
-
#
-
# ==== Examples
-
# hidden_field(:signup, :pass_confirm)
-
# # => <input type="hidden" id="signup_pass_confirm" name="signup[pass_confirm]" value="#{@signup.pass_confirm}" />
-
#
-
# hidden_field(:post, :tag_list)
-
# # => <input type="hidden" id="post_tag_list" name="post[tag_list]" value="#{@post.tag_list}" />
-
#
-
# hidden_field(:user, :token)
-
# # => <input type="hidden" id="user_token" name="user[token]" value="#{@user.token}" />
-
#
-
1
def hidden_field(method, options = {})
-
@emitted_hidden_id = true if method == :id
-
@template.hidden_field(@object_name, method, objectify_options(options))
-
end
-
-
# Returns a file upload input tag tailored for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
-
# hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
-
# shown.
-
#
-
# Using this method inside a +form_for+ block will set the enclosing form's encoding to <tt>multipart/form-data</tt>.
-
#
-
# ==== Options
-
# * Creates standard HTML attributes for the tag.
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * <tt>:multiple</tt> - If set to true, *in most updated browsers* the user will be allowed to select multiple files.
-
# * <tt>:accept</tt> - If set to one or multiple mime-types, the user will be suggested a filter when choosing a file. You still need to set up model validations.
-
#
-
# ==== Examples
-
# file_field(:user, :avatar)
-
# # => <input type="file" id="user_avatar" name="user[avatar]" />
-
#
-
# file_field(:post, :image, :multiple => true)
-
# # => <input type="file" id="post_image" name="post[image]" multiple="true" />
-
#
-
# file_field(:post, :attached, accept: 'text/html')
-
# # => <input accept="text/html" type="file" id="post_attached" name="post[attached]" />
-
#
-
# file_field(:post, :image, accept: 'image/png,image/gif,image/jpeg')
-
# # => <input type="file" id="post_image" name="post[image]" accept="image/png,image/gif,image/jpeg" />
-
#
-
# file_field(:attachment, :file, class: 'file_input')
-
# # => <input type="file" id="attachment_file" name="attachment[file]" class="file_input" />
-
1
def file_field(method, options = {})
-
self.multipart = true
-
@template.file_field(@object_name, method, objectify_options(options))
-
end
-
-
# Add the submit button for the given form. When no value is given, it checks
-
# if the object is a new resource or not to create the proper label:
-
#
-
# <%= form_for @post do |f| %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# In the example above, if @post is a new record, it will use "Create Post" as
-
# submit button label, otherwise, it uses "Update Post".
-
#
-
# Those labels can be customized using I18n, under the helpers.submit key and accept
-
# the %{model} as translation interpolation:
-
#
-
# en:
-
# helpers:
-
# submit:
-
# create: "Create a %{model}"
-
# update: "Confirm changes to %{model}"
-
#
-
# It also searches for a key specific for the given object:
-
#
-
# en:
-
# helpers:
-
# submit:
-
# post:
-
# create: "Add %{model}"
-
#
-
1
def submit(value=nil, options={})
-
value, options = nil, value if value.is_a?(Hash)
-
value ||= submit_default_value
-
@template.submit_tag(value, options)
-
end
-
-
# Add the submit button for the given form. When no value is given, it checks
-
# if the object is a new resource or not to create the proper label:
-
#
-
# <%= form_for @post do |f| %>
-
# <%= f.button %>
-
# <% end %>
-
#
-
# In the example above, if @post is a new record, it will use "Create Post" as
-
# button label, otherwise, it uses "Update Post".
-
#
-
# Those labels can be customized using I18n, under the helpers.submit key
-
# (the same as submit helper) and accept the %{model} as translation interpolation:
-
#
-
# en:
-
# helpers:
-
# submit:
-
# create: "Create a %{model}"
-
# update: "Confirm changes to %{model}"
-
#
-
# It also searches for a key specific for the given object:
-
#
-
# en:
-
# helpers:
-
# submit:
-
# post:
-
# create: "Add %{model}"
-
#
-
# ==== Examples
-
# button("Create a post")
-
# # => <button name='button' type='submit'>Create post</button>
-
#
-
# button do
-
# content_tag(:strong, 'Ask me!')
-
# end
-
# # => <button name='button' type='submit'>
-
# # <strong>Ask me!</strong>
-
# # </button>
-
#
-
1
def button(value = nil, options = {}, &block)
-
value, options = nil, value if value.is_a?(Hash)
-
value ||= submit_default_value
-
@template.button_tag(value, options, &block)
-
end
-
-
1
def emitted_hidden_id?
-
@emitted_hidden_id ||= nil
-
end
-
-
1
private
-
1
def objectify_options(options)
-
@default_options.merge(options.merge(object: @object))
-
end
-
-
1
def submit_default_value
-
object = convert_to_model(@object)
-
key = object ? (object.persisted? ? :update : :create) : :submit
-
-
model = if object.class.respond_to?(:model_name)
-
object.class.model_name.human
-
else
-
@object_name.to_s.humanize
-
end
-
-
defaults = []
-
defaults << :"helpers.submit.#{object_name}.#{key}"
-
defaults << :"helpers.submit.#{key}"
-
defaults << "#{key.to_s.humanize} #{model}"
-
-
I18n.t(defaults.shift, model: model, default: defaults)
-
end
-
-
1
def nested_attributes_association?(association_name)
-
@object.respond_to?("#{association_name}_attributes=")
-
end
-
-
1
def fields_for_with_nested_attributes(association_name, association, options, block)
-
name = "#{object_name}[#{association_name}_attributes]"
-
association = convert_to_model(association)
-
-
if association.respond_to?(:persisted?)
-
association = [association] if @object.send(association_name).respond_to?(:to_ary)
-
elsif !association.respond_to?(:to_ary)
-
association = @object.send(association_name)
-
end
-
-
if association.respond_to?(:to_ary)
-
explicit_child_index = options[:child_index]
-
output = ActiveSupport::SafeBuffer.new
-
association.each do |child|
-
options[:child_index] = nested_child_index(name) unless explicit_child_index
-
output << fields_for_nested_model("#{name}[#{options[:child_index]}]", child, options, block)
-
end
-
output
-
elsif association
-
fields_for_nested_model(name, association, options, block)
-
end
-
end
-
-
1
def fields_for_nested_model(name, object, fields_options, block)
-
object = convert_to_model(object)
-
emit_hidden_id = object.persisted? && fields_options.fetch(:include_id) {
-
options.fetch(:include_id, true)
-
}
-
-
@template.fields_for(name, object, fields_options) do |f|
-
output = @template.capture(f, &block)
-
output.concat f.hidden_field(:id) if output && emit_hidden_id && !f.emitted_hidden_id?
-
output
-
end
-
end
-
-
1
def nested_child_index(name)
-
@nested_child_index[name] ||= -1
-
@nested_child_index[name] += 1
-
end
-
end
-
end
-
-
1
ActiveSupport.on_load(:action_view) do
-
3
cattr_accessor(:default_form_builder) { ::ActionView::Helpers::FormBuilder }
-
end
-
end
-
1
require 'cgi'
-
1
require 'erb'
-
1
require 'action_view/helpers/form_helper'
-
1
require 'active_support/core_ext/string/output_safety'
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'active_support/core_ext/array/wrap'
-
-
1
module ActionView
-
# = Action View Form Option Helpers
-
1
module Helpers
-
# Provides a number of methods for turning different kinds of containers into a set of option tags.
-
#
-
# The <tt>collection_select</tt>, <tt>select</tt> and <tt>time_zone_select</tt> methods take an <tt>options</tt> parameter, a hash:
-
#
-
# * <tt>:include_blank</tt> - set to true or a prompt string if the first option element of the select element is a blank. Useful if there is not a default value required for the select element.
-
#
-
# select("post", "category", Post::CATEGORIES, {include_blank: true})
-
#
-
# could become:
-
#
-
# <select name="post[category]">
-
# <option></option>
-
# <option>joke</option>
-
# <option>poem</option>
-
# </select>
-
#
-
# Another common case is a select tag for a <tt>belongs_to</tt>-associated object.
-
#
-
# Example with @post.person_id => 2:
-
#
-
# select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {include_blank: 'None'})
-
#
-
# could become:
-
#
-
# <select name="post[person_id]">
-
# <option value="">None</option>
-
# <option value="1">David</option>
-
# <option value="2" selected="selected">Sam</option>
-
# <option value="3">Tobias</option>
-
# </select>
-
#
-
# * <tt>:prompt</tt> - set to true or a prompt string. When the select element doesn't have a value yet, this prepends an option with a generic prompt -- "Please select" -- or the given prompt string.
-
#
-
# select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {prompt: 'Select Person'})
-
#
-
# could become:
-
#
-
# <select name="post[person_id]">
-
# <option value="">Select Person</option>
-
# <option value="1">David</option>
-
# <option value="2">Sam</option>
-
# <option value="3">Tobias</option>
-
# </select>
-
#
-
# Like the other form helpers, +select+ can accept an <tt>:index</tt> option to manually set the ID used in the resulting output. Unlike other helpers, +select+ expects this
-
# option to be in the +html_options+ parameter.
-
#
-
# select("album[]", "genre", %w[rap rock country], {}, { index: nil })
-
#
-
# becomes:
-
#
-
# <select name="album[][genre]" id="album__genre">
-
# <option value="rap">rap</option>
-
# <option value="rock">rock</option>
-
# <option value="country">country</option>
-
# </select>
-
#
-
# * <tt>:disabled</tt> - can be a single value or an array of values that will be disabled options in the final output.
-
#
-
# select("post", "category", Post::CATEGORIES, {disabled: 'restricted'})
-
#
-
# could become:
-
#
-
# <select name="post[category]">
-
# <option></option>
-
# <option>joke</option>
-
# <option>poem</option>
-
# <option disabled="disabled">restricted</option>
-
# </select>
-
#
-
# When used with the <tt>collection_select</tt> helper, <tt>:disabled</tt> can also be a Proc that identifies those options that should be disabled.
-
#
-
# collection_select(:post, :category_id, Category.all, :id, :name, {disabled: lambda{|category| category.archived? }})
-
#
-
# If the categories "2008 stuff" and "Christmas" return true when the method <tt>archived?</tt> is called, this would return:
-
# <select name="post[category_id]">
-
# <option value="1" disabled="disabled">2008 stuff</option>
-
# <option value="2" disabled="disabled">Christmas</option>
-
# <option value="3">Jokes</option>
-
# <option value="4">Poems</option>
-
# </select>
-
#
-
1
module FormOptionsHelper
-
# ERB::Util can mask some helpers like textilize. Make sure to include them.
-
1
include TextHelper
-
-
# Create a select tag and a series of contained option tags for the provided object and method.
-
# The option currently held by the object will be selected, provided that the object is available.
-
#
-
# There are two possible formats for the +choices+ parameter, corresponding to other helpers' output:
-
#
-
# * A flat collection (see +options_for_select+).
-
#
-
# * A nested collection (see +grouped_options_for_select+).
-
#
-
# For example:
-
#
-
# select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, { include_blank: true })
-
#
-
# would become:
-
#
-
# <select name="post[person_id]">
-
# <option value=""></option>
-
# <option value="1" selected="selected">David</option>
-
# <option value="2">Sam</option>
-
# <option value="3">Tobias</option>
-
# </select>
-
#
-
# assuming the associated person has ID 1.
-
#
-
# This can be used to provide a default set of options in the standard way: before rendering the create form, a
-
# new model instance is assigned the default options and bound to @model_name. Usually this model is not saved
-
# to the database. Instead, a second model object is created when the create request is received.
-
# This allows the user to submit a form page more than once with the expected results of creating multiple records.
-
# In addition, this allows a single partial to be used to generate form inputs for both edit and create forms.
-
#
-
# By default, <tt>post.person_id</tt> is the selected option. Specify <tt>selected: value</tt> to use a different selection
-
# or <tt>selected: nil</tt> to leave all options unselected. Similarly, you can specify values to be disabled in the option
-
# tags by specifying the <tt>:disabled</tt> option. This can either be a single value or an array of values to be disabled.
-
#
-
# A block can be passed to +select+ to customize how the options tags will be rendered. This
-
# is useful when the options tag has complex attributes.
-
#
-
# select(report, "campaign_ids") do
-
# available_campaigns.each do |c|
-
# content_tag(:option, c.name, value: c.id, data: { tags: c.tags.to_json })
-
# end
-
# end
-
#
-
# ==== Gotcha
-
#
-
# The HTML specification says when +multiple+ parameter passed to select and all options got deselected
-
# web browsers do not send any value to server. Unfortunately this introduces a gotcha:
-
# if an +User+ model has many +roles+ and have +role_ids+ accessor, and in the form that edits roles of the user
-
# the user deselects all roles from +role_ids+ multiple select box, no +role_ids+ parameter is sent. So,
-
# any mass-assignment idiom like
-
#
-
# @user.update(params[:user])
-
#
-
# wouldn't update roles.
-
#
-
# To prevent this the helper generates an auxiliary hidden field before
-
# every multiple select. The hidden field has the same name as multiple select and blank value.
-
#
-
# This way, the client either sends only the hidden field (representing
-
# the deselected multiple select box), or both fields. Since the HTML specification
-
# says key/value pairs have to be sent in the same order they appear in the
-
# form, and parameters extraction gets the last occurrence of any repeated
-
# key in the query string, that works for ordinary forms.
-
#
-
# In case if you don't want the helper to generate this hidden field you can specify
-
# <tt>include_hidden: false</tt> option.
-
#
-
1
def select(object, method, choices = nil, options = {}, html_options = {}, &block)
-
Tags::Select.new(object, method, self, choices, options, html_options, &block).render
-
end
-
-
# Returns <tt><select></tt> and <tt><option></tt> tags for the collection of existing return values of
-
# +method+ for +object+'s class. The value returned from calling +method+ on the instance +object+ will
-
# be selected. If calling +method+ returns +nil+, no selection is made without including <tt>:prompt</tt>
-
# or <tt>:include_blank</tt> in the +options+ hash.
-
#
-
# The <tt>:value_method</tt> and <tt>:text_method</tt> parameters are methods to be called on each member
-
# of +collection+. The return values are used as the +value+ attribute and contents of each
-
# <tt><option></tt> tag, respectively. They can also be any object that responds to +call+, such
-
# as a +proc+, that will be called for each member of the +collection+ to
-
# retrieve the value/text.
-
#
-
# Example object structure for use with this method:
-
#
-
# class Post < ActiveRecord::Base
-
# belongs_to :author
-
# end
-
#
-
# class Author < ActiveRecord::Base
-
# has_many :posts
-
# def name_with_initial
-
# "#{first_name.first}. #{last_name}"
-
# end
-
# end
-
#
-
# Sample usage (selecting the associated Author for an instance of Post, <tt>@post</tt>):
-
#
-
# collection_select(:post, :author_id, Author.all, :id, :name_with_initial, prompt: true)
-
#
-
# If <tt>@post.author_id</tt> is already <tt>1</tt>, this would return:
-
# <select name="post[author_id]">
-
# <option value="">Please select</option>
-
# <option value="1" selected="selected">D. Heinemeier Hansson</option>
-
# <option value="2">D. Thomas</option>
-
# <option value="3">M. Clark</option>
-
# </select>
-
1
def collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
-
Tags::CollectionSelect.new(object, method, self, collection, value_method, text_method, options, html_options).render
-
end
-
-
# Returns <tt><select></tt>, <tt><optgroup></tt> and <tt><option></tt> tags for the collection of existing return values of
-
# +method+ for +object+'s class. The value returned from calling +method+ on the instance +object+ will
-
# be selected. If calling +method+ returns +nil+, no selection is made without including <tt>:prompt</tt>
-
# or <tt>:include_blank</tt> in the +options+ hash.
-
#
-
# Parameters:
-
# * +object+ - The instance of the class to be used for the select tag
-
# * +method+ - The attribute of +object+ corresponding to the select tag
-
# * +collection+ - An array of objects representing the <tt><optgroup></tt> tags.
-
# * +group_method+ - The name of a method which, when called on a member of +collection+, returns an
-
# array of child objects representing the <tt><option></tt> tags.
-
# * +group_label_method+ - The name of a method which, when called on a member of +collection+, returns a
-
# string to be used as the +label+ attribute for its <tt><optgroup></tt> tag.
-
# * +option_key_method+ - The name of a method which, when called on a child object of a member of
-
# +collection+, returns a value to be used as the +value+ attribute for its <tt><option></tt> tag.
-
# * +option_value_method+ - The name of a method which, when called on a child object of a member of
-
# +collection+, returns a value to be used as the contents of its <tt><option></tt> tag.
-
#
-
# Example object structure for use with this method:
-
#
-
# class Continent < ActiveRecord::Base
-
# has_many :countries
-
# # attribs: id, name
-
# end
-
#
-
# class Country < ActiveRecord::Base
-
# belongs_to :continent
-
# # attribs: id, name, continent_id
-
# end
-
#
-
# class City < ActiveRecord::Base
-
# belongs_to :country
-
# # attribs: id, name, country_id
-
# end
-
#
-
# Sample usage:
-
#
-
# grouped_collection_select(:city, :country_id, @continents, :countries, :name, :id, :name)
-
#
-
# Possible output:
-
#
-
# <select name="city[country_id]">
-
# <optgroup label="Africa">
-
# <option value="1">South Africa</option>
-
# <option value="3">Somalia</option>
-
# </optgroup>
-
# <optgroup label="Europe">
-
# <option value="7" selected="selected">Denmark</option>
-
# <option value="2">Ireland</option>
-
# </optgroup>
-
# </select>
-
#
-
1
def grouped_collection_select(object, method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {})
-
Tags::GroupedCollectionSelect.new(object, method, self, collection, group_method, group_label_method, option_key_method, option_value_method, options, html_options).render
-
end
-
-
# Returns select and option tags for the given object and method, using
-
# #time_zone_options_for_select to generate the list of option tags.
-
#
-
# In addition to the <tt>:include_blank</tt> option documented above,
-
# this method also supports a <tt>:model</tt> option, which defaults
-
# to ActiveSupport::TimeZone. This may be used by users to specify a
-
# different time zone model object. (See +time_zone_options_for_select+
-
# for more information.)
-
#
-
# You can also supply an array of ActiveSupport::TimeZone objects
-
# as +priority_zones+, so that they will be listed above the rest of the
-
# (long) list. (You can use ActiveSupport::TimeZone.us_zones as a convenience
-
# for obtaining a list of the US time zones, or a Regexp to select the zones
-
# of your choice)
-
#
-
# Finally, this method supports a <tt>:default</tt> option, which selects
-
# a default ActiveSupport::TimeZone if the object's time zone is +nil+.
-
#
-
# time_zone_select( "user", "time_zone", nil, include_blank: true)
-
#
-
# time_zone_select( "user", "time_zone", nil, default: "Pacific Time (US & Canada)" )
-
#
-
# time_zone_select( "user", 'time_zone', ActiveSupport::TimeZone.us_zones, default: "Pacific Time (US & Canada)")
-
#
-
# time_zone_select( "user", 'time_zone', [ ActiveSupport::TimeZone['Alaska'], ActiveSupport::TimeZone['Hawaii'] ])
-
#
-
# time_zone_select( "user", 'time_zone', /Australia/)
-
#
-
# time_zone_select( "user", "time_zone", ActiveSupport::TimeZone.all.sort, model: ActiveSupport::TimeZone)
-
1
def time_zone_select(object, method, priority_zones = nil, options = {}, html_options = {})
-
Tags::TimeZoneSelect.new(object, method, self, priority_zones, options, html_options).render
-
end
-
-
# Accepts a container (hash, array, enumerable, your type) and returns a string of option tags. Given a container
-
# where the elements respond to first and last (such as a two-element array), the "lasts" serve as option values and
-
# the "firsts" as option text. Hashes are turned into this form automatically, so the keys become "firsts" and values
-
# become lasts. If +selected+ is specified, the matching "last" or element will get the selected option-tag. +selected+
-
# may also be an array of values to be selected when using a multiple select.
-
#
-
# options_for_select([["Dollar", "$"], ["Kroner", "DKK"]])
-
# # => <option value="$">Dollar</option>
-
# # => <option value="DKK">Kroner</option>
-
#
-
# options_for_select([ "VISA", "MasterCard" ], "MasterCard")
-
# # => <option>VISA</option>
-
# # => <option selected="selected">MasterCard</option>
-
#
-
# options_for_select({ "Basic" => "$20", "Plus" => "$40" }, "$40")
-
# # => <option value="$20">Basic</option>
-
# # => <option value="$40" selected="selected">Plus</option>
-
#
-
# options_for_select([ "VISA", "MasterCard", "Discover" ], ["VISA", "Discover"])
-
# # => <option selected="selected">VISA</option>
-
# # => <option>MasterCard</option>
-
# # => <option selected="selected">Discover</option>
-
#
-
# You can optionally provide html attributes as the last element of the array.
-
#
-
# options_for_select([ "Denmark", ["USA", {class: 'bold'}], "Sweden" ], ["USA", "Sweden"])
-
# # => <option value="Denmark">Denmark</option>
-
# # => <option value="USA" class="bold" selected="selected">USA</option>
-
# # => <option value="Sweden" selected="selected">Sweden</option>
-
#
-
# options_for_select([["Dollar", "$", {class: "bold"}], ["Kroner", "DKK", {onclick: "alert('HI');"}]])
-
# # => <option value="$" class="bold">Dollar</option>
-
# # => <option value="DKK" onclick="alert('HI');">Kroner</option>
-
#
-
# If you wish to specify disabled option tags, set +selected+ to be a hash, with <tt>:disabled</tt> being either a value
-
# or array of values to be disabled. In this case, you can use <tt>:selected</tt> to specify selected option tags.
-
#
-
# options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], disabled: "Super Platinum")
-
# # => <option value="Free">Free</option>
-
# # => <option value="Basic">Basic</option>
-
# # => <option value="Advanced">Advanced</option>
-
# # => <option value="Super Platinum" disabled="disabled">Super Platinum</option>
-
#
-
# options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], disabled: ["Advanced", "Super Platinum"])
-
# # => <option value="Free">Free</option>
-
# # => <option value="Basic">Basic</option>
-
# # => <option value="Advanced" disabled="disabled">Advanced</option>
-
# # => <option value="Super Platinum" disabled="disabled">Super Platinum</option>
-
#
-
# options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], selected: "Free", disabled: "Super Platinum")
-
# # => <option value="Free" selected="selected">Free</option>
-
# # => <option value="Basic">Basic</option>
-
# # => <option value="Advanced">Advanced</option>
-
# # => <option value="Super Platinum" disabled="disabled">Super Platinum</option>
-
#
-
# NOTE: Only the option tags are returned, you have to wrap this call in a regular HTML select tag.
-
1
def options_for_select(container, selected = nil)
-
return container if String === container
-
-
selected, disabled = extract_selected_and_disabled(selected).map do |r|
-
Array(r).map { |item| item.to_s }
-
end
-
-
container.map do |element|
-
html_attributes = option_html_attributes(element)
-
text, value = option_text_and_value(element).map { |item| item.to_s }
-
-
html_attributes[:selected] = option_value_selected?(value, selected)
-
html_attributes[:disabled] = disabled && option_value_selected?(value, disabled)
-
html_attributes[:value] = value
-
-
content_tag_string(:option, text, html_attributes)
-
end.join("\n").html_safe
-
end
-
-
# Returns a string of option tags that have been compiled by iterating over the +collection+ and assigning
-
# the result of a call to the +value_method+ as the option value and the +text_method+ as the option text.
-
#
-
# options_from_collection_for_select(@people, 'id', 'name')
-
# # => <option value="#{person.id}">#{person.name}</option>
-
#
-
# This is more often than not used inside a #select_tag like this example:
-
#
-
# select_tag 'person', options_from_collection_for_select(@people, 'id', 'name')
-
#
-
# If +selected+ is specified as a value or array of values, the element(s) returning a match on +value_method+
-
# will be selected option tag(s).
-
#
-
# If +selected+ is specified as a Proc, those members of the collection that return true for the anonymous
-
# function are the selected values.
-
#
-
# +selected+ can also be a hash, specifying both <tt>:selected</tt> and/or <tt>:disabled</tt> values as required.
-
#
-
# Be sure to specify the same class as the +value_method+ when specifying selected or disabled options.
-
# Failure to do this will produce undesired results. Example:
-
# options_from_collection_for_select(@people, 'id', 'name', '1')
-
# Will not select a person with the id of 1 because 1 (an Integer) is not the same as '1' (a string)
-
# options_from_collection_for_select(@people, 'id', 'name', 1)
-
# should produce the desired results.
-
1
def options_from_collection_for_select(collection, value_method, text_method, selected = nil)
-
options = collection.map do |element|
-
[value_for_collection(element, text_method), value_for_collection(element, value_method), option_html_attributes(element)]
-
end
-
selected, disabled = extract_selected_and_disabled(selected)
-
select_deselect = {
-
selected: extract_values_from_collection(collection, value_method, selected),
-
disabled: extract_values_from_collection(collection, value_method, disabled)
-
}
-
-
options_for_select(options, select_deselect)
-
end
-
-
# Returns a string of <tt><option></tt> tags, like <tt>options_from_collection_for_select</tt>, but
-
# groups them by <tt><optgroup></tt> tags based on the object relationships of the arguments.
-
#
-
# Parameters:
-
# * +collection+ - An array of objects representing the <tt><optgroup></tt> tags.
-
# * +group_method+ - The name of a method which, when called on a member of +collection+, returns an
-
# array of child objects representing the <tt><option></tt> tags.
-
# * group_label_method+ - The name of a method which, when called on a member of +collection+, returns a
-
# string to be used as the +label+ attribute for its <tt><optgroup></tt> tag.
-
# * +option_key_method+ - The name of a method which, when called on a child object of a member of
-
# +collection+, returns a value to be used as the +value+ attribute for its <tt><option></tt> tag.
-
# * +option_value_method+ - The name of a method which, when called on a child object of a member of
-
# +collection+, returns a value to be used as the contents of its <tt><option></tt> tag.
-
# * +selected_key+ - A value equal to the +value+ attribute for one of the <tt><option></tt> tags,
-
# which will have the +selected+ attribute set. Corresponds to the return value of one of the calls
-
# to +option_key_method+. If +nil+, no selection is made. Can also be a hash if disabled values are
-
# to be specified.
-
#
-
# Example object structure for use with this method:
-
#
-
# class Continent < ActiveRecord::Base
-
# has_many :countries
-
# # attribs: id, name
-
# end
-
#
-
# class Country < ActiveRecord::Base
-
# belongs_to :continent
-
# # attribs: id, name, continent_id
-
# end
-
#
-
# Sample usage:
-
# option_groups_from_collection_for_select(@continents, :countries, :name, :id, :name, 3)
-
#
-
# Possible output:
-
# <optgroup label="Africa">
-
# <option value="1">Egypt</option>
-
# <option value="4">Rwanda</option>
-
# ...
-
# </optgroup>
-
# <optgroup label="Asia">
-
# <option value="3" selected="selected">China</option>
-
# <option value="12">India</option>
-
# <option value="5">Japan</option>
-
# ...
-
# </optgroup>
-
#
-
# <b>Note:</b> Only the <tt><optgroup></tt> and <tt><option></tt> tags are returned, so you still have to
-
# wrap the output in an appropriate <tt><select></tt> tag.
-
1
def option_groups_from_collection_for_select(collection, group_method, group_label_method, option_key_method, option_value_method, selected_key = nil)
-
collection.map do |group|
-
option_tags = options_from_collection_for_select(
-
group.send(group_method), option_key_method, option_value_method, selected_key)
-
-
content_tag(:optgroup, option_tags, label: group.send(group_label_method))
-
end.join.html_safe
-
end
-
-
# Returns a string of <tt><option></tt> tags, like <tt>options_for_select</tt>, but
-
# wraps them with <tt><optgroup></tt> tags.
-
#
-
# Parameters:
-
# * +grouped_options+ - Accepts a nested array or hash of strings. The first value serves as the
-
# <tt><optgroup></tt> label while the second value must be an array of options. The second value can be a
-
# nested array of text-value pairs. See <tt>options_for_select</tt> for more info.
-
# Ex. ["North America",[["United States","US"],["Canada","CA"]]]
-
# * +selected_key+ - A value equal to the +value+ attribute for one of the <tt><option></tt> tags,
-
# which will have the +selected+ attribute set. Note: It is possible for this value to match multiple options
-
# as you might have the same option in multiple groups. Each will then get <tt>selected="selected"</tt>.
-
#
-
# Options:
-
# * <tt>:prompt</tt> - set to true or a prompt string. When the select element doesn't have a value yet, this
-
# prepends an option with a generic prompt - "Please select" - or the given prompt string.
-
# * <tt>:divider</tt> - the divider for the options groups.
-
#
-
# grouped_options = [
-
# ['North America',
-
# [['United States','US'],'Canada']],
-
# ['Europe',
-
# ['Denmark','Germany','France']]
-
# ]
-
# grouped_options_for_select(grouped_options)
-
#
-
# grouped_options = {
-
# 'North America' => [['United States','US'], 'Canada'],
-
# 'Europe' => ['Denmark','Germany','France']
-
# }
-
# grouped_options_for_select(grouped_options)
-
#
-
# Possible output:
-
# <optgroup label="North America">
-
# <option value="US">United States</option>
-
# <option value="Canada">Canada</option>
-
# </optgroup>
-
# <optgroup label="Europe">
-
# <option value="Denmark">Denmark</option>
-
# <option value="Germany">Germany</option>
-
# <option value="France">France</option>
-
# </optgroup>
-
#
-
# grouped_options = [
-
# [['United States','US'], 'Canada'],
-
# ['Denmark','Germany','France']
-
# ]
-
# grouped_options_for_select(grouped_options, nil, divider: '---------')
-
#
-
# Possible output:
-
# <optgroup label="---------">
-
# <option value="US">United States</option>
-
# <option value="Canada">Canada</option>
-
# </optgroup>
-
# <optgroup label="---------">
-
# <option value="Denmark">Denmark</option>
-
# <option value="Germany">Germany</option>
-
# <option value="France">France</option>
-
# </optgroup>
-
#
-
# <b>Note:</b> Only the <tt><optgroup></tt> and <tt><option></tt> tags are returned, so you still have to
-
# wrap the output in an appropriate <tt><select></tt> tag.
-
1
def grouped_options_for_select(grouped_options, selected_key = nil, options = {})
-
prompt = options[:prompt]
-
divider = options[:divider]
-
-
body = "".html_safe
-
-
if prompt
-
body.safe_concat content_tag(:option, prompt_text(prompt), value: "")
-
end
-
-
grouped_options.each do |container|
-
html_attributes = option_html_attributes(container)
-
-
if divider
-
label = divider
-
else
-
label, container = container
-
end
-
-
html_attributes = { label: label }.merge!(html_attributes)
-
body.safe_concat content_tag(:optgroup, options_for_select(container, selected_key), html_attributes)
-
end
-
-
body
-
end
-
-
# Returns a string of option tags for pretty much any time zone in the
-
# world. Supply a ActiveSupport::TimeZone name as +selected+ to have it
-
# marked as the selected option tag. You can also supply an array of
-
# ActiveSupport::TimeZone objects as +priority_zones+, so that they will
-
# be listed above the rest of the (long) list. (You can use
-
# ActiveSupport::TimeZone.us_zones as a convenience for obtaining a list
-
# of the US time zones, or a Regexp to select the zones of your choice)
-
#
-
# The +selected+ parameter must be either +nil+, or a string that names
-
# a ActiveSupport::TimeZone.
-
#
-
# By default, +model+ is the ActiveSupport::TimeZone constant (which can
-
# be obtained in Active Record as a value object). The only requirement
-
# is that the +model+ parameter be an object that responds to +all+, and
-
# returns an array of objects that represent time zones.
-
#
-
# NOTE: Only the option tags are returned, you have to wrap this call in
-
# a regular HTML select tag.
-
1
def time_zone_options_for_select(selected = nil, priority_zones = nil, model = ::ActiveSupport::TimeZone)
-
zone_options = "".html_safe
-
-
zones = model.all
-
convert_zones = lambda { |list| list.map { |z| [ z.to_s, z.name ] } }
-
-
if priority_zones
-
if priority_zones.is_a?(Regexp)
-
priority_zones = zones.select { |z| z =~ priority_zones }
-
end
-
-
zone_options.safe_concat options_for_select(convert_zones[priority_zones], selected)
-
zone_options.safe_concat content_tag(:option, '-------------', value: '', disabled: true)
-
zone_options.safe_concat "\n"
-
-
zones = zones - priority_zones
-
end
-
-
zone_options.safe_concat options_for_select(convert_zones[zones], selected)
-
end
-
-
# Returns radio button tags for the collection of existing return values
-
# of +method+ for +object+'s class. The value returned from calling
-
# +method+ on the instance +object+ will be selected. If calling +method+
-
# returns +nil+, no selection is made.
-
#
-
# The <tt>:value_method</tt> and <tt>:text_method</tt> parameters are
-
# methods to be called on each member of +collection+. The return values
-
# are used as the +value+ attribute and contents of each radio button tag,
-
# respectively. They can also be any object that responds to +call+, such
-
# as a +proc+, that will be called for each member of the +collection+ to
-
# retrieve the value/text.
-
#
-
# Example object structure for use with this method:
-
# class Post < ActiveRecord::Base
-
# belongs_to :author
-
# end
-
# class Author < ActiveRecord::Base
-
# has_many :posts
-
# def name_with_initial
-
# "#{first_name.first}. #{last_name}"
-
# end
-
# end
-
#
-
# Sample usage (selecting the associated Author for an instance of Post, <tt>@post</tt>):
-
# collection_radio_buttons(:post, :author_id, Author.all, :id, :name_with_initial)
-
#
-
# If <tt>@post.author_id</tt> is already <tt>1</tt>, this would return:
-
# <input id="post_author_id_1" name="post[author_id]" type="radio" value="1" checked="checked" />
-
# <label for="post_author_id_1">D. Heinemeier Hansson</label>
-
# <input id="post_author_id_2" name="post[author_id]" type="radio" value="2" />
-
# <label for="post_author_id_2">D. Thomas</label>
-
# <input id="post_author_id_3" name="post[author_id]" type="radio" value="3" />
-
# <label for="post_author_id_3">M. Clark</label>
-
#
-
# It is also possible to customize the way the elements will be shown by
-
# giving a block to the method:
-
# collection_radio_buttons(:post, :author_id, Author.all, :id, :name_with_initial) do |b|
-
# b.label { b.radio_button }
-
# end
-
#
-
# The argument passed to the block is a special kind of builder for this
-
# collection, which has the ability to generate the label and radio button
-
# for the current item in the collection, with proper text and value.
-
# Using it, you can change the label and radio button display order or
-
# even use the label as wrapper, as in the example above.
-
#
-
# The builder methods <tt>label</tt> and <tt>radio_button</tt> also accept
-
# extra html options:
-
# collection_radio_buttons(:post, :author_id, Author.all, :id, :name_with_initial) do |b|
-
# b.label(class: "radio_button") { b.radio_button(class: "radio_button") }
-
# end
-
#
-
# There are also three special methods available: <tt>object</tt>, <tt>text</tt> and
-
# <tt>value</tt>, which are the current item being rendered, its text and value methods,
-
# respectively. You can use them like this:
-
# collection_radio_buttons(:post, :author_id, Author.all, :id, :name_with_initial) do |b|
-
# b.label(:"data-value" => b.value) { b.radio_button + b.text }
-
# end
-
1
def collection_radio_buttons(object, method, collection, value_method, text_method, options = {}, html_options = {}, &block)
-
Tags::CollectionRadioButtons.new(object, method, self, collection, value_method, text_method, options, html_options).render(&block)
-
end
-
-
# Returns check box tags for the collection of existing return values of
-
# +method+ for +object+'s class. The value returned from calling +method+
-
# on the instance +object+ will be selected. If calling +method+ returns
-
# +nil+, no selection is made.
-
#
-
# The <tt>:value_method</tt> and <tt>:text_method</tt> parameters are
-
# methods to be called on each member of +collection+. The return values
-
# are used as the +value+ attribute and contents of each check box tag,
-
# respectively. They can also be any object that responds to +call+, such
-
# as a +proc+, that will be called for each member of the +collection+ to
-
# retrieve the value/text.
-
#
-
# Example object structure for use with this method:
-
# class Post < ActiveRecord::Base
-
# has_and_belongs_to_many :authors
-
# end
-
# class Author < ActiveRecord::Base
-
# has_and_belongs_to_many :posts
-
# def name_with_initial
-
# "#{first_name.first}. #{last_name}"
-
# end
-
# end
-
#
-
# Sample usage (selecting the associated Author for an instance of Post, <tt>@post</tt>):
-
# collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial)
-
#
-
# If <tt>@post.author_ids</tt> is already <tt>[1]</tt>, this would return:
-
# <input id="post_author_ids_1" name="post[author_ids][]" type="checkbox" value="1" checked="checked" />
-
# <label for="post_author_ids_1">D. Heinemeier Hansson</label>
-
# <input id="post_author_ids_2" name="post[author_ids][]" type="checkbox" value="2" />
-
# <label for="post_author_ids_2">D. Thomas</label>
-
# <input id="post_author_ids_3" name="post[author_ids][]" type="checkbox" value="3" />
-
# <label for="post_author_ids_3">M. Clark</label>
-
# <input name="post[author_ids][]" type="hidden" value="" />
-
#
-
# It is also possible to customize the way the elements will be shown by
-
# giving a block to the method:
-
# collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial) do |b|
-
# b.label { b.check_box }
-
# end
-
#
-
# The argument passed to the block is a special kind of builder for this
-
# collection, which has the ability to generate the label and check box
-
# for the current item in the collection, with proper text and value.
-
# Using it, you can change the label and check box display order or even
-
# use the label as wrapper, as in the example above.
-
#
-
# The builder methods <tt>label</tt> and <tt>check_box</tt> also accept
-
# extra html options:
-
# collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial) do |b|
-
# b.label(class: "check_box") { b.check_box(class: "check_box") }
-
# end
-
#
-
# There are also three special methods available: <tt>object</tt>, <tt>text</tt> and
-
# <tt>value</tt>, which are the current item being rendered, its text and value methods,
-
# respectively. You can use them like this:
-
# collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial) do |b|
-
# b.label(:"data-value" => b.value) { b.check_box + b.text }
-
# end
-
1
def collection_check_boxes(object, method, collection, value_method, text_method, options = {}, html_options = {}, &block)
-
Tags::CollectionCheckBoxes.new(object, method, self, collection, value_method, text_method, options, html_options).render(&block)
-
end
-
-
1
private
-
1
def option_html_attributes(element)
-
if Array === element
-
element.select { |e| Hash === e }.reduce({}, :merge!)
-
else
-
{}
-
end
-
end
-
-
1
def option_text_and_value(option)
-
# Options are [text, value] pairs or strings used for both.
-
if !option.is_a?(String) && option.respond_to?(:first) && option.respond_to?(:last)
-
option = option.reject { |e| Hash === e } if Array === option
-
[option.first, option.last]
-
else
-
[option, option]
-
end
-
end
-
-
1
def option_value_selected?(value, selected)
-
Array(selected).include? value
-
end
-
-
1
def extract_selected_and_disabled(selected)
-
if selected.is_a?(Proc)
-
[selected, nil]
-
else
-
selected = Array.wrap(selected)
-
options = selected.extract_options!.symbolize_keys
-
selected_items = options.fetch(:selected, selected)
-
[selected_items, options[:disabled]]
-
end
-
end
-
-
1
def extract_values_from_collection(collection, value_method, selected)
-
if selected.is_a?(Proc)
-
collection.map do |element|
-
element.send(value_method) if selected.call(element)
-
end.compact
-
else
-
selected
-
end
-
end
-
-
1
def value_for_collection(item, value)
-
value.respond_to?(:call) ? value.call(item) : item.send(value)
-
end
-
-
1
def prompt_text(prompt)
-
prompt.kind_of?(String) ? prompt : I18n.translate('helpers.select.prompt', default: 'Please select')
-
end
-
end
-
-
1
class FormBuilder
-
# Wraps ActionView::Helpers::FormOptionsHelper#select for form builders:
-
#
-
# <%= form_for @post do |f| %>
-
# <%= f.select :person_id, Person.all.collect { |p| [ p.name, p.id ] }, include_blank: true %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# Please refer to the documentation of the base helper for details.
-
1
def select(method, choices = nil, options = {}, html_options = {}, &block)
-
@template.select(@object_name, method, choices, objectify_options(options), @default_options.merge(html_options), &block)
-
end
-
-
# Wraps ActionView::Helpers::FormOptionsHelper#collection_select for form builders:
-
#
-
# <%= form_for @post do |f| %>
-
# <%= f.collection_select :person_id, Author.all, :id, :name_with_initial, prompt: true %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# Please refer to the documentation of the base helper for details.
-
1
def collection_select(method, collection, value_method, text_method, options = {}, html_options = {})
-
@template.collection_select(@object_name, method, collection, value_method, text_method, objectify_options(options), @default_options.merge(html_options))
-
end
-
-
# Wraps ActionView::Helpers::FormOptionsHelper#grouped_collection_select for form builders:
-
#
-
# <%= form_for @city do |f| %>
-
# <%= f.grouped_collection_select :country_id, @continents, :countries, :name, :id, :name %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# Please refer to the documentation of the base helper for details.
-
1
def grouped_collection_select(method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {})
-
@template.grouped_collection_select(@object_name, method, collection, group_method, group_label_method, option_key_method, option_value_method, objectify_options(options), @default_options.merge(html_options))
-
end
-
-
# Wraps ActionView::Helpers::FormOptionsHelper#time_zone_select for form builders:
-
#
-
# <%= form_for @user do |f| %>
-
# <%= f.time_zone_select :time_zone, nil, include_blank: true %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# Please refer to the documentation of the base helper for details.
-
1
def time_zone_select(method, priority_zones = nil, options = {}, html_options = {})
-
@template.time_zone_select(@object_name, method, priority_zones, objectify_options(options), @default_options.merge(html_options))
-
end
-
-
# Wraps ActionView::Helpers::FormOptionsHelper#collection_check_boxes for form builders:
-
#
-
# <%= form_for @post do |f| %>
-
# <%= f.collection_check_boxes :author_ids, Author.all, :id, :name_with_initial %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# Please refer to the documentation of the base helper for details.
-
1
def collection_check_boxes(method, collection, value_method, text_method, options = {}, html_options = {}, &block)
-
@template.collection_check_boxes(@object_name, method, collection, value_method, text_method, objectify_options(options), @default_options.merge(html_options), &block)
-
end
-
-
# Wraps ActionView::Helpers::FormOptionsHelper#collection_radio_buttons for form builders:
-
#
-
# <%= form_for @post do |f| %>
-
# <%= f.collection_radio_buttons :author_id, Author.all, :id, :name_with_initial %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# Please refer to the documentation of the base helper for details.
-
1
def collection_radio_buttons(method, collection, value_method, text_method, options = {}, html_options = {}, &block)
-
@template.collection_radio_buttons(@object_name, method, collection, value_method, text_method, objectify_options(options), @default_options.merge(html_options), &block)
-
end
-
end
-
end
-
end
-
1
require 'cgi'
-
1
require 'action_view/helpers/tag_helper'
-
1
require 'active_support/core_ext/string/output_safety'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
-
1
module ActionView
-
# = Action View Form Tag Helpers
-
1
module Helpers
-
# Provides a number of methods for creating form tags that don't rely on an Active Record object assigned to the template like
-
# FormHelper does. Instead, you provide the names and values manually.
-
#
-
# NOTE: The HTML options <tt>disabled</tt>, <tt>readonly</tt>, and <tt>multiple</tt> can all be treated as booleans. So specifying
-
# <tt>disabled: true</tt> will give <tt>disabled="disabled"</tt>.
-
1
module FormTagHelper
-
1
extend ActiveSupport::Concern
-
-
1
include UrlHelper
-
1
include TextHelper
-
-
1
mattr_accessor :embed_authenticity_token_in_remote_forms
-
1
self.embed_authenticity_token_in_remote_forms = false
-
-
# Starts a form tag that points the action to an url configured with <tt>url_for_options</tt> just like
-
# ActionController::Base#url_for. The method for the form defaults to POST.
-
#
-
# ==== Options
-
# * <tt>:multipart</tt> - If set to true, the enctype is set to "multipart/form-data".
-
# * <tt>:method</tt> - The method to use when submitting the form, usually either "get" or "post".
-
# If "patch", "put", "delete", or another verb is used, a hidden input with name <tt>_method</tt>
-
# is added to simulate the verb over post.
-
# * <tt>:authenticity_token</tt> - Authenticity token to use in the form. Use only if you need to
-
# pass custom authenticity token string, or to not add authenticity_token field at all
-
# (by passing <tt>false</tt>). Remote forms may omit the embedded authenticity token
-
# by setting <tt>config.action_view.embed_authenticity_token_in_remote_forms = false</tt>.
-
# This is helpful when you're fragment-caching the form. Remote forms get the
-
# authenticity token from the <tt>meta</tt> tag, so embedding is unnecessary unless you
-
# support browsers without JavaScript.
-
# * A list of parameters to feed to the URL the form will be posted to.
-
# * <tt>:remote</tt> - If set to true, will allow the Unobtrusive JavaScript drivers to control the
-
# submit behavior. By default this behavior is an ajax submit.
-
# * <tt>:enforce_utf8</tt> - If set to false, a hidden input with name utf8 is not output.
-
#
-
# ==== Examples
-
# form_tag('/posts')
-
# # => <form action="/posts" method="post">
-
#
-
# form_tag('/posts/1', method: :put)
-
# # => <form action="/posts/1" method="post"> ... <input name="_method" type="hidden" value="put" /> ...
-
#
-
# form_tag('/upload', multipart: true)
-
# # => <form action="/upload" method="post" enctype="multipart/form-data">
-
#
-
# <%= form_tag('/posts') do -%>
-
# <div><%= submit_tag 'Save' %></div>
-
# <% end -%>
-
# # => <form action="/posts" method="post"><div><input type="submit" name="commit" value="Save" /></div></form>
-
#
-
# <%= form_tag('/posts', remote: true) %>
-
# # => <form action="/posts" method="post" data-remote="true">
-
#
-
# form_tag('http://far.away.com/form', authenticity_token: false)
-
# # form without authenticity token
-
#
-
# form_tag('http://far.away.com/form', authenticity_token: "cf50faa3fe97702ca1ae")
-
# # form with custom authenticity token
-
#
-
1
def form_tag(url_for_options = {}, options = {}, &block)
-
html_options = html_options_for_form(url_for_options, options)
-
if block_given?
-
form_tag_in_block(html_options, &block)
-
else
-
form_tag_html(html_options)
-
end
-
end
-
-
# Creates a dropdown selection box, or if the <tt>:multiple</tt> option is set to true, a multiple
-
# choice selection box.
-
#
-
# Helpers::FormOptions can be used to create common select boxes such as countries, time zones, or
-
# associated records. <tt>option_tags</tt> is a string containing the option tags for the select box.
-
#
-
# ==== Options
-
# * <tt>:multiple</tt> - If set to true the selection will allow multiple choices.
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * <tt>:include_blank</tt> - If set to true, an empty option will be created.
-
# * <tt>:prompt</tt> - Create a prompt option with blank value and the text asking user to select something
-
# * Any other key creates standard HTML attributes for the tag.
-
#
-
# ==== Examples
-
# select_tag "people", options_from_collection_for_select(@people, "id", "name")
-
# # <select id="people" name="people"><option value="1">David</option></select>
-
#
-
# select_tag "people", "<option>David</option>".html_safe
-
# # => <select id="people" name="people"><option>David</option></select>
-
#
-
# select_tag "count", "<option>1</option><option>2</option><option>3</option><option>4</option>".html_safe
-
# # => <select id="count" name="count"><option>1</option><option>2</option>
-
# # <option>3</option><option>4</option></select>
-
#
-
# select_tag "colors", "<option>Red</option><option>Green</option><option>Blue</option>".html_safe, multiple: true
-
# # => <select id="colors" multiple="multiple" name="colors[]"><option>Red</option>
-
# # <option>Green</option><option>Blue</option></select>
-
#
-
# select_tag "locations", "<option>Home</option><option selected='selected'>Work</option><option>Out</option>".html_safe
-
# # => <select id="locations" name="locations"><option>Home</option><option selected='selected'>Work</option>
-
# # <option>Out</option></select>
-
#
-
# select_tag "access", "<option>Read</option><option>Write</option>".html_safe, multiple: true, class: 'form_input'
-
# # => <select class="form_input" id="access" multiple="multiple" name="access[]"><option>Read</option>
-
# # <option>Write</option></select>
-
#
-
# select_tag "people", options_from_collection_for_select(@people, "id", "name"), include_blank: true
-
# # => <select id="people" name="people"><option value=""></option><option value="1">David</option></select>
-
#
-
# select_tag "people", options_from_collection_for_select(@people, "id", "name"), prompt: "Select something"
-
# # => <select id="people" name="people"><option value="">Select something</option><option value="1">David</option></select>
-
#
-
# select_tag "destination", "<option>NYC</option><option>Paris</option><option>Rome</option>".html_safe, disabled: true
-
# # => <select disabled="disabled" id="destination" name="destination"><option>NYC</option>
-
# # <option>Paris</option><option>Rome</option></select>
-
#
-
# select_tag "credit_card", options_for_select([ "VISA", "MasterCard" ], "MasterCard")
-
# # => <select id="credit_card" name="credit_card"><option>VISA</option>
-
# # <option selected="selected">MasterCard</option></select>
-
1
def select_tag(name, option_tags = nil, options = {})
-
option_tags ||= ""
-
html_name = (options[:multiple] == true && !name.to_s.ends_with?("[]")) ? "#{name}[]" : name
-
-
if options.delete(:include_blank)
-
option_tags = content_tag(:option, '', :value => '').safe_concat(option_tags)
-
end
-
-
if prompt = options.delete(:prompt)
-
option_tags = content_tag(:option, prompt, :value => '').safe_concat(option_tags)
-
end
-
-
content_tag :select, option_tags, { "name" => html_name, "id" => sanitize_to_id(name) }.update(options.stringify_keys)
-
end
-
-
# Creates a standard text field; use these text fields to input smaller chunks of text like a username
-
# or a search query.
-
#
-
# ==== Options
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * <tt>:size</tt> - The number of visible characters that will fit in the input.
-
# * <tt>:maxlength</tt> - The maximum number of characters that the browser will allow the user to enter.
-
# * <tt>:placeholder</tt> - The text contained in the field by default which is removed when the field receives focus.
-
# * Any other key creates standard HTML attributes for the tag.
-
#
-
# ==== Examples
-
# text_field_tag 'name'
-
# # => <input id="name" name="name" type="text" />
-
#
-
# text_field_tag 'query', 'Enter your search query here'
-
# # => <input id="query" name="query" type="text" value="Enter your search query here" />
-
#
-
# text_field_tag 'search', nil, placeholder: 'Enter search term...'
-
# # => <input id="search" name="search" placeholder="Enter search term..." type="text" />
-
#
-
# text_field_tag 'request', nil, class: 'special_input'
-
# # => <input class="special_input" id="request" name="request" type="text" />
-
#
-
# text_field_tag 'address', '', size: 75
-
# # => <input id="address" name="address" size="75" type="text" value="" />
-
#
-
# text_field_tag 'zip', nil, maxlength: 5
-
# # => <input id="zip" maxlength="5" name="zip" type="text" />
-
#
-
# text_field_tag 'payment_amount', '$0.00', disabled: true
-
# # => <input disabled="disabled" id="payment_amount" name="payment_amount" type="text" value="$0.00" />
-
#
-
# text_field_tag 'ip', '0.0.0.0', maxlength: 15, size: 20, class: "ip-input"
-
# # => <input class="ip-input" id="ip" maxlength="15" name="ip" size="20" type="text" value="0.0.0.0" />
-
1
def text_field_tag(name, value = nil, options = {})
-
tag :input, { "type" => "text", "name" => name, "id" => sanitize_to_id(name), "value" => value }.update(options.stringify_keys)
-
end
-
-
# Creates a label element. Accepts a block.
-
#
-
# ==== Options
-
# * Creates standard HTML attributes for the tag.
-
#
-
# ==== Examples
-
# label_tag 'name'
-
# # => <label for="name">Name</label>
-
#
-
# label_tag 'name', 'Your name'
-
# # => <label for="name">Your name</label>
-
#
-
# label_tag 'name', nil, class: 'small_label'
-
# # => <label for="name" class="small_label">Name</label>
-
1
def label_tag(name = nil, content_or_options = nil, options = nil, &block)
-
if block_given? && content_or_options.is_a?(Hash)
-
options = content_or_options = content_or_options.stringify_keys
-
else
-
options ||= {}
-
options = options.stringify_keys
-
end
-
options["for"] = sanitize_to_id(name) unless name.blank? || options.has_key?("for")
-
content_tag :label, content_or_options || name.to_s.humanize, options, &block
-
end
-
-
# Creates a hidden form input field used to transmit data that would be lost due to HTTP's statelessness or
-
# data that should be hidden from the user.
-
#
-
# ==== Options
-
# * Creates standard HTML attributes for the tag.
-
#
-
# ==== Examples
-
# hidden_field_tag 'tags_list'
-
# # => <input id="tags_list" name="tags_list" type="hidden" />
-
#
-
# hidden_field_tag 'token', 'VUBJKB23UIVI1UU1VOBVI@'
-
# # => <input id="token" name="token" type="hidden" value="VUBJKB23UIVI1UU1VOBVI@" />
-
#
-
# hidden_field_tag 'collected_input', '', onchange: "alert('Input collected!')"
-
# # => <input id="collected_input" name="collected_input" onchange="alert('Input collected!')"
-
# # type="hidden" value="" />
-
1
def hidden_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.stringify_keys.update("type" => "hidden"))
-
end
-
-
# Creates a file upload field. If you are using file uploads then you will also need
-
# to set the multipart option for the form tag:
-
#
-
# <%= form_tag '/upload', multipart: true do %>
-
# <label for="file">File to Upload</label> <%= file_field_tag "file" %>
-
# <%= submit_tag %>
-
# <% end %>
-
#
-
# The specified URL will then be passed a File object containing the selected file, or if the field
-
# was left blank, a StringIO object.
-
#
-
# ==== Options
-
# * Creates standard HTML attributes for the tag.
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * <tt>:multiple</tt> - If set to true, *in most updated browsers* the user will be allowed to select multiple files.
-
# * <tt>:accept</tt> - If set to one or multiple mime-types, the user will be suggested a filter when choosing a file. You still need to set up model validations.
-
#
-
# ==== Examples
-
# file_field_tag 'attachment'
-
# # => <input id="attachment" name="attachment" type="file" />
-
#
-
# file_field_tag 'avatar', class: 'profile_input'
-
# # => <input class="profile_input" id="avatar" name="avatar" type="file" />
-
#
-
# file_field_tag 'picture', disabled: true
-
# # => <input disabled="disabled" id="picture" name="picture" type="file" />
-
#
-
# file_field_tag 'resume', value: '~/resume.doc'
-
# # => <input id="resume" name="resume" type="file" value="~/resume.doc" />
-
#
-
# file_field_tag 'user_pic', accept: 'image/png,image/gif,image/jpeg'
-
# # => <input accept="image/png,image/gif,image/jpeg" id="user_pic" name="user_pic" type="file" />
-
#
-
# file_field_tag 'file', accept: 'text/html', class: 'upload', value: 'index.html'
-
# # => <input accept="text/html" class="upload" id="file" name="file" type="file" value="index.html" />
-
1
def file_field_tag(name, options = {})
-
text_field_tag(name, nil, options.update("type" => "file"))
-
end
-
-
# Creates a password field, a masked text field that will hide the users input behind a mask character.
-
#
-
# ==== Options
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * <tt>:size</tt> - The number of visible characters that will fit in the input.
-
# * <tt>:maxlength</tt> - The maximum number of characters that the browser will allow the user to enter.
-
# * Any other key creates standard HTML attributes for the tag.
-
#
-
# ==== Examples
-
# password_field_tag 'pass'
-
# # => <input id="pass" name="pass" type="password" />
-
#
-
# password_field_tag 'secret', 'Your secret here'
-
# # => <input id="secret" name="secret" type="password" value="Your secret here" />
-
#
-
# password_field_tag 'masked', nil, class: 'masked_input_field'
-
# # => <input class="masked_input_field" id="masked" name="masked" type="password" />
-
#
-
# password_field_tag 'token', '', size: 15
-
# # => <input id="token" name="token" size="15" type="password" value="" />
-
#
-
# password_field_tag 'key', nil, maxlength: 16
-
# # => <input id="key" maxlength="16" name="key" type="password" />
-
#
-
# password_field_tag 'confirm_pass', nil, disabled: true
-
# # => <input disabled="disabled" id="confirm_pass" name="confirm_pass" type="password" />
-
#
-
# password_field_tag 'pin', '1234', maxlength: 4, size: 6, class: "pin_input"
-
# # => <input class="pin_input" id="pin" maxlength="4" name="pin" size="6" type="password" value="1234" />
-
1
def password_field_tag(name = "password", value = nil, options = {})
-
text_field_tag(name, value, options.update("type" => "password"))
-
end
-
-
# Creates a text input area; use a textarea for longer text inputs such as blog posts or descriptions.
-
#
-
# ==== Options
-
# * <tt>:size</tt> - A string specifying the dimensions (columns by rows) of the textarea (e.g., "25x10").
-
# * <tt>:rows</tt> - Specify the number of rows in the textarea
-
# * <tt>:cols</tt> - Specify the number of columns in the textarea
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * <tt>:escape</tt> - By default, the contents of the text input are HTML escaped.
-
# If you need unescaped contents, set this to false.
-
# * Any other key creates standard HTML attributes for the tag.
-
#
-
# ==== Examples
-
# text_area_tag 'post'
-
# # => <textarea id="post" name="post"></textarea>
-
#
-
# text_area_tag 'bio', @user.bio
-
# # => <textarea id="bio" name="bio">This is my biography.</textarea>
-
#
-
# text_area_tag 'body', nil, rows: 10, cols: 25
-
# # => <textarea cols="25" id="body" name="body" rows="10"></textarea>
-
#
-
# text_area_tag 'body', nil, size: "25x10"
-
# # => <textarea name="body" id="body" cols="25" rows="10"></textarea>
-
#
-
# text_area_tag 'description', "Description goes here.", disabled: true
-
# # => <textarea disabled="disabled" id="description" name="description">Description goes here.</textarea>
-
#
-
# text_area_tag 'comment', nil, class: 'comment_input'
-
# # => <textarea class="comment_input" id="comment" name="comment"></textarea>
-
1
def text_area_tag(name, content = nil, options = {})
-
options = options.stringify_keys
-
-
if size = options.delete("size")
-
options["cols"], options["rows"] = size.split("x") if size.respond_to?(:split)
-
end
-
-
escape = options.delete("escape") { true }
-
content = ERB::Util.html_escape(content) if escape
-
-
content_tag :textarea, content.to_s.html_safe, { "name" => name, "id" => sanitize_to_id(name) }.update(options)
-
end
-
-
# Creates a check box form input tag.
-
#
-
# ==== Options
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * Any other key creates standard HTML options for the tag.
-
#
-
# ==== Examples
-
# check_box_tag 'accept'
-
# # => <input id="accept" name="accept" type="checkbox" value="1" />
-
#
-
# check_box_tag 'rock', 'rock music'
-
# # => <input id="rock" name="rock" type="checkbox" value="rock music" />
-
#
-
# check_box_tag 'receive_email', 'yes', true
-
# # => <input checked="checked" id="receive_email" name="receive_email" type="checkbox" value="yes" />
-
#
-
# check_box_tag 'tos', 'yes', false, class: 'accept_tos'
-
# # => <input class="accept_tos" id="tos" name="tos" type="checkbox" value="yes" />
-
#
-
# check_box_tag 'eula', 'accepted', false, disabled: true
-
# # => <input disabled="disabled" id="eula" name="eula" type="checkbox" value="accepted" />
-
1
def check_box_tag(name, value = "1", checked = false, options = {})
-
html_options = { "type" => "checkbox", "name" => name, "id" => sanitize_to_id(name), "value" => value }.update(options.stringify_keys)
-
html_options["checked"] = "checked" if checked
-
tag :input, html_options
-
end
-
-
# Creates a radio button; use groups of radio buttons named the same to allow users to
-
# select from a group of options.
-
#
-
# ==== Options
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * Any other key creates standard HTML options for the tag.
-
#
-
# ==== Examples
-
# radio_button_tag 'gender', 'male'
-
# # => <input id="gender_male" name="gender" type="radio" value="male" />
-
#
-
# radio_button_tag 'receive_updates', 'no', true
-
# # => <input checked="checked" id="receive_updates_no" name="receive_updates" type="radio" value="no" />
-
#
-
# radio_button_tag 'time_slot', "3:00 p.m.", false, disabled: true
-
# # => <input disabled="disabled" id="time_slot_300_pm" name="time_slot" type="radio" value="3:00 p.m." />
-
#
-
# radio_button_tag 'color', "green", true, class: "color_input"
-
# # => <input checked="checked" class="color_input" id="color_green" name="color" type="radio" value="green" />
-
1
def radio_button_tag(name, value, checked = false, options = {})
-
html_options = { "type" => "radio", "name" => name, "id" => "#{sanitize_to_id(name)}_#{sanitize_to_id(value)}", "value" => value }.update(options.stringify_keys)
-
html_options["checked"] = "checked" if checked
-
tag :input, html_options
-
end
-
-
# Creates a submit button with the text <tt>value</tt> as the caption.
-
#
-
# ==== Options
-
# * <tt>:data</tt> - This option can be used to add custom data attributes.
-
# * <tt>:disabled</tt> - If true, the user will not be able to use this input.
-
# * Any other key creates standard HTML options for the tag.
-
#
-
# ==== Data attributes
-
#
-
# * <tt>confirm: 'question?'</tt> - If present the unobtrusive JavaScript
-
# drivers will provide a prompt with the question specified. If the user accepts,
-
# the form is processed normally, otherwise no action is taken.
-
# * <tt>:disable_with</tt> - Value of this parameter will be used as the value for a
-
# disabled version of the submit button when the form is submitted. This feature is
-
# provided by the unobtrusive JavaScript driver.
-
#
-
# ==== Examples
-
# submit_tag
-
# # => <input name="commit" type="submit" value="Save changes" />
-
#
-
# submit_tag "Edit this article"
-
# # => <input name="commit" type="submit" value="Edit this article" />
-
#
-
# submit_tag "Save edits", disabled: true
-
# # => <input disabled="disabled" name="commit" type="submit" value="Save edits" />
-
#
-
# submit_tag "Complete sale", data: { disable_with: "Please wait..." }
-
# # => <input name="commit" data-disable-with="Please wait..." type="submit" value="Complete sale" />
-
#
-
# submit_tag nil, class: "form_submit"
-
# # => <input class="form_submit" name="commit" type="submit" />
-
#
-
# submit_tag "Edit", class: "edit_button"
-
# # => <input class="edit_button" name="commit" type="submit" value="Edit" />
-
#
-
# submit_tag "Save", data: { confirm: "Are you sure?" }
-
# # => <input name='commit' type='submit' value='Save' data-confirm="Are you sure?" />
-
#
-
1
def submit_tag(value = "Save changes", options = {})
-
options = options.stringify_keys
-
-
tag :input, { "type" => "submit", "name" => "commit", "value" => value }.update(options)
-
end
-
-
# Creates a button element that defines a <tt>submit</tt> button,
-
# <tt>reset</tt>button or a generic button which can be used in
-
# JavaScript, for example. You can use the button tag as a regular
-
# submit tag but it isn't supported in legacy browsers. However,
-
# the button tag allows richer labels such as images and emphasis,
-
# so this helper will also accept a block.
-
#
-
# ==== Options
-
# * <tt>:data</tt> - This option can be used to add custom data attributes.
-
# * <tt>:disabled</tt> - If true, the user will not be able to
-
# use this input.
-
# * Any other key creates standard HTML options for the tag.
-
#
-
# ==== Data attributes
-
#
-
# * <tt>confirm: 'question?'</tt> - If present, the
-
# unobtrusive JavaScript drivers will provide a prompt with
-
# the question specified. If the user accepts, the form is
-
# processed normally, otherwise no action is taken.
-
# * <tt>:disable_with</tt> - Value of this parameter will be
-
# used as the value for a disabled version of the submit
-
# button when the form is submitted. This feature is provided
-
# by the unobtrusive JavaScript driver.
-
#
-
# ==== Examples
-
# button_tag
-
# # => <button name="button" type="submit">Button</button>
-
#
-
# button_tag(type: 'button') do
-
# content_tag(:strong, 'Ask me!')
-
# end
-
# # => <button name="button" type="button">
-
# # <strong>Ask me!</strong>
-
# # </button>
-
#
-
# button_tag "Checkout", data: { disable_with: "Please wait..." }
-
# # => <button data-disable-with="Please wait..." name="button" type="submit">Checkout</button>
-
#
-
1
def button_tag(content_or_options = nil, options = nil, &block)
-
if content_or_options.is_a? Hash
-
options = content_or_options
-
else
-
options ||= {}
-
end
-
-
options = { 'name' => 'button', 'type' => 'submit' }.merge!(options.stringify_keys)
-
-
if block_given?
-
content_tag :button, options, &block
-
else
-
content_tag :button, content_or_options || 'Button', options
-
end
-
end
-
-
# Displays an image which when clicked will submit the form.
-
#
-
# <tt>source</tt> is passed to AssetTagHelper#path_to_image
-
#
-
# ==== Options
-
# * <tt>:data</tt> - This option can be used to add custom data attributes.
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * Any other key creates standard HTML options for the tag.
-
#
-
# ==== Data attributes
-
#
-
# * <tt>confirm: 'question?'</tt> - This will add a JavaScript confirm
-
# prompt with the question specified. If the user accepts, the form is
-
# processed normally, otherwise no action is taken.
-
#
-
# ==== Examples
-
# image_submit_tag("login.png")
-
# # => <input alt="Login" src="/images/login.png" type="image" />
-
#
-
# image_submit_tag("purchase.png", disabled: true)
-
# # => <input alt="Purchase" disabled="disabled" src="/images/purchase.png" type="image" />
-
#
-
# image_submit_tag("search.png", class: 'search_button', alt: 'Find')
-
# # => <input alt="Find" class="search_button" src="/images/search.png" type="image" />
-
#
-
# image_submit_tag("agree.png", disabled: true, class: "agree_disagree_button")
-
# # => <input alt="Agree" class="agree_disagree_button" disabled="disabled" src="/images/agree.png" type="image" />
-
#
-
# image_submit_tag("save.png", data: { confirm: "Are you sure?" })
-
# # => <input alt="Save" src="/images/save.png" data-confirm="Are you sure?" type="image" />
-
1
def image_submit_tag(source, options = {})
-
options = options.stringify_keys
-
tag :input, { "alt" => image_alt(source), "type" => "image", "src" => path_to_image(source) }.update(options)
-
end
-
-
# Creates a field set for grouping HTML form elements.
-
#
-
# <tt>legend</tt> will become the fieldset's title (optional as per W3C).
-
# <tt>options</tt> accept the same values as tag.
-
#
-
# ==== Examples
-
# <%= field_set_tag do %>
-
# <p><%= text_field_tag 'name' %></p>
-
# <% end %>
-
# # => <fieldset><p><input id="name" name="name" type="text" /></p></fieldset>
-
#
-
# <%= field_set_tag 'Your details' do %>
-
# <p><%= text_field_tag 'name' %></p>
-
# <% end %>
-
# # => <fieldset><legend>Your details</legend><p><input id="name" name="name" type="text" /></p></fieldset>
-
#
-
# <%= field_set_tag nil, class: 'format' do %>
-
# <p><%= text_field_tag 'name' %></p>
-
# <% end %>
-
# # => <fieldset class="format"><p><input id="name" name="name" type="text" /></p></fieldset>
-
1
def field_set_tag(legend = nil, options = nil, &block)
-
output = tag(:fieldset, options, true)
-
output.safe_concat(content_tag(:legend, legend)) unless legend.blank?
-
output.concat(capture(&block)) if block_given?
-
output.safe_concat("</fieldset>")
-
end
-
-
# Creates a text field of type "color".
-
#
-
# ==== Options
-
# * Accepts the same options as text_field_tag.
-
1
def color_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.stringify_keys.update("type" => "color"))
-
end
-
-
# Creates a text field of type "search".
-
#
-
# ==== Options
-
# * Accepts the same options as text_field_tag.
-
1
def search_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.stringify_keys.update("type" => "search"))
-
end
-
-
# Creates a text field of type "tel".
-
#
-
# ==== Options
-
# * Accepts the same options as text_field_tag.
-
1
def telephone_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.stringify_keys.update("type" => "tel"))
-
end
-
1
alias phone_field_tag telephone_field_tag
-
-
# Creates a text field of type "date".
-
#
-
# ==== Options
-
# * Accepts the same options as text_field_tag.
-
1
def date_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.stringify_keys.update("type" => "date"))
-
end
-
-
# Creates a text field of type "time".
-
#
-
# === Options
-
# * <tt>:min</tt> - The minimum acceptable value.
-
# * <tt>:max</tt> - The maximum acceptable value.
-
# * <tt>:step</tt> - The acceptable value granularity.
-
# * Otherwise accepts the same options as text_field_tag.
-
1
def time_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.stringify_keys.update("type" => "time"))
-
end
-
-
# Creates a text field of type "datetime".
-
#
-
# === Options
-
# * <tt>:min</tt> - The minimum acceptable value.
-
# * <tt>:max</tt> - The maximum acceptable value.
-
# * <tt>:step</tt> - The acceptable value granularity.
-
# * Otherwise accepts the same options as text_field_tag.
-
1
def datetime_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.stringify_keys.update("type" => "datetime"))
-
end
-
-
# Creates a text field of type "datetime-local".
-
#
-
# === Options
-
# * <tt>:min</tt> - The minimum acceptable value.
-
# * <tt>:max</tt> - The maximum acceptable value.
-
# * <tt>:step</tt> - The acceptable value granularity.
-
# * Otherwise accepts the same options as text_field_tag.
-
1
def datetime_local_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.stringify_keys.update("type" => "datetime-local"))
-
end
-
-
# Creates a text field of type "month".
-
#
-
# === Options
-
# * <tt>:min</tt> - The minimum acceptable value.
-
# * <tt>:max</tt> - The maximum acceptable value.
-
# * <tt>:step</tt> - The acceptable value granularity.
-
# * Otherwise accepts the same options as text_field_tag.
-
1
def month_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.stringify_keys.update("type" => "month"))
-
end
-
-
# Creates a text field of type "week".
-
#
-
# === Options
-
# * <tt>:min</tt> - The minimum acceptable value.
-
# * <tt>:max</tt> - The maximum acceptable value.
-
# * <tt>:step</tt> - The acceptable value granularity.
-
# * Otherwise accepts the same options as text_field_tag.
-
1
def week_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.stringify_keys.update("type" => "week"))
-
end
-
-
# Creates a text field of type "url".
-
#
-
# ==== Options
-
# * Accepts the same options as text_field_tag.
-
1
def url_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.stringify_keys.update("type" => "url"))
-
end
-
-
# Creates a text field of type "email".
-
#
-
# ==== Options
-
# * Accepts the same options as text_field_tag.
-
1
def email_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.stringify_keys.update("type" => "email"))
-
end
-
-
# Creates a number field.
-
#
-
# ==== Options
-
# * <tt>:min</tt> - The minimum acceptable value.
-
# * <tt>:max</tt> - The maximum acceptable value.
-
# * <tt>:in</tt> - A range specifying the <tt>:min</tt> and
-
# <tt>:max</tt> values.
-
# * <tt>:step</tt> - The acceptable value granularity.
-
# * Otherwise accepts the same options as text_field_tag.
-
#
-
# ==== Examples
-
# number_field_tag 'quantity', nil, in: 1...10
-
# # => <input id="quantity" name="quantity" min="1" max="9" type="number" />
-
1
def number_field_tag(name, value = nil, options = {})
-
options = options.stringify_keys
-
options["type"] ||= "number"
-
if range = options.delete("in") || options.delete("within")
-
options.update("min" => range.min, "max" => range.max)
-
end
-
text_field_tag(name, value, options)
-
end
-
-
# Creates a range form element.
-
#
-
# ==== Options
-
# * Accepts the same options as number_field_tag.
-
1
def range_field_tag(name, value = nil, options = {})
-
number_field_tag(name, value, options.stringify_keys.update("type" => "range"))
-
end
-
-
# Creates the hidden UTF8 enforcer tag. Override this method in a helper
-
# to customize the tag.
-
1
def utf8_enforcer_tag
-
tag(:input, :type => "hidden", :name => "utf8", :value => "✓".html_safe)
-
end
-
-
1
private
-
1
def html_options_for_form(url_for_options, options)
-
options.stringify_keys.tap do |html_options|
-
html_options["enctype"] = "multipart/form-data" if html_options.delete("multipart")
-
# The following URL is unescaped, this is just a hash of options, and it is the
-
# responsibility of the caller to escape all the values.
-
html_options["action"] = url_for(url_for_options)
-
html_options["accept-charset"] = "UTF-8"
-
-
html_options["data-remote"] = true if html_options.delete("remote")
-
-
if html_options["data-remote"] &&
-
!embed_authenticity_token_in_remote_forms &&
-
html_options["authenticity_token"].blank?
-
# The authenticity token is taken from the meta tag in this case
-
html_options["authenticity_token"] = false
-
elsif html_options["authenticity_token"] == true
-
# Include the default authenticity_token, which is only generated when its set to nil,
-
# but we needed the true value to override the default of no authenticity_token on data-remote.
-
html_options["authenticity_token"] = nil
-
end
-
end
-
end
-
-
1
def extra_tags_for_form(html_options)
-
authenticity_token = html_options.delete("authenticity_token")
-
method = html_options.delete("method").to_s
-
-
method_tag = case method
-
when /^get$/i # must be case-insensitive, but can't use downcase as might be nil
-
html_options["method"] = "get"
-
''
-
when /^post$/i, "", nil
-
html_options["method"] = "post"
-
token_tag(authenticity_token)
-
else
-
html_options["method"] = "post"
-
method_tag(method) + token_tag(authenticity_token)
-
end
-
-
enforce_utf8 = html_options.delete("enforce_utf8") { true }
-
tags = (enforce_utf8 ? utf8_enforcer_tag : ''.html_safe) << method_tag
-
content_tag(:div, tags, :style => 'display:none')
-
end
-
-
1
def form_tag_html(html_options)
-
extra_tags = extra_tags_for_form(html_options)
-
tag(:form, html_options, true) + extra_tags
-
end
-
-
1
def form_tag_in_block(html_options, &block)
-
content = capture(&block)
-
output = form_tag_html(html_options)
-
output << content
-
output.safe_concat("</form>")
-
end
-
-
# see http://www.w3.org/TR/html4/types.html#type-name
-
1
def sanitize_to_id(name)
-
name.to_s.delete(']').gsub(/[^-a-zA-Z0-9:.]/, "_")
-
end
-
end
-
end
-
end
-
1
require 'action_view/helpers/tag_helper'
-
-
1
module ActionView
-
1
module Helpers
-
1
module JavaScriptHelper
-
1
JS_ESCAPE_MAP = {
-
'\\' => '\\\\',
-
'</' => '<\/',
-
"\r\n" => '\n',
-
"\n" => '\n',
-
"\r" => '\n',
-
'"' => '\\"',
-
"'" => "\\'"
-
}
-
-
1
JS_ESCAPE_MAP["\342\200\250".force_encoding(Encoding::UTF_8).encode!] = '
'
-
1
JS_ESCAPE_MAP["\342\200\251".force_encoding(Encoding::UTF_8).encode!] = '
'
-
-
# Escapes carriage returns and single and double quotes for JavaScript segments.
-
#
-
# Also available through the alias j(). This is particularly helpful in JavaScript
-
# responses, like:
-
#
-
# $('some_element').replaceWith('<%=j render 'some/element_template' %>');
-
1
def escape_javascript(javascript)
-
if javascript
-
result = javascript.gsub(/(\\|<\/|\r\n|\342\200\250|\342\200\251|[\n\r"'])/u) {|match| JS_ESCAPE_MAP[match] }
-
javascript.html_safe? ? result.html_safe : result
-
else
-
''
-
end
-
end
-
-
1
alias_method :j, :escape_javascript
-
-
# Returns a JavaScript tag with the +content+ inside. Example:
-
# javascript_tag "alert('All is good')"
-
#
-
# Returns:
-
# <script>
-
# //<![CDATA[
-
# alert('All is good')
-
# //]]>
-
# </script>
-
#
-
# +html_options+ may be a hash of attributes for the <tt>\<script></tt>
-
# tag.
-
#
-
# javascript_tag "alert('All is good')", defer: 'defer'
-
# # => <script defer="defer">alert('All is good')</script>
-
#
-
# Instead of passing the content as an argument, you can also use a block
-
# in which case, you pass your +html_options+ as the first parameter.
-
#
-
# <%= javascript_tag defer: 'defer' do -%>
-
# alert('All is good')
-
# <% end -%>
-
1
def javascript_tag(content_or_options_with_block = nil, html_options = {}, &block)
-
content =
-
if block_given?
-
html_options = content_or_options_with_block if content_or_options_with_block.is_a?(Hash)
-
capture(&block)
-
else
-
content_or_options_with_block
-
end
-
-
content_tag(:script, javascript_cdata_section(content), html_options)
-
end
-
-
1
def javascript_cdata_section(content) #:nodoc:
-
"\n//#{cdata_section("\n#{content}\n//")}\n".html_safe
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
-
1
require 'active_support/core_ext/hash/keys'
-
1
require 'active_support/core_ext/string/output_safety'
-
1
require 'active_support/number_helper'
-
-
1
module ActionView
-
# = Action View Number Helpers
-
1
module Helpers #:nodoc:
-
-
# Provides methods for converting numbers into formatted strings.
-
# Methods are provided for phone numbers, currency, percentage,
-
# precision, positional notation, file size and pretty printing.
-
#
-
# Most methods expect a +number+ argument, and will return it
-
# unchanged if can't be converted into a valid number.
-
1
module NumberHelper
-
-
# Raised when argument +number+ param given to the helpers is invalid and
-
# the option :raise is set to +true+.
-
1
class InvalidNumberError < StandardError
-
1
attr_accessor :number
-
1
def initialize(number)
-
@number = number
-
end
-
end
-
-
# Formats a +number+ into a US phone number (e.g., (555)
-
# 123-9876). You can customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:area_code</tt> - Adds parentheses around the area code.
-
# * <tt>:delimiter</tt> - Specifies the delimiter to use
-
# (defaults to "-").
-
# * <tt>:extension</tt> - Specifies an extension to add to the
-
# end of the generated number.
-
# * <tt>:country_code</tt> - Sets the country code for the phone
-
# number.
-
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
-
# the argument is invalid.
-
#
-
# ==== Examples
-
#
-
# number_to_phone(5551234) # => 555-1234
-
# number_to_phone("5551234") # => 555-1234
-
# number_to_phone(1235551234) # => 123-555-1234
-
# number_to_phone(1235551234, area_code: true) # => (123) 555-1234
-
# number_to_phone(1235551234, delimiter: " ") # => 123 555 1234
-
# number_to_phone(1235551234, area_code: true, extension: 555) # => (123) 555-1234 x 555
-
# number_to_phone(1235551234, country_code: 1) # => +1-123-555-1234
-
# number_to_phone("123a456") # => 123a456
-
# number_to_phone("1234a567", raise: true) # => InvalidNumberError
-
#
-
# number_to_phone(1235551234, country_code: 1, extension: 1343, delimiter: ".")
-
# # => +1.123.555.1234 x 1343
-
1
def number_to_phone(number, options = {})
-
return unless number
-
options = options.symbolize_keys
-
-
parse_float(number, true) if options.delete(:raise)
-
ERB::Util.html_escape(ActiveSupport::NumberHelper.number_to_phone(number, options))
-
end
-
-
# Formats a +number+ into a currency string (e.g., $13.65). You
-
# can customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the level of precision (defaults
-
# to 2).
-
# * <tt>:unit</tt> - Sets the denomination of the currency
-
# (defaults to "$").
-
# * <tt>:separator</tt> - Sets the separator between the units
-
# (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to ",").
-
# * <tt>:format</tt> - Sets the format for non-negative numbers
-
# (defaults to "%u%n"). Fields are <tt>%u</tt> for the
-
# currency, and <tt>%n</tt> for the number.
-
# * <tt>:negative_format</tt> - Sets the format for negative
-
# numbers (defaults to prepending an hyphen to the formatted
-
# number given by <tt>:format</tt>). Accepts the same fields
-
# than <tt>:format</tt>, except <tt>%n</tt> is here the
-
# absolute value of the number.
-
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
-
# the argument is invalid.
-
#
-
# ==== Examples
-
#
-
# number_to_currency(1234567890.50) # => $1,234,567,890.50
-
# number_to_currency(1234567890.506) # => $1,234,567,890.51
-
# number_to_currency(1234567890.506, precision: 3) # => $1,234,567,890.506
-
# number_to_currency(1234567890.506, locale: :fr) # => 1 234 567 890,51 €
-
# number_to_currency("123a456") # => $123a456
-
#
-
# number_to_currency("123a456", raise: true) # => InvalidNumberError
-
#
-
# number_to_currency(-1234567890.50, negative_format: "(%u%n)")
-
# # => ($1,234,567,890.50)
-
# number_to_currency(1234567890.50, unit: "R$", separator: ",", delimiter: "")
-
# # => R$1234567890,50
-
# number_to_currency(1234567890.50, unit: "R$", separator: ",", delimiter: "", format: "%n %u")
-
# # => 1234567890,50 R$
-
1
def number_to_currency(number, options = {})
-
delegate_number_helper_method(:number_to_currency, number, options)
-
end
-
-
# Formats a +number+ as a percentage string (e.g., 65%). You can
-
# customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +false+).
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +false+).
-
# * <tt>:format</tt> - Specifies the format of the percentage
-
# string The number field is <tt>%n</tt> (defaults to "%n%").
-
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
-
# the argument is invalid.
-
#
-
# ==== Examples
-
#
-
# number_to_percentage(100) # => 100.000%
-
# number_to_percentage("98") # => 98.000%
-
# number_to_percentage(100, precision: 0) # => 100%
-
# number_to_percentage(1000, delimiter: '.', separator: ',') # => 1.000,000%
-
# number_to_percentage(302.24398923423, precision: 5) # => 302.24399%
-
# number_to_percentage(1000, locale: :fr) # => 1 000,000%
-
# number_to_percentage("98a") # => 98a%
-
# number_to_percentage(100, format: "%n %") # => 100 %
-
#
-
# number_to_percentage("98a", raise: true) # => InvalidNumberError
-
1
def number_to_percentage(number, options = {})
-
delegate_number_helper_method(:number_to_percentage, number, options)
-
end
-
-
# Formats a +number+ with grouped thousands using +delimiter+
-
# (e.g., 12,324). You can customize the format in the +options+
-
# hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to ",").
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
-
# the argument is invalid.
-
#
-
# ==== Examples
-
#
-
# number_with_delimiter(12345678) # => 12,345,678
-
# number_with_delimiter("123456") # => 123,456
-
# number_with_delimiter(12345678.05) # => 12,345,678.05
-
# number_with_delimiter(12345678, delimiter: ".") # => 12.345.678
-
# number_with_delimiter(12345678, delimiter: ",") # => 12,345,678
-
# number_with_delimiter(12345678.05, separator: " ") # => 12,345,678 05
-
# number_with_delimiter(12345678.05, locale: :fr) # => 12 345 678,05
-
# number_with_delimiter("112a") # => 112a
-
# number_with_delimiter(98765432.98, delimiter: " ", separator: ",")
-
# # => 98 765 432,98
-
#
-
# number_with_delimiter("112a", raise: true) # => raise InvalidNumberError
-
1
def number_with_delimiter(number, options = {})
-
delegate_number_helper_method(:number_to_delimited, number, options)
-
end
-
-
# Formats a +number+ with the specified level of
-
# <tt>:precision</tt> (e.g., 112.32 has a precision of 2 if
-
# +:significant+ is +false+, and 5 if +:significant+ is +true+).
-
# You can customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +false+).
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +false+).
-
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
-
# the argument is invalid.
-
#
-
# ==== Examples
-
#
-
# number_with_precision(111.2345) # => 111.235
-
# number_with_precision(111.2345, precision: 2) # => 111.23
-
# number_with_precision(13, precision: 5) # => 13.00000
-
# number_with_precision(389.32314, precision: 0) # => 389
-
# number_with_precision(111.2345, significant: true) # => 111
-
# number_with_precision(111.2345, precision: 1, significant: true) # => 100
-
# number_with_precision(13, precision: 5, significant: true) # => 13.000
-
# number_with_precision(111.234, locale: :fr) # => 111,234
-
#
-
# number_with_precision(13, precision: 5, significant: true, strip_insignificant_zeros: true)
-
# # => 13
-
#
-
# number_with_precision(389.32314, precision: 4, significant: true) # => 389.3
-
# number_with_precision(1111.2345, precision: 2, separator: ',', delimiter: '.')
-
# # => 1.111,23
-
1
def number_with_precision(number, options = {})
-
delegate_number_helper_method(:number_to_rounded, number, options)
-
end
-
-
# Formats the bytes in +number+ into a more understandable
-
# representation (e.g., giving it 1500 yields 1.5 KB). This
-
# method is useful for reporting file sizes to users. You can
-
# customize the format in the +options+ hash.
-
#
-
# See <tt>number_to_human</tt> if you want to pretty-print a
-
# generic number.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +true+)
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +true+)
-
# * <tt>:prefix</tt> - If +:si+ formats the number using the SI
-
# prefix (defaults to :binary)
-
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
-
# the argument is invalid.
-
#
-
# ==== Examples
-
#
-
# number_to_human_size(123) # => 123 Bytes
-
# number_to_human_size(1234) # => 1.21 KB
-
# number_to_human_size(12345) # => 12.1 KB
-
# number_to_human_size(1234567) # => 1.18 MB
-
# number_to_human_size(1234567890) # => 1.15 GB
-
# number_to_human_size(1234567890123) # => 1.12 TB
-
# number_to_human_size(1234567, precision: 2) # => 1.2 MB
-
# number_to_human_size(483989, precision: 2) # => 470 KB
-
# number_to_human_size(1234567, precision: 2, separator: ',') # => 1,2 MB
-
#
-
# Non-significant zeros after the fractional separator are
-
# stripped out by default (set
-
# <tt>:strip_insignificant_zeros</tt> to +false+ to change
-
# that):
-
#
-
# number_to_human_size(1234567890123, precision: 5) # => "1.1229 TB"
-
# number_to_human_size(524288000, precision: 5) # => "500 MB"
-
1
def number_to_human_size(number, options = {})
-
delegate_number_helper_method(:number_to_human_size, number, options)
-
end
-
-
# Pretty prints (formats and approximates) a number in a way it
-
# is more readable by humans (eg.: 1200000000 becomes "1.2
-
# Billion"). This is useful for numbers that can get very large
-
# (and too hard to read).
-
#
-
# See <tt>number_to_human_size</tt> if you want to print a file
-
# size.
-
#
-
# You can also define you own unit-quantifier names if you want
-
# to use other decimal units (eg.: 1500 becomes "1.5
-
# kilometers", 0.150 becomes "150 milliliters", etc). You may
-
# define a wide range of unit quantifiers, even fractional ones
-
# (centi, deci, mili, etc).
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +true+)
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +true+)
-
# * <tt>:units</tt> - A Hash of unit quantifier names. Or a
-
# string containing an i18n scope where to find this hash. It
-
# might have the following keys:
-
# * *integers*: <tt>:unit</tt>, <tt>:ten</tt>,
-
# *<tt>:hundred</tt>, <tt>:thousand</tt>, <tt>:million</tt>,
-
# *<tt>:billion</tt>, <tt>:trillion</tt>,
-
# *<tt>:quadrillion</tt>
-
# * *fractionals*: <tt>:deci</tt>, <tt>:centi</tt>,
-
# *<tt>:mili</tt>, <tt>:micro</tt>, <tt>:nano</tt>,
-
# *<tt>:pico</tt>, <tt>:femto</tt>
-
# * <tt>:format</tt> - Sets the format of the output string
-
# (defaults to "%n %u"). The field types are:
-
# * %u - The quantifier (ex.: 'thousand')
-
# * %n - The number
-
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
-
# the argument is invalid.
-
#
-
# ==== Examples
-
#
-
# number_to_human(123) # => "123"
-
# number_to_human(1234) # => "1.23 Thousand"
-
# number_to_human(12345) # => "12.3 Thousand"
-
# number_to_human(1234567) # => "1.23 Million"
-
# number_to_human(1234567890) # => "1.23 Billion"
-
# number_to_human(1234567890123) # => "1.23 Trillion"
-
# number_to_human(1234567890123456) # => "1.23 Quadrillion"
-
# number_to_human(1234567890123456789) # => "1230 Quadrillion"
-
# number_to_human(489939, precision: 2) # => "490 Thousand"
-
# number_to_human(489939, precision: 4) # => "489.9 Thousand"
-
# number_to_human(1234567, precision: 4,
-
# significant: false) # => "1.2346 Million"
-
# number_to_human(1234567, precision: 1,
-
# separator: ',',
-
# significant: false) # => "1,2 Million"
-
#
-
# Non-significant zeros after the decimal separator are stripped
-
# out by default (set <tt>:strip_insignificant_zeros</tt> to
-
# +false+ to change that):
-
# number_to_human(12345012345, significant_digits: 6) # => "12.345 Billion"
-
# number_to_human(500000000, precision: 5) # => "500 Million"
-
#
-
# ==== Custom Unit Quantifiers
-
#
-
# You can also use your own custom unit quantifiers:
-
# number_to_human(500000, units: {unit: "ml", thousand: "lt"}) # => "500 lt"
-
#
-
# If in your I18n locale you have:
-
# distance:
-
# centi:
-
# one: "centimeter"
-
# other: "centimeters"
-
# unit:
-
# one: "meter"
-
# other: "meters"
-
# thousand:
-
# one: "kilometer"
-
# other: "kilometers"
-
# billion: "gazillion-distance"
-
#
-
# Then you could do:
-
#
-
# number_to_human(543934, units: :distance) # => "544 kilometers"
-
# number_to_human(54393498, units: :distance) # => "54400 kilometers"
-
# number_to_human(54393498000, units: :distance) # => "54.4 gazillion-distance"
-
# number_to_human(343, units: :distance, precision: 1) # => "300 meters"
-
# number_to_human(1, units: :distance) # => "1 meter"
-
# number_to_human(0.34, units: :distance) # => "34 centimeters"
-
#
-
1
def number_to_human(number, options = {})
-
delegate_number_helper_method(:number_to_human, number, options)
-
end
-
-
1
private
-
-
1
def delegate_number_helper_method(method, number, options)
-
return unless number
-
options = escape_unsafe_options(options.symbolize_keys)
-
-
wrap_with_output_safety_handling(number, options.delete(:raise)) {
-
ActiveSupport::NumberHelper.public_send(method, number, options)
-
}
-
end
-
-
1
def escape_unsafe_options(options)
-
options[:format] = ERB::Util.html_escape(options[:format]) if options[:format]
-
options[:negative_format] = ERB::Util.html_escape(options[:negative_format]) if options[:negative_format]
-
options[:separator] = ERB::Util.html_escape(options[:separator]) if options[:separator]
-
options[:delimiter] = ERB::Util.html_escape(options[:delimiter]) if options[:delimiter]
-
options[:unit] = ERB::Util.html_escape(options[:unit]) if options[:unit] && !options[:unit].html_safe?
-
options[:units] = escape_units(options[:units]) if options[:units] && Hash === options[:units]
-
options
-
end
-
-
1
def escape_units(units)
-
Hash[units.map do |k, v|
-
[k, ERB::Util.html_escape(v)]
-
end]
-
end
-
-
1
def wrap_with_output_safety_handling(number, raise_on_invalid, &block)
-
valid_float = valid_float?(number)
-
raise InvalidNumberError, number if raise_on_invalid && !valid_float
-
-
formatted_number = yield
-
-
if valid_float || number.html_safe?
-
formatted_number.html_safe
-
else
-
formatted_number
-
end
-
end
-
-
1
def valid_float?(number)
-
!parse_float(number, false).nil?
-
end
-
-
1
def parse_float(number, raise_error)
-
Float(number)
-
rescue ArgumentError, TypeError
-
raise InvalidNumberError, number if raise_error
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/string/output_safety'
-
-
1
module ActionView #:nodoc:
-
# = Action View Raw Output Helper
-
1
module Helpers #:nodoc:
-
1
module OutputSafetyHelper
-
# This method outputs without escaping a string. Since escaping tags is
-
# now default, this can be used when you don't want Rails to automatically
-
# escape tags. This is not recommended if the data is coming from the user's
-
# input.
-
#
-
# For example:
-
#
-
# raw @user.name
-
# # => 'Jimmy <alert>Tables</alert>'
-
1
def raw(stringish)
-
stringish.to_s.html_safe
-
end
-
-
# This method returns a html safe string similar to what <tt>Array#join</tt>
-
# would return. All items in the array, including the supplied separator, are
-
# html escaped unless they are html safe, and the returned string is marked
-
# as html safe.
-
#
-
# safe_join(["<p>foo</p>".html_safe, "<p>bar</p>"], "<br />")
-
# # => "<p>foo</p><br /><p>bar</p>"
-
#
-
# safe_join(["<p>foo</p>".html_safe, "<p>bar</p>".html_safe], "<br />".html_safe)
-
# # => "<p>foo</p><br /><p>bar</p>"
-
#
-
1
def safe_join(array, sep=$,)
-
sep = ERB::Util.html_escape(sep)
-
-
array.map { |i| ERB::Util.html_escape(i) }.join(sep).html_safe
-
end
-
end
-
end
-
end
-
1
require 'action_view/record_identifier'
-
-
1
module ActionView
-
# = Action View Record Tag Helpers
-
1
module Helpers
-
1
module RecordTagHelper
-
1
include ActionView::RecordIdentifier
-
-
# Produces a wrapper DIV element with id and class parameters that
-
# relate to the specified Active Record object. Usage example:
-
#
-
# <%= div_for(@person, class: "foo") do %>
-
# <%= @person.name %>
-
# <% end %>
-
#
-
# produces:
-
#
-
# <div id="person_123" class="person foo"> Joe Bloggs </div>
-
#
-
# You can also pass an array of Active Record objects, which will then
-
# get iterated over and yield each record as an argument for the block.
-
# For example:
-
#
-
# <%= div_for(@people, class: "foo") do |person| %>
-
# <%= person.name %>
-
# <% end %>
-
#
-
# produces:
-
#
-
# <div id="person_123" class="person foo"> Joe Bloggs </div>
-
# <div id="person_124" class="person foo"> Jane Bloggs </div>
-
#
-
1
def div_for(record, *args, &block)
-
content_tag_for(:div, record, *args, &block)
-
end
-
-
# content_tag_for creates an HTML element with id and class parameters
-
# that relate to the specified Active Record object. For example:
-
#
-
# <%= content_tag_for(:tr, @person) do %>
-
# <td><%= @person.first_name %></td>
-
# <td><%= @person.last_name %></td>
-
# <% end %>
-
#
-
# would produce the following HTML (assuming @person is an instance of
-
# a Person object, with an id value of 123):
-
#
-
# <tr id="person_123" class="person">....</tr>
-
#
-
# If you require the HTML id attribute to have a prefix, you can specify it:
-
#
-
# <%= content_tag_for(:tr, @person, :foo) do %> ...
-
#
-
# produces:
-
#
-
# <tr id="foo_person_123" class="person">...
-
#
-
# You can also pass an array of objects which this method will loop through
-
# and yield the current object to the supplied block, reducing the need for
-
# having to iterate through the object (using <tt>each</tt>) beforehand.
-
# For example (assuming @people is an array of Person objects):
-
#
-
# <%= content_tag_for(:tr, @people) do |person| %>
-
# <td><%= person.first_name %></td>
-
# <td><%= person.last_name %></td>
-
# <% end %>
-
#
-
# produces:
-
#
-
# <tr id="person_123" class="person">...</tr>
-
# <tr id="person_124" class="person">...</tr>
-
#
-
# content_tag_for also accepts a hash of options, which will be converted to
-
# additional HTML attributes. If you specify a <tt>:class</tt> value, it will be combined
-
# with the default class name for your object. For example:
-
#
-
# <%= content_tag_for(:li, @person, class: "bar") %>...
-
#
-
# produces:
-
#
-
# <li id="person_123" class="person bar">...
-
#
-
1
def content_tag_for(tag_name, single_or_multiple_records, prefix = nil, options = nil, &block)
-
options, prefix = prefix, nil if prefix.is_a?(Hash)
-
-
Array(single_or_multiple_records).map do |single_record|
-
content_tag_for_single_record(tag_name, single_record, prefix, options, &block)
-
end.join("\n").html_safe
-
end
-
-
1
private
-
-
# Called by <tt>content_tag_for</tt> internally to render a content tag
-
# for each record.
-
1
def content_tag_for_single_record(tag_name, record, prefix, options, &block)
-
options = options ? options.dup : {}
-
options[:class] = [ dom_class(record, prefix), options[:class] ].compact
-
options[:id] = dom_id(record, prefix)
-
-
if block_given?
-
content_tag(tag_name, capture(record, &block), options)
-
else
-
content_tag(tag_name, "", options)
-
end
-
end
-
end
-
end
-
end
-
1
module ActionView
-
1
module Helpers
-
# = Action View Rendering
-
#
-
# Implements methods that allow rendering from a view context.
-
# In order to use this module, all you need is to implement
-
# view_renderer that returns an ActionView::Renderer object.
-
1
module RenderingHelper
-
# Returns the result of a render that's dictated by the options hash. The primary options are:
-
#
-
# * <tt>:partial</tt> - See <tt>ActionView::PartialRenderer</tt>.
-
# * <tt>:file</tt> - Renders an explicit template file (this used to be the old default), add :locals to pass in those.
-
# * <tt>:inline</tt> - Renders an inline template similar to how it's done in the controller.
-
# * <tt>:text</tt> - Renders the text passed in out.
-
# * <tt>:plain</tt> - Renders the text passed in out. Setting the content
-
# type as <tt>text/plain</tt>.
-
# * <tt>:html</tt> - Renders the html safe string passed in out, otherwise
-
# performs html escape on the string first. Setting the content type as
-
# <tt>text/html</tt>.
-
# * <tt>:body</tt> - Renders the text passed in, and inherits the content
-
# type of <tt>text/html</tt> from <tt>ActionDispatch::Response</tt>
-
# object.
-
#
-
# If no options hash is passed or :update specified, the default is to render a partial and use the second parameter
-
# as the locals hash.
-
1
def render(options = {}, locals = {}, &block)
-
case options
-
when Hash
-
if block_given?
-
view_renderer.render_partial(self, options.merge(:partial => options[:layout]), &block)
-
else
-
view_renderer.render(self, options)
-
end
-
else
-
view_renderer.render_partial(self, :partial => options, :locals => locals)
-
end
-
end
-
-
# Overwrites _layout_for in the context object so it supports the case a block is
-
# passed to a partial. Returns the contents that are yielded to a layout, given a
-
# name or a block.
-
#
-
# You can think of a layout as a method that is called with a block. If the user calls
-
# <tt>yield :some_name</tt>, the block, by default, returns <tt>content_for(:some_name)</tt>.
-
# If the user calls simply +yield+, the default block returns <tt>content_for(:layout)</tt>.
-
#
-
# The user can override this default by passing a block to the layout:
-
#
-
# # The template
-
# <%= render layout: "my_layout" do %>
-
# Content
-
# <% end %>
-
#
-
# # The layout
-
# <html>
-
# <%= yield %>
-
# </html>
-
#
-
# In this case, instead of the default block, which would return <tt>content_for(:layout)</tt>,
-
# this method returns the block that was passed in to <tt>render :layout</tt>, and the response
-
# would be
-
#
-
# <html>
-
# Content
-
# </html>
-
#
-
# Finally, the block can take block arguments, which can be passed in by +yield+:
-
#
-
# # The template
-
# <%= render layout: "my_layout" do |customer| %>
-
# Hello <%= customer.name %>
-
# <% end %>
-
#
-
# # The layout
-
# <html>
-
# <%= yield Struct.new(:name).new("David") %>
-
# </html>
-
#
-
# In this case, the layout would receive the block passed into <tt>render :layout</tt>,
-
# and the struct specified would be passed into the block as an argument. The result
-
# would be
-
#
-
# <html>
-
# Hello David
-
# </html>
-
#
-
1
def _layout_for(*args, &block)
-
name = args.first
-
-
if block && !name.is_a?(Symbol)
-
capture(*args, &block)
-
else
-
super
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/object/try'
-
1
require 'action_view/vendor/html-scanner'
-
-
1
module ActionView
-
# = Action View Sanitize Helpers
-
1
module Helpers
-
# The SanitizeHelper module provides a set of methods for scrubbing text of undesired HTML elements.
-
# These helper methods extend Action View making them callable within your template files.
-
1
module SanitizeHelper
-
1
extend ActiveSupport::Concern
-
# This +sanitize+ helper will html encode all tags and strip all attributes that
-
# aren't specifically allowed.
-
#
-
# It also strips href/src tags with invalid protocols, like javascript: especially.
-
# It does its best to counter any tricks that hackers may use, like throwing in
-
# unicode/ascii/hex values to get past the javascript: filters. Check out
-
# the extensive test suite.
-
#
-
# <%= sanitize @article.body %>
-
#
-
# You can add or remove tags/attributes if you want to customize it a bit.
-
# See ActionView::Base for full docs on the available options. You can add
-
# tags/attributes for single uses of +sanitize+ by passing either the
-
# <tt>:attributes</tt> or <tt>:tags</tt> options:
-
#
-
# Normal Use
-
#
-
# <%= sanitize @article.body %>
-
#
-
# Custom Use (only the mentioned tags and attributes are allowed, nothing else)
-
#
-
# <%= sanitize @article.body, tags: %w(table tr td), attributes: %w(id class style) %>
-
#
-
# Add table tags to the default allowed tags
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_allowed_tags = 'table', 'tr', 'td'
-
# end
-
#
-
# Remove tags to the default allowed tags
-
#
-
# class Application < Rails::Application
-
# config.after_initialize do
-
# ActionView::Base.sanitized_allowed_tags.delete 'div'
-
# end
-
# end
-
#
-
# Change allowed default attributes
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_allowed_attributes = 'id', 'class', 'style'
-
# end
-
#
-
# Please note that sanitizing user-provided text does not guarantee that the
-
# resulting markup is valid (conforming to a document type) or even well-formed.
-
# The output may still contain e.g. unescaped '<', '>', '&' characters and
-
# confuse browsers.
-
#
-
1
def sanitize(html, options = {})
-
self.class.white_list_sanitizer.sanitize(html, options).try(:html_safe)
-
end
-
-
# Sanitizes a block of CSS code. Used by +sanitize+ when it comes across a style attribute.
-
1
def sanitize_css(style)
-
self.class.white_list_sanitizer.sanitize_css(style)
-
end
-
-
# Strips all HTML tags from the +html+, including comments. This uses the
-
# html-scanner tokenizer and so its HTML parsing ability is limited by
-
# that of html-scanner.
-
#
-
# strip_tags("Strip <i>these</i> tags!")
-
# # => Strip these tags!
-
#
-
# strip_tags("<b>Bold</b> no more! <a href='more.html'>See more here</a>...")
-
# # => Bold no more! See more here...
-
#
-
# strip_tags("<div id='top-bar'>Welcome to my website!</div>")
-
# # => Welcome to my website!
-
1
def strip_tags(html)
-
self.class.full_sanitizer.sanitize(html)
-
end
-
-
# Strips all link tags from +text+ leaving just the link text.
-
#
-
# strip_links('<a href="http://www.rubyonrails.org">Ruby on Rails</a>')
-
# # => Ruby on Rails
-
#
-
# strip_links('Please e-mail me at <a href="mailto:me@email.com">me@email.com</a>.')
-
# # => Please e-mail me at me@email.com.
-
#
-
# strip_links('Blog: <a href="http://www.myblog.com/" class="nav" target=\"_blank\">Visit</a>.')
-
# # => Blog: Visit.
-
1
def strip_links(html)
-
self.class.link_sanitizer.sanitize(html)
-
end
-
-
1
module ClassMethods #:nodoc:
-
1
attr_writer :full_sanitizer, :link_sanitizer, :white_list_sanitizer
-
-
1
def sanitized_protocol_separator
-
white_list_sanitizer.protocol_separator
-
end
-
-
1
def sanitized_uri_attributes
-
white_list_sanitizer.uri_attributes
-
end
-
-
1
def sanitized_bad_tags
-
white_list_sanitizer.bad_tags
-
end
-
-
1
def sanitized_allowed_tags
-
white_list_sanitizer.allowed_tags
-
end
-
-
1
def sanitized_allowed_attributes
-
white_list_sanitizer.allowed_attributes
-
end
-
-
1
def sanitized_allowed_css_properties
-
white_list_sanitizer.allowed_css_properties
-
end
-
-
1
def sanitized_allowed_css_keywords
-
white_list_sanitizer.allowed_css_keywords
-
end
-
-
1
def sanitized_shorthand_css_properties
-
white_list_sanitizer.shorthand_css_properties
-
end
-
-
1
def sanitized_allowed_protocols
-
white_list_sanitizer.allowed_protocols
-
end
-
-
1
def sanitized_protocol_separator=(value)
-
white_list_sanitizer.protocol_separator = value
-
end
-
-
# Gets the HTML::FullSanitizer instance used by +strip_tags+. Replace with
-
# any object that responds to +sanitize+.
-
#
-
# class Application < Rails::Application
-
# config.action_view.full_sanitizer = MySpecialSanitizer.new
-
# end
-
#
-
1
def full_sanitizer
-
@full_sanitizer ||= HTML::FullSanitizer.new
-
end
-
-
# Gets the HTML::LinkSanitizer instance used by +strip_links+. Replace with
-
# any object that responds to +sanitize+.
-
#
-
# class Application < Rails::Application
-
# config.action_view.link_sanitizer = MySpecialSanitizer.new
-
# end
-
#
-
1
def link_sanitizer
-
@link_sanitizer ||= HTML::LinkSanitizer.new
-
end
-
-
# Gets the HTML::WhiteListSanitizer instance used by sanitize and +sanitize_css+.
-
# Replace with any object that responds to +sanitize+.
-
#
-
# class Application < Rails::Application
-
# config.action_view.white_list_sanitizer = MySpecialSanitizer.new
-
# end
-
#
-
1
def white_list_sanitizer
-
@white_list_sanitizer ||= HTML::WhiteListSanitizer.new
-
end
-
-
# Adds valid HTML attributes that the +sanitize+ helper checks for URIs.
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_uri_attributes = 'lowsrc', 'target'
-
# end
-
#
-
1
def sanitized_uri_attributes=(attributes)
-
HTML::WhiteListSanitizer.uri_attributes.merge(attributes)
-
end
-
-
# Adds to the Set of 'bad' tags for the +sanitize+ helper.
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_bad_tags = 'embed', 'object'
-
# end
-
#
-
1
def sanitized_bad_tags=(attributes)
-
HTML::WhiteListSanitizer.bad_tags.merge(attributes)
-
end
-
-
# Adds to the Set of allowed tags for the +sanitize+ helper.
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_allowed_tags = 'table', 'tr', 'td'
-
# end
-
#
-
1
def sanitized_allowed_tags=(attributes)
-
HTML::WhiteListSanitizer.allowed_tags.merge(attributes)
-
end
-
-
# Adds to the Set of allowed HTML attributes for the +sanitize+ helper.
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_allowed_attributes = 'onclick', 'longdesc'
-
# end
-
#
-
1
def sanitized_allowed_attributes=(attributes)
-
HTML::WhiteListSanitizer.allowed_attributes.merge(attributes)
-
end
-
-
# Adds to the Set of allowed CSS properties for the #sanitize and +sanitize_css+ helpers.
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_allowed_css_properties = 'expression'
-
# end
-
#
-
1
def sanitized_allowed_css_properties=(attributes)
-
HTML::WhiteListSanitizer.allowed_css_properties.merge(attributes)
-
end
-
-
# Adds to the Set of allowed CSS keywords for the +sanitize+ and +sanitize_css+ helpers.
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_allowed_css_keywords = 'expression'
-
# end
-
#
-
1
def sanitized_allowed_css_keywords=(attributes)
-
HTML::WhiteListSanitizer.allowed_css_keywords.merge(attributes)
-
end
-
-
# Adds to the Set of allowed shorthand CSS properties for the +sanitize+ and +sanitize_css+ helpers.
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_shorthand_css_properties = 'expression'
-
# end
-
#
-
1
def sanitized_shorthand_css_properties=(attributes)
-
HTML::WhiteListSanitizer.shorthand_css_properties.merge(attributes)
-
end
-
-
# Adds to the Set of allowed protocols for the +sanitize+ helper.
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_allowed_protocols = 'ssh', 'feed'
-
# end
-
#
-
1
def sanitized_allowed_protocols=(attributes)
-
HTML::WhiteListSanitizer.allowed_protocols.merge(attributes)
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/string/output_safety'
-
1
require 'set'
-
-
1
module ActionView
-
# = Action View Tag Helpers
-
1
module Helpers #:nodoc:
-
# Provides methods to generate HTML tags programmatically when you can't use
-
# a Builder. By default, they output XHTML compliant tags.
-
1
module TagHelper
-
1
extend ActiveSupport::Concern
-
1
include CaptureHelper
-
-
1
BOOLEAN_ATTRIBUTES = %w(disabled readonly multiple checked autobuffer
-
autoplay controls loop selected hidden scoped async
-
defer reversed ismap seamless muted required
-
autofocus novalidate formnovalidate open pubdate
-
itemscope allowfullscreen default inert sortable
-
truespeed typemustmatch).to_set
-
-
31
BOOLEAN_ATTRIBUTES.merge(BOOLEAN_ATTRIBUTES.map {|attribute| attribute.to_sym })
-
-
1
PRE_CONTENT_STRINGS = {
-
:textarea => "\n"
-
}
-
-
# Returns an empty HTML tag of type +name+ which by default is XHTML
-
# compliant. Set +open+ to true to create an open tag compatible
-
# with HTML 4.0 and below. Add HTML attributes by passing an attributes
-
# hash to +options+. Set +escape+ to false to disable attribute value
-
# escaping.
-
#
-
# ==== Options
-
# You can use symbols or strings for the attribute names.
-
#
-
# Use +true+ with boolean attributes that can render with no value, like
-
# +disabled+ and +readonly+.
-
#
-
# HTML5 <tt>data-*</tt> attributes can be set with a single +data+ key
-
# pointing to a hash of sub-attributes.
-
#
-
# To play nicely with JavaScript conventions sub-attributes are dasherized.
-
# For example, a key +user_id+ would render as <tt>data-user-id</tt> and
-
# thus accessed as <tt>dataset.userId</tt>.
-
#
-
# Values are encoded to JSON, with the exception of strings and symbols.
-
# This may come in handy when using jQuery's HTML5-aware <tt>.data()</tt>
-
# from 1.4.3.
-
#
-
# ==== Examples
-
# tag("br")
-
# # => <br />
-
#
-
# tag("br", nil, true)
-
# # => <br>
-
#
-
# tag("input", type: 'text', disabled: true)
-
# # => <input type="text" disabled="disabled" />
-
#
-
# tag("img", src: "open & shut.png")
-
# # => <img src="open & shut.png" />
-
#
-
# tag("img", {src: "open & shut.png"}, false, false)
-
# # => <img src="open & shut.png" />
-
#
-
# tag("div", data: {name: 'Stephen', city_state: %w(Chicago IL)})
-
# # => <div data-name="Stephen" data-city-state="["Chicago","IL"]" />
-
1
def tag(name, options = nil, open = false, escape = true)
-
"<#{name}#{tag_options(options, escape) if options}#{open ? ">" : " />"}".html_safe
-
end
-
-
# Returns an HTML block tag of type +name+ surrounding the +content+. Add
-
# HTML attributes by passing an attributes hash to +options+.
-
# Instead of passing the content as an argument, you can also use a block
-
# in which case, you pass your +options+ as the second parameter.
-
# Set escape to false to disable attribute value escaping.
-
#
-
# ==== Options
-
# The +options+ hash is used with attributes with no value like (<tt>disabled</tt> and
-
# <tt>readonly</tt>), which you can give a value of true in the +options+ hash. You can use
-
# symbols or strings for the attribute names.
-
#
-
# ==== Examples
-
# content_tag(:p, "Hello world!")
-
# # => <p>Hello world!</p>
-
# content_tag(:div, content_tag(:p, "Hello world!"), class: "strong")
-
# # => <div class="strong"><p>Hello world!</p></div>
-
# content_tag("select", options, multiple: true)
-
# # => <select multiple="multiple">...options...</select>
-
#
-
# <%= content_tag :div, class: "strong" do -%>
-
# Hello world!
-
# <% end -%>
-
# # => <div class="strong">Hello world!</div>
-
1
def content_tag(name, content_or_options_with_block = nil, options = nil, escape = true, &block)
-
if block_given?
-
options = content_or_options_with_block if content_or_options_with_block.is_a?(Hash)
-
content_tag_string(name, capture(&block), options, escape)
-
else
-
content_tag_string(name, content_or_options_with_block, options, escape)
-
end
-
end
-
-
# Returns a CDATA section with the given +content+. CDATA sections
-
# are used to escape blocks of text containing characters which would
-
# otherwise be recognized as markup. CDATA sections begin with the string
-
# <tt><![CDATA[</tt> and end with (and may not contain) the string <tt>]]></tt>.
-
#
-
# cdata_section("<hello world>")
-
# # => <![CDATA[<hello world>]]>
-
#
-
# cdata_section(File.read("hello_world.txt"))
-
# # => <![CDATA[<hello from a text file]]>
-
#
-
# cdata_section("hello]]>world")
-
# # => <![CDATA[hello]]]]><![CDATA[>world]]>
-
1
def cdata_section(content)
-
splitted = content.to_s.gsub(']]>', ']]]]><![CDATA[>')
-
"<![CDATA[#{splitted}]]>".html_safe
-
end
-
-
# Returns an escaped version of +html+ without affecting existing escaped entities.
-
#
-
# escape_once("1 < 2 & 3")
-
# # => "1 < 2 & 3"
-
#
-
# escape_once("<< Accept & Checkout")
-
# # => "<< Accept & Checkout"
-
1
def escape_once(html)
-
ERB::Util.html_escape_once(html)
-
end
-
-
1
private
-
-
1
def content_tag_string(name, content, options, escape = true)
-
tag_options = tag_options(options, escape) if options
-
content = ERB::Util.h(content) if escape
-
"<#{name}#{tag_options}>#{PRE_CONTENT_STRINGS[name.to_sym]}#{content}</#{name}>".html_safe
-
end
-
-
1
def tag_options(options, escape = true)
-
return if options.blank?
-
attrs = []
-
options.each_pair do |key, value|
-
if key.to_s == 'data' && value.is_a?(Hash)
-
value.each_pair do |k, v|
-
attrs << data_tag_option(k, v, escape)
-
end
-
elsif BOOLEAN_ATTRIBUTES.include?(key)
-
attrs << boolean_tag_option(key) if value
-
elsif !value.nil?
-
attrs << tag_option(key, value, escape)
-
end
-
end
-
" #{attrs.sort! * ' '}" unless attrs.empty?
-
end
-
-
1
def data_tag_option(key, value, escape)
-
key = "data-#{key.to_s.dasherize}"
-
unless value.is_a?(String) || value.is_a?(Symbol) || value.is_a?(BigDecimal)
-
value = value.to_json
-
end
-
tag_option(key, value, escape)
-
end
-
-
1
def boolean_tag_option(key)
-
%(#{key}="#{key}")
-
end
-
-
1
def tag_option(key, value, escape)
-
value = value.join(" ") if value.is_a?(Array)
-
value = ERB::Util.h(value) if escape
-
%(#{key}="#{value}")
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/string/filters'
-
1
require 'active_support/core_ext/array/extract_options'
-
-
1
module ActionView
-
# = Action View Text Helpers
-
1
module Helpers #:nodoc:
-
# The TextHelper module provides a set of methods for filtering, formatting
-
# and transforming strings, which can reduce the amount of inline Ruby code in
-
# your views. These helper methods extend Action View making them callable
-
# within your template files.
-
#
-
# ==== Sanitization
-
#
-
# Most text helpers by default sanitize the given content, but do not escape it.
-
# This means HTML tags will appear in the page but all malicious code will be removed.
-
# Let's look at some examples using the +simple_format+ method:
-
#
-
# simple_format('<a href="http://example.com/">Example</a>')
-
# # => "<p><a href=\"http://example.com/\">Example</a></p>"
-
#
-
# simple_format('<a href="javascript:alert(\'no!\')">Example</a>')
-
# # => "<p><a>Example</a></p>"
-
#
-
# If you want to escape all content, you should invoke the +h+ method before
-
# calling the text helper.
-
#
-
# simple_format h('<a href="http://example.com/">Example</a>')
-
# # => "<p><a href=\"http://example.com/\">Example</a></p>"
-
1
module TextHelper
-
1
extend ActiveSupport::Concern
-
-
1
include SanitizeHelper
-
1
include TagHelper
-
1
include OutputSafetyHelper
-
-
# The preferred method of outputting text in your views is to use the
-
# <%= "text" %> eRuby syntax. The regular _puts_ and _print_ methods
-
# do not operate as expected in an eRuby code block. If you absolutely must
-
# output text within a non-output code block (i.e., <% %>), you can use the concat method.
-
#
-
# <%
-
# concat "hello"
-
# # is the equivalent of <%= "hello" %>
-
#
-
# if logged_in
-
# concat "Logged in!"
-
# else
-
# concat link_to('login', action: :login)
-
# end
-
# # will either display "Logged in!" or a login link
-
# %>
-
1
def concat(string)
-
output_buffer << string
-
end
-
-
1
def safe_concat(string)
-
output_buffer.respond_to?(:safe_concat) ? output_buffer.safe_concat(string) : concat(string)
-
end
-
-
# Truncates a given +text+ after a given <tt>:length</tt> if +text+ is longer than <tt>:length</tt>
-
# (defaults to 30). The last characters will be replaced with the <tt>:omission</tt> (defaults to "...")
-
# for a total length not exceeding <tt>:length</tt>.
-
#
-
# Pass a <tt>:separator</tt> to truncate +text+ at a natural break.
-
#
-
# Pass a block if you want to show extra content when the text is truncated.
-
#
-
# The result is marked as HTML-safe, but it is escaped by default, unless <tt>:escape</tt> is
-
# +false+. Care should be taken if +text+ contains HTML tags or entities, because truncation
-
# may produce invalid HTML (such as unbalanced or incomplete tags).
-
#
-
# truncate("Once upon a time in a world far far away")
-
# # => "Once upon a time in a world..."
-
#
-
# truncate("Once upon a time in a world far far away", length: 17)
-
# # => "Once upon a ti..."
-
#
-
# truncate("Once upon a time in a world far far away", length: 17, separator: ' ')
-
# # => "Once upon a..."
-
#
-
# truncate("And they found that many people were sleeping better.", length: 25, omission: '... (continued)')
-
# # => "And they f... (continued)"
-
#
-
# truncate("<p>Once upon a time in a world far far away</p>")
-
# # => "<p>Once upon a time in a wo..."
-
#
-
# truncate("<p>Once upon a time in a world far far away</p>", escape: false)
-
# # => "<p>Once upon a time in a wo..."
-
#
-
# truncate("Once upon a time in a world far far away") { link_to "Continue", "#" }
-
# # => "Once upon a time in a wo...<a href="#">Continue</a>"
-
1
def truncate(text, options = {}, &block)
-
if text
-
length = options.fetch(:length, 30)
-
-
content = text.truncate(length, options)
-
content = options[:escape] == false ? content.html_safe : ERB::Util.html_escape(content)
-
content << capture(&block) if block_given? && text.length > length
-
content
-
end
-
end
-
-
# Highlights one or more +phrases+ everywhere in +text+ by inserting it into
-
# a <tt>:highlighter</tt> string. The highlighter can be specialized by passing <tt>:highlighter</tt>
-
# as a single-quoted string with <tt>\1</tt> where the phrase is to be inserted (defaults to
-
# '<mark>\1</mark>')
-
#
-
# highlight('You searched for: rails', 'rails')
-
# # => You searched for: <mark>rails</mark>
-
#
-
# highlight('You searched for: ruby, rails, dhh', 'actionpack')
-
# # => You searched for: ruby, rails, dhh
-
#
-
# highlight('You searched for: rails', ['for', 'rails'], highlighter: '<em>\1</em>')
-
# # => You searched <em>for</em>: <em>rails</em>
-
#
-
# highlight('You searched for: rails', 'rails', highlighter: '<a href="search?q=\1">\1</a>')
-
# # => You searched for: <a href="search?q=rails">rails</a>
-
1
def highlight(text, phrases, options = {})
-
text = sanitize(text) if options.fetch(:sanitize, true)
-
-
if text.blank? || phrases.blank?
-
text
-
else
-
highlighter = options.fetch(:highlighter, '<mark>\1</mark>')
-
match = Array(phrases).map { |p| Regexp.escape(p) }.join('|')
-
text.gsub(/(#{match})(?![^<]*?>)/i, highlighter)
-
end.html_safe
-
end
-
-
# Extracts an excerpt from +text+ that matches the first instance of +phrase+.
-
# The <tt>:radius</tt> option expands the excerpt on each side of the first occurrence of +phrase+ by the number of characters
-
# defined in <tt>:radius</tt> (which defaults to 100). If the excerpt radius overflows the beginning or end of the +text+,
-
# then the <tt>:omission</tt> option (which defaults to "...") will be prepended/appended accordingly. Use the
-
# <tt>:separator</tt> option to choose the delimitation. The resulting string will be stripped in any case. If the +phrase+
-
# isn't found, nil is returned.
-
#
-
# excerpt('This is an example', 'an', radius: 5)
-
# # => ...s is an exam...
-
#
-
# excerpt('This is an example', 'is', radius: 5)
-
# # => This is a...
-
#
-
# excerpt('This is an example', 'is')
-
# # => This is an example
-
#
-
# excerpt('This next thing is an example', 'ex', radius: 2)
-
# # => ...next...
-
#
-
# excerpt('This is also an example', 'an', radius: 8, omission: '<chop> ')
-
# # => <chop> is also an example
-
#
-
# excerpt('This is a very beautiful morning', 'very', separator: ' ', radius: 1)
-
# # => ...a very beautiful...
-
1
def excerpt(text, phrase, options = {})
-
return unless text && phrase
-
-
separator = options[:separator] || ''
-
phrase = Regexp.escape(phrase)
-
regex = /#{phrase}/i
-
-
return unless matches = text.match(regex)
-
phrase = matches[0]
-
-
unless separator.empty?
-
text.split(separator).each do |value|
-
if value.match(regex)
-
regex = phrase = value
-
break
-
end
-
end
-
end
-
-
first_part, second_part = text.split(regex, 2)
-
-
prefix, first_part = cut_excerpt_part(:first, first_part, separator, options)
-
postfix, second_part = cut_excerpt_part(:second, second_part, separator, options)
-
-
affix = [first_part, separator, phrase, separator, second_part].join.strip
-
[prefix, affix, postfix].join
-
end
-
-
# Attempts to pluralize the +singular+ word unless +count+ is 1. If
-
# +plural+ is supplied, it will use that when count is > 1, otherwise
-
# it will use the Inflector to determine the plural form.
-
#
-
# pluralize(1, 'person')
-
# # => 1 person
-
#
-
# pluralize(2, 'person')
-
# # => 2 people
-
#
-
# pluralize(3, 'person', 'users')
-
# # => 3 users
-
#
-
# pluralize(0, 'person')
-
# # => 0 people
-
1
def pluralize(count, singular, plural = nil)
-
word = if (count == 1 || count =~ /^1(\.0+)?$/)
-
singular
-
else
-
plural || singular.pluralize
-
end
-
-
"#{count || 0} #{word}"
-
end
-
-
# Wraps the +text+ into lines no longer than +line_width+ width. This method
-
# breaks on the first whitespace character that does not exceed +line_width+
-
# (which is 80 by default).
-
#
-
# word_wrap('Once upon a time')
-
# # => Once upon a time
-
#
-
# word_wrap('Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding a successor to the throne turned out to be more trouble than anyone could have imagined...')
-
# # => Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding\na successor to the throne turned out to be more trouble than anyone could have\nimagined...
-
#
-
# word_wrap('Once upon a time', line_width: 8)
-
# # => Once\nupon a\ntime
-
#
-
# word_wrap('Once upon a time', line_width: 1)
-
# # => Once\nupon\na\ntime
-
1
def word_wrap(text, options = {})
-
line_width = options.fetch(:line_width, 80)
-
-
text.split("\n").collect! do |line|
-
line.length > line_width ? line.gsub(/(.{1,#{line_width}})(\s+|$)/, "\\1\n").strip : line
-
end * "\n"
-
end
-
-
# Returns +text+ transformed into HTML using simple formatting rules.
-
# Two or more consecutive newlines(<tt>\n\n</tt>) are considered as a
-
# paragraph and wrapped in <tt><p></tt> tags. One newline (<tt>\n</tt>) is
-
# considered as a linebreak and a <tt><br /></tt> tag is appended. This
-
# method does not remove the newlines from the +text+.
-
#
-
# You can pass any HTML attributes into <tt>html_options</tt>. These
-
# will be added to all created paragraphs.
-
#
-
# ==== Options
-
# * <tt>:sanitize</tt> - If +false+, does not sanitize +text+.
-
# * <tt>:wrapper_tag</tt> - String representing the wrapper tag, defaults to <tt>"p"</tt>
-
#
-
# ==== Examples
-
# my_text = "Here is some basic text...\n...with a line break."
-
#
-
# simple_format(my_text)
-
# # => "<p>Here is some basic text...\n<br />...with a line break.</p>"
-
#
-
# simple_format(my_text, {}, wrapper_tag: "div")
-
# # => "<div>Here is some basic text...\n<br />...with a line break.</div>"
-
#
-
# more_text = "We want to put a paragraph...\n\n...right there."
-
#
-
# simple_format(more_text)
-
# # => "<p>We want to put a paragraph...</p>\n\n<p>...right there.</p>"
-
#
-
# simple_format("Look ma! A class!", class: 'description')
-
# # => "<p class='description'>Look ma! A class!</p>"
-
#
-
# simple_format("<blink>Unblinkable.</blink>")
-
# # => "<p>Unblinkable.</p>"
-
#
-
# simple_format("<blink>Blinkable!</blink> It's true.", {}, sanitize: false)
-
# # => "<p><blink>Blinkable!</blink> It's true.</p>"
-
1
def simple_format(text, html_options = {}, options = {})
-
wrapper_tag = options.fetch(:wrapper_tag, :p)
-
-
text = sanitize(text) if options.fetch(:sanitize, true)
-
paragraphs = split_paragraphs(text)
-
-
if paragraphs.empty?
-
content_tag(wrapper_tag, nil, html_options)
-
else
-
paragraphs.map! { |paragraph|
-
content_tag(wrapper_tag, raw(paragraph), html_options)
-
}.join("\n\n").html_safe
-
end
-
end
-
-
# Creates a Cycle object whose _to_s_ method cycles through elements of an
-
# array every time it is called. This can be used for example, to alternate
-
# classes for table rows. You can use named cycles to allow nesting in loops.
-
# Passing a Hash as the last parameter with a <tt>:name</tt> key will create a
-
# named cycle. The default name for a cycle without a +:name+ key is
-
# <tt>"default"</tt>. You can manually reset a cycle by calling reset_cycle
-
# and passing the name of the cycle. The current cycle string can be obtained
-
# anytime using the current_cycle method.
-
#
-
# # Alternate CSS classes for even and odd numbers...
-
# @items = [1,2,3,4]
-
# <table>
-
# <% @items.each do |item| %>
-
# <tr class="<%= cycle("odd", "even") -%>">
-
# <td>item</td>
-
# </tr>
-
# <% end %>
-
# </table>
-
#
-
#
-
# # Cycle CSS classes for rows, and text colors for values within each row
-
# @items = x = [{first: 'Robert', middle: 'Daniel', last: 'James'},
-
# {first: 'Emily', middle: 'Shannon', maiden: 'Pike', last: 'Hicks'},
-
# {first: 'June', middle: 'Dae', last: 'Jones'}]
-
# <% @items.each do |item| %>
-
# <tr class="<%= cycle("odd", "even", name: "row_class") -%>">
-
# <td>
-
# <% item.values.each do |value| %>
-
# <%# Create a named cycle "colors" %>
-
# <span style="color:<%= cycle("red", "green", "blue", name: "colors") -%>">
-
# <%= value %>
-
# </span>
-
# <% end %>
-
# <% reset_cycle("colors") %>
-
# </td>
-
# </tr>
-
# <% end %>
-
1
def cycle(first_value, *values)
-
options = values.extract_options!
-
name = options.fetch(:name, 'default')
-
-
values.unshift(*first_value)
-
-
cycle = get_cycle(name)
-
unless cycle && cycle.values == values
-
cycle = set_cycle(name, Cycle.new(*values))
-
end
-
cycle.to_s
-
end
-
-
# Returns the current cycle string after a cycle has been started. Useful
-
# for complex table highlighting or any other design need which requires
-
# the current cycle string in more than one place.
-
#
-
# # Alternate background colors
-
# @items = [1,2,3,4]
-
# <% @items.each do |item| %>
-
# <div style="background-color:<%= cycle("red","white","blue") %>">
-
# <span style="background-color:<%= current_cycle %>"><%= item %></span>
-
# </div>
-
# <% end %>
-
1
def current_cycle(name = "default")
-
cycle = get_cycle(name)
-
cycle.current_value if cycle
-
end
-
-
# Resets a cycle so that it starts from the first element the next time
-
# it is called. Pass in +name+ to reset a named cycle.
-
#
-
# # Alternate CSS classes for even and odd numbers...
-
# @items = [[1,2,3,4], [5,6,3], [3,4,5,6,7,4]]
-
# <table>
-
# <% @items.each do |item| %>
-
# <tr class="<%= cycle("even", "odd") -%>">
-
# <% item.each do |value| %>
-
# <span style="color:<%= cycle("#333", "#666", "#999", name: "colors") -%>">
-
# <%= value %>
-
# </span>
-
# <% end %>
-
#
-
# <% reset_cycle("colors") %>
-
# </tr>
-
# <% end %>
-
# </table>
-
1
def reset_cycle(name = "default")
-
cycle = get_cycle(name)
-
cycle.reset if cycle
-
end
-
-
1
class Cycle #:nodoc:
-
1
attr_reader :values
-
-
1
def initialize(first_value, *values)
-
@values = values.unshift(first_value)
-
reset
-
end
-
-
1
def reset
-
@index = 0
-
end
-
-
1
def current_value
-
@values[previous_index].to_s
-
end
-
-
1
def to_s
-
value = @values[@index].to_s
-
@index = next_index
-
return value
-
end
-
-
1
private
-
-
1
def next_index
-
step_index(1)
-
end
-
-
1
def previous_index
-
step_index(-1)
-
end
-
-
1
def step_index(n)
-
(@index + n) % @values.size
-
end
-
end
-
-
1
private
-
# The cycle helpers need to store the cycles in a place that is
-
# guaranteed to be reset every time a page is rendered, so it
-
# uses an instance variable of ActionView::Base.
-
1
def get_cycle(name)
-
@_cycles = Hash.new unless defined?(@_cycles)
-
return @_cycles[name]
-
end
-
-
1
def set_cycle(name, cycle_object)
-
@_cycles = Hash.new unless defined?(@_cycles)
-
@_cycles[name] = cycle_object
-
end
-
-
1
def split_paragraphs(text)
-
return [] if text.blank?
-
-
text.to_str.gsub(/\r\n?/, "\n").split(/\n\n+/).map! do |t|
-
t.gsub!(/([^\n]\n)(?=[^\n])/, '\1<br />') || t
-
end
-
end
-
-
1
def cut_excerpt_part(part_position, part, separator, options)
-
return "", "" unless part
-
-
radius = options.fetch(:radius, 100)
-
omission = options.fetch(:omission, "...")
-
-
part = part.split(separator)
-
part.delete("")
-
affix = part.size > radius ? omission : ""
-
-
part = if part_position == :first
-
drop_index = [part.length - radius, 0].max
-
part.drop(drop_index)
-
else
-
part.first(radius)
-
end
-
-
return affix, part.join(separator)
-
end
-
end
-
end
-
end
-
1
require 'action_view/helpers/tag_helper'
-
1
require 'i18n/exceptions'
-
-
1
module ActionView
-
# = Action View Translation Helpers
-
1
module Helpers
-
1
module TranslationHelper
-
# Delegates to <tt>I18n#translate</tt> but also performs three additional functions.
-
#
-
# First, it will ensure that any thrown +MissingTranslation+ messages will be turned
-
# into inline spans that:
-
#
-
# * have a "translation-missing" class set,
-
# * contain the missing key as a title attribute and
-
# * a titleized version of the last key segment as a text.
-
#
-
# E.g. the value returned for a missing translation key :"blog.post.title" will be
-
# <span class="translation_missing" title="translation missing: en.blog.post.title">Title</span>.
-
# This way your views will display rather reasonable strings but it will still
-
# be easy to spot missing translations.
-
#
-
# Second, it'll scope the key by the current partial if the key starts
-
# with a period. So if you call <tt>translate(".foo")</tt> from the
-
# <tt>people/index.html.erb</tt> template, you'll actually be calling
-
# <tt>I18n.translate("people.index.foo")</tt>. This makes it less repetitive
-
# to translate many keys within the same partials and gives you a simple framework
-
# for scoping them consistently. If you don't prepend the key with a period,
-
# nothing is converted.
-
#
-
# Third, it'll mark the translation as safe HTML if the key has the suffix
-
# "_html" or the last element of the key is the word "html". For example,
-
# calling translate("footer_html") or translate("footer.html") will return
-
# a safe HTML string that won't be escaped by other HTML helper methods. This
-
# naming convention helps to identify translations that include HTML tags so that
-
# you know what kind of output to expect when you call translate in a template.
-
1
def translate(key, options = {})
-
options[:default] = wrap_translate_defaults(options[:default]) if options[:default]
-
-
# If the user has specified rescue_format then pass it all through, otherwise use
-
# raise and do the work ourselves
-
options[:raise] ||= ActionView::Base.raise_on_missing_translations
-
-
raise_error = options[:raise] || options.key?(:rescue_format)
-
unless raise_error
-
options[:raise] = true
-
end
-
-
if html_safe_translation_key?(key)
-
html_safe_options = options.dup
-
options.except(*I18n::RESERVED_KEYS).each do |name, value|
-
unless name == :count && value.is_a?(Numeric)
-
html_safe_options[name] = ERB::Util.html_escape(value.to_s)
-
end
-
end
-
translation = I18n.translate(scope_key_by_partial(key), html_safe_options)
-
-
translation.respond_to?(:html_safe) ? translation.html_safe : translation
-
else
-
I18n.translate(scope_key_by_partial(key), options)
-
end
-
rescue I18n::MissingTranslationData => e
-
raise e if raise_error
-
-
keys = I18n.normalize_keys(e.locale, e.key, e.options[:scope])
-
content_tag('span', keys.last.to_s.titleize, :class => 'translation_missing', :title => "translation missing: #{keys.join('.')}")
-
end
-
1
alias :t :translate
-
-
# Delegates to <tt>I18n.localize</tt> with no additional functionality.
-
#
-
# See http://rubydoc.info/github/svenfuchs/i18n/master/I18n/Backend/Base:localize
-
# for more information.
-
1
def localize(*args)
-
I18n.localize(*args)
-
end
-
1
alias :l :localize
-
-
1
private
-
1
def scope_key_by_partial(key)
-
if key.to_s.first == "."
-
if @virtual_path
-
@virtual_path.gsub(%r{/_?}, ".") + key.to_s
-
else
-
raise "Cannot use t(#{key.inspect}) shortcut because path is not available"
-
end
-
else
-
key
-
end
-
end
-
-
1
def html_safe_translation_key?(key)
-
key.to_s =~ /(\b|_|\.)html$/
-
end
-
-
1
def wrap_translate_defaults(defaults)
-
new_defaults = []
-
defaults = Array(defaults)
-
while key = defaults.shift
-
if key.is_a?(Symbol)
-
new_defaults << lambda { |_, options| translate key, options.merge(:default => defaults) }
-
break
-
else
-
new_defaults << key
-
end
-
end
-
-
new_defaults
-
end
-
end
-
end
-
end
-
1
require 'action_view/helpers/javascript_helper'
-
1
require 'active_support/core_ext/array/access'
-
1
require 'active_support/core_ext/hash/keys'
-
1
require 'active_support/core_ext/string/output_safety'
-
-
1
module ActionView
-
# = Action View URL Helpers
-
1
module Helpers #:nodoc:
-
# Provides a set of methods for making links and getting URLs that
-
# depend on the routing subsystem (see ActionDispatch::Routing).
-
# This allows you to use the same format for links in views
-
# and controllers.
-
1
module UrlHelper
-
# This helper may be included in any class that includes the
-
# URL helpers of a routes (routes.url_helpers). Some methods
-
# provided here will only work in the context of a request
-
# (link_to_unless_current, for instance), which must be provided
-
# as a method called #request on the context.
-
1
BUTTON_TAG_METHOD_VERBS = %w{patch put delete}
-
1
extend ActiveSupport::Concern
-
-
1
include TagHelper
-
-
1
module ClassMethods
-
1
def _url_for_modules
-
ActionView::RoutingUrlFor
-
end
-
end
-
-
# Basic implementation of url_for to allow use helpers without routes existence
-
1
def url_for(options = nil) # :nodoc:
-
case options
-
when String
-
options
-
when :back
-
_back_url
-
else
-
raise ArgumentError, "arguments passed to url_for can't be handled. Please require " +
-
"routes or provide your own implementation"
-
end
-
end
-
-
1
def _back_url # :nodoc:
-
referrer = controller.respond_to?(:request) && controller.request.env["HTTP_REFERER"]
-
referrer || 'javascript:history.back()'
-
end
-
1
protected :_back_url
-
-
# Creates a link tag of the given +name+ using a URL created by the set of +options+.
-
# See the valid options in the documentation for +url_for+. It's also possible to
-
# pass a String instead of an options hash, which generates a link tag that uses the
-
# value of the String as the href for the link. Using a <tt>:back</tt> Symbol instead
-
# of an options hash will generate a link to the referrer (a JavaScript back link
-
# will be used in place of a referrer if none exists). If +nil+ is passed as the name
-
# the value of the link itself will become the name.
-
#
-
# ==== Signatures
-
#
-
# link_to(body, url, html_options = {})
-
# # url is a String; you can use URL helpers like
-
# # posts_path
-
#
-
# link_to(body, url_options = {}, html_options = {})
-
# # url_options, except :method, is passed to url_for
-
#
-
# link_to(options = {}, html_options = {}) do
-
# # name
-
# end
-
#
-
# link_to(url, html_options = {}) do
-
# # name
-
# end
-
#
-
# ==== Options
-
# * <tt>:data</tt> - This option can be used to add custom data attributes.
-
# * <tt>method: symbol of HTTP verb</tt> - This modifier will dynamically
-
# create an HTML form and immediately submit the form for processing using
-
# the HTTP verb specified. Useful for having links perform a POST operation
-
# in dangerous actions like deleting a record (which search bots can follow
-
# while spidering your site). Supported verbs are <tt>:post</tt>, <tt>:delete</tt>, <tt>:patch</tt>, and <tt>:put</tt>.
-
# Note that if the user has JavaScript disabled, the request will fall back
-
# to using GET. If <tt>href: '#'</tt> is used and the user has JavaScript
-
# disabled clicking the link will have no effect. If you are relying on the
-
# POST behavior, you should check for it in your controller's action by using
-
# the request object's methods for <tt>post?</tt>, <tt>delete?</tt>, <tt>patch?</tt>, or <tt>put?</tt>.
-
# * <tt>remote: true</tt> - This will allow the unobtrusive JavaScript
-
# driver to make an Ajax request to the URL in question instead of following
-
# the link. The drivers each provide mechanisms for listening for the
-
# completion of the Ajax request and performing JavaScript operations once
-
# they're complete
-
#
-
# ==== Data attributes
-
#
-
# * <tt>confirm: 'question?'</tt> - This will allow the unobtrusive JavaScript
-
# driver to prompt with the question specified (in this case, the
-
# resulting text would be <tt>question?</tt>. If the user accepts, the
-
# link is processed normally, otherwise no action is taken.
-
# * <tt>:disable_with</tt> - Value of this parameter will be
-
# used as the value for a disabled version of the submit
-
# button when the form is submitted. This feature is provided
-
# by the unobtrusive JavaScript driver.
-
#
-
# ==== Examples
-
# Because it relies on +url_for+, +link_to+ supports both older-style controller/action/id arguments
-
# and newer RESTful routes. Current Rails style favors RESTful routes whenever possible, so base
-
# your application on resources and use
-
#
-
# link_to "Profile", profile_path(@profile)
-
# # => <a href="/profiles/1">Profile</a>
-
#
-
# or the even pithier
-
#
-
# link_to "Profile", @profile
-
# # => <a href="/profiles/1">Profile</a>
-
#
-
# in place of the older more verbose, non-resource-oriented
-
#
-
# link_to "Profile", controller: "profiles", action: "show", id: @profile
-
# # => <a href="/profiles/show/1">Profile</a>
-
#
-
# Similarly,
-
#
-
# link_to "Profiles", profiles_path
-
# # => <a href="/profiles">Profiles</a>
-
#
-
# is better than
-
#
-
# link_to "Profiles", controller: "profiles"
-
# # => <a href="/profiles">Profiles</a>
-
#
-
# You can use a block as well if your link target is hard to fit into the name parameter. ERB example:
-
#
-
# <%= link_to(@profile) do %>
-
# <strong><%= @profile.name %></strong> -- <span>Check it out!</span>
-
# <% end %>
-
# # => <a href="/profiles/1">
-
# <strong>David</strong> -- <span>Check it out!</span>
-
# </a>
-
#
-
# Classes and ids for CSS are easy to produce:
-
#
-
# link_to "Articles", articles_path, id: "news", class: "article"
-
# # => <a href="/articles" class="article" id="news">Articles</a>
-
#
-
# Be careful when using the older argument style, as an extra literal hash is needed:
-
#
-
# link_to "Articles", { controller: "articles" }, id: "news", class: "article"
-
# # => <a href="/articles" class="article" id="news">Articles</a>
-
#
-
# Leaving the hash off gives the wrong link:
-
#
-
# link_to "WRONG!", controller: "articles", id: "news", class: "article"
-
# # => <a href="/articles/index/news?class=article">WRONG!</a>
-
#
-
# +link_to+ can also produce links with anchors or query strings:
-
#
-
# link_to "Comment wall", profile_path(@profile, anchor: "wall")
-
# # => <a href="/profiles/1#wall">Comment wall</a>
-
#
-
# link_to "Ruby on Rails search", controller: "searches", query: "ruby on rails"
-
# # => <a href="/searches?query=ruby+on+rails">Ruby on Rails search</a>
-
#
-
# link_to "Nonsense search", searches_path(foo: "bar", baz: "quux")
-
# # => <a href="/searches?foo=bar&baz=quux">Nonsense search</a>
-
#
-
# The only option specific to +link_to+ (<tt>:method</tt>) is used as follows:
-
#
-
# link_to("Destroy", "http://www.example.com", method: :delete)
-
# # => <a href='http://www.example.com' rel="nofollow" data-method="delete">Destroy</a>
-
#
-
# You can also use custom data attributes using the <tt>:data</tt> option:
-
#
-
# link_to "Visit Other Site", "http://www.rubyonrails.org/", data: { confirm: "Are you sure?" }
-
# # => <a href="http://www.rubyonrails.org/" data-confirm="Are you sure?">Visit Other Site</a>
-
1
def link_to(name = nil, options = nil, html_options = nil, &block)
-
html_options, options, name = options, name, block if block_given?
-
options ||= {}
-
-
html_options = convert_options_to_data_attributes(options, html_options)
-
-
url = url_for(options)
-
html_options['href'] ||= url
-
-
content_tag(:a, name || url, html_options, &block)
-
end
-
-
# Generates a form containing a single button that submits to the URL created
-
# by the set of +options+. This is the safest method to ensure links that
-
# cause changes to your data are not triggered by search bots or accelerators.
-
# If the HTML button does not work with your layout, you can also consider
-
# using the +link_to+ method with the <tt>:method</tt> modifier as described in
-
# the +link_to+ documentation.
-
#
-
# By default, the generated form element has a class name of <tt>button_to</tt>
-
# to allow styling of the form itself and its children. This can be changed
-
# using the <tt>:form_class</tt> modifier within +html_options+. You can control
-
# the form submission and input element behavior using +html_options+.
-
# This method accepts the <tt>:method</tt> modifier described in the +link_to+ documentation.
-
# If no <tt>:method</tt> modifier is given, it will default to performing a POST operation.
-
# You can also disable the button by passing <tt>disabled: true</tt> in +html_options+.
-
# If you are using RESTful routes, you can pass the <tt>:method</tt>
-
# to change the HTTP verb used to submit the form.
-
#
-
# ==== Options
-
# The +options+ hash accepts the same options as +url_for+.
-
#
-
# There are a few special +html_options+:
-
# * <tt>:method</tt> - Symbol of HTTP verb. Supported verbs are <tt>:post</tt>, <tt>:get</tt>,
-
# <tt>:delete</tt>, <tt>:patch</tt>, and <tt>:put</tt>. By default it will be <tt>:post</tt>.
-
# * <tt>:disabled</tt> - If set to true, it will generate a disabled button.
-
# * <tt>:data</tt> - This option can be used to add custom data attributes.
-
# * <tt>:remote</tt> - If set to true, will allow the Unobtrusive JavaScript drivers to control the
-
# submit behavior. By default this behavior is an ajax submit.
-
# * <tt>:form</tt> - This hash will be form attributes
-
# * <tt>:form_class</tt> - This controls the class of the form within which the submit button will
-
# be placed
-
# * <tt>:params</tt> - Hash of parameters to be rendered as hidden fields within the form.
-
#
-
# ==== Data attributes
-
#
-
# * <tt>:confirm</tt> - This will use the unobtrusive JavaScript driver to
-
# prompt with the question specified. If the user accepts, the link is
-
# processed normally, otherwise no action is taken.
-
# * <tt>:disable_with</tt> - Value of this parameter will be
-
# used as the value for a disabled version of the submit
-
# button when the form is submitted. This feature is provided
-
# by the unobtrusive JavaScript driver.
-
#
-
# ==== Examples
-
# <%= button_to "New", action: "new" %>
-
# # => "<form method="post" action="/controller/new" class="button_to">
-
# # <div><input value="New" type="submit" /></div>
-
# # </form>"
-
#
-
# <%= button_to "New", new_articles_path %>
-
# # => "<form method="post" action="/articles/new" class="button_to">
-
# # <div><input value="New" type="submit" /></div>
-
# # </form>"
-
#
-
# <%= button_to [:make_happy, @user] do %>
-
# Make happy <strong><%= @user.name %></strong>
-
# <% end %>
-
# # => "<form method="post" action="/users/1/make_happy" class="button_to">
-
# # <div>
-
# # <button type="submit">
-
# # Make happy <strong><%= @user.name %></strong>
-
# # </button>
-
# # </div>
-
# # </form>"
-
#
-
# <%= button_to "New", { action: "new" }, form_class: "new-thing" %>
-
# # => "<form method="post" action="/controller/new" class="new-thing">
-
# # <div><input value="New" type="submit" /></div>
-
# # </form>"
-
#
-
#
-
# <%= button_to "Create", { action: "create" }, remote: true, form: { "data-type" => "json" } %>
-
# # => "<form method="post" action="/images/create" class="button_to" data-remote="true" data-type="json">
-
# # <div>
-
# # <input value="Create" type="submit" />
-
# # <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"/>
-
# # </div>
-
# # </form>"
-
#
-
#
-
# <%= button_to "Delete Image", { action: "delete", id: @image.id },
-
# method: :delete, data: { confirm: "Are you sure?" } %>
-
# # => "<form method="post" action="/images/delete/1" class="button_to">
-
# # <div>
-
# # <input type="hidden" name="_method" value="delete" />
-
# # <input data-confirm='Are you sure?' value="Delete Image" type="submit" />
-
# # <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"/>
-
# # </div>
-
# # </form>"
-
#
-
#
-
# <%= button_to('Destroy', 'http://www.example.com',
-
# method: "delete", remote: true, data: { confirm: 'Are you sure?', disable_with: 'loading...' }) %>
-
# # => "<form class='button_to' method='post' action='http://www.example.com' data-remote='true'>
-
# # <div>
-
# # <input name='_method' value='delete' type='hidden' />
-
# # <input value='Destroy' type='submit' data-disable-with='loading...' data-confirm='Are you sure?' />
-
# # <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"/>
-
# # </div>
-
# # </form>"
-
# #
-
1
def button_to(name = nil, options = nil, html_options = nil, &block)
-
html_options, options = options, name if block_given?
-
options ||= {}
-
html_options ||= {}
-
-
html_options = html_options.stringify_keys
-
convert_boolean_attributes!(html_options, %w(disabled))
-
-
url = options.is_a?(String) ? options : url_for(options)
-
remote = html_options.delete('remote')
-
params = html_options.delete('params')
-
-
method = html_options.delete('method').to_s
-
method_tag = BUTTON_TAG_METHOD_VERBS.include?(method) ? method_tag(method) : ''.html_safe
-
-
form_method = method == 'get' ? 'get' : 'post'
-
form_options = html_options.delete('form') || {}
-
form_options[:class] ||= html_options.delete('form_class') || 'button_to'
-
form_options.merge!(method: form_method, action: url)
-
form_options.merge!("data-remote" => "true") if remote
-
-
request_token_tag = form_method == 'post' ? token_tag : ''
-
-
html_options = convert_options_to_data_attributes(options, html_options)
-
html_options['type'] = 'submit'
-
-
button = if block_given?
-
content_tag('button', html_options, &block)
-
else
-
html_options['value'] = name || url
-
tag('input', html_options)
-
end
-
-
inner_tags = method_tag.safe_concat(button).safe_concat(request_token_tag)
-
if params
-
params.each do |param_name, value|
-
inner_tags.safe_concat tag(:input, type: "hidden", name: param_name, value: value.to_param)
-
end
-
end
-
content_tag('form', content_tag('div', inner_tags), form_options)
-
end
-
-
# Creates a link tag of the given +name+ using a URL created by the set of
-
# +options+ unless the current request URI is the same as the links, in
-
# which case only the name is returned (or the given block is yielded, if
-
# one exists). You can give +link_to_unless_current+ a block which will
-
# specialize the default behavior (e.g., show a "Start Here" link rather
-
# than the link's text).
-
#
-
# ==== Examples
-
# Let's say you have a navigation menu...
-
#
-
# <ul id="navbar">
-
# <li><%= link_to_unless_current("Home", { action: "index" }) %></li>
-
# <li><%= link_to_unless_current("About Us", { action: "about" }) %></li>
-
# </ul>
-
#
-
# If in the "about" action, it will render...
-
#
-
# <ul id="navbar">
-
# <li><a href="/controller/index">Home</a></li>
-
# <li>About Us</li>
-
# </ul>
-
#
-
# ...but if in the "index" action, it will render:
-
#
-
# <ul id="navbar">
-
# <li>Home</li>
-
# <li><a href="/controller/about">About Us</a></li>
-
# </ul>
-
#
-
# The implicit block given to +link_to_unless_current+ is evaluated if the current
-
# action is the action given. So, if we had a comments page and wanted to render a
-
# "Go Back" link instead of a link to the comments page, we could do something like this...
-
#
-
# <%=
-
# link_to_unless_current("Comment", { controller: "comments", action: "new" }) do
-
# link_to("Go back", { controller: "posts", action: "index" })
-
# end
-
# %>
-
1
def link_to_unless_current(name, options = {}, html_options = {}, &block)
-
link_to_unless current_page?(options), name, options, html_options, &block
-
end
-
-
# Creates a link tag of the given +name+ using a URL created by the set of
-
# +options+ unless +condition+ is true, in which case only the name is
-
# returned. To specialize the default behavior (i.e., show a login link rather
-
# than just the plaintext link text), you can pass a block that
-
# accepts the name or the full argument list for +link_to_unless+.
-
#
-
# ==== Examples
-
# <%= link_to_unless(@current_user.nil?, "Reply", { action: "reply" }) %>
-
# # If the user is logged in...
-
# # => <a href="/controller/reply/">Reply</a>
-
#
-
# <%=
-
# link_to_unless(@current_user.nil?, "Reply", { action: "reply" }) do |name|
-
# link_to(name, { controller: "accounts", action: "signup" })
-
# end
-
# %>
-
# # If the user is logged in...
-
# # => <a href="/controller/reply/">Reply</a>
-
# # If not...
-
# # => <a href="/accounts/signup">Reply</a>
-
1
def link_to_unless(condition, name, options = {}, html_options = {}, &block)
-
if condition
-
if block_given?
-
block.arity <= 1 ? capture(name, &block) : capture(name, options, html_options, &block)
-
else
-
ERB::Util.html_escape(name)
-
end
-
else
-
link_to(name, options, html_options)
-
end
-
end
-
-
# Creates a link tag of the given +name+ using a URL created by the set of
-
# +options+ if +condition+ is true, otherwise only the name is
-
# returned. To specialize the default behavior, you can pass a block that
-
# accepts the name or the full argument list for +link_to_unless+ (see the examples
-
# in +link_to_unless+).
-
#
-
# ==== Examples
-
# <%= link_to_if(@current_user.nil?, "Login", { controller: "sessions", action: "new" }) %>
-
# # If the user isn't logged in...
-
# # => <a href="/sessions/new/">Login</a>
-
#
-
# <%=
-
# link_to_if(@current_user.nil?, "Login", { controller: "sessions", action: "new" }) do
-
# link_to(@current_user.login, { controller: "accounts", action: "show", id: @current_user })
-
# end
-
# %>
-
# # If the user isn't logged in...
-
# # => <a href="/sessions/new/">Login</a>
-
# # If they are logged in...
-
# # => <a href="/accounts/show/3">my_username</a>
-
1
def link_to_if(condition, name, options = {}, html_options = {}, &block)
-
link_to_unless !condition, name, options, html_options, &block
-
end
-
-
# Creates a mailto link tag to the specified +email_address+, which is
-
# also used as the name of the link unless +name+ is specified. Additional
-
# HTML attributes for the link can be passed in +html_options+.
-
#
-
# +mail_to+ has several methods for customizing the email itself by
-
# passing special keys to +html_options+.
-
#
-
# ==== Options
-
# * <tt>:subject</tt> - Preset the subject line of the email.
-
# * <tt>:body</tt> - Preset the body of the email.
-
# * <tt>:cc</tt> - Carbon Copy additional recipients on the email.
-
# * <tt>:bcc</tt> - Blind Carbon Copy additional recipients on the email.
-
#
-
# ==== Obfuscation
-
# Prior to Rails 4.0, +mail_to+ provided options for encoding the address
-
# in order to hinder email harvesters. To take advantage of these options,
-
# install the +actionview-encoded_mail_to+ gem.
-
#
-
# ==== Examples
-
# mail_to "me@domain.com"
-
# # => <a href="mailto:me@domain.com">me@domain.com</a>
-
#
-
# mail_to "me@domain.com", "My email"
-
# # => <a href="mailto:me@domain.com">My email</a>
-
#
-
# mail_to "me@domain.com", "My email", cc: "ccaddress@domain.com",
-
# subject: "This is an example email"
-
# # => <a href="mailto:me@domain.com?cc=ccaddress@domain.com&subject=This%20is%20an%20example%20email">My email</a>
-
#
-
# You can use a block as well if your link target is hard to fit into the name parameter. ERB example:
-
#
-
# <%= mail_to "me@domain.com" do %>
-
# <strong>Email me:</strong> <span>me@domain.com</span>
-
# <% end %>
-
# # => <a href="mailto:me@domain.com">
-
# <strong>Email me:</strong> <span>me@domain.com</span>
-
# </a>
-
1
def mail_to(email_address, name = nil, html_options = {}, &block)
-
email_address = ERB::Util.html_escape(email_address)
-
-
html_options, name = name, nil if block_given?
-
html_options = (html_options || {}).stringify_keys
-
-
extras = %w{ cc bcc body subject }.map! { |item|
-
option = html_options.delete(item) || next
-
"#{item}=#{Rack::Utils.escape_path(option)}"
-
}.compact
-
extras = extras.empty? ? '' : '?' + ERB::Util.html_escape(extras.join('&'))
-
-
html_options["href"] = "mailto:#{email_address}#{extras}".html_safe
-
-
content_tag(:a, name || email_address.html_safe, html_options, &block)
-
end
-
-
# True if the current request URI was generated by the given +options+.
-
#
-
# ==== Examples
-
# Let's say we're in the <tt>http://www.example.com/shop/checkout?order=desc</tt> action.
-
#
-
# current_page?(action: 'process')
-
# # => false
-
#
-
# current_page?(controller: 'shop', action: 'checkout')
-
# # => true
-
#
-
# current_page?(controller: 'shop', action: 'checkout', order: 'asc')
-
# # => false
-
#
-
# current_page?(action: 'checkout')
-
# # => true
-
#
-
# current_page?(controller: 'library', action: 'checkout')
-
# # => false
-
#
-
# current_page?('http://www.example.com/shop/checkout')
-
# # => true
-
#
-
# current_page?('/shop/checkout')
-
# # => true
-
#
-
# Let's say we're in the <tt>http://www.example.com/shop/checkout?order=desc&page=1</tt> action.
-
#
-
# current_page?(action: 'process')
-
# # => false
-
#
-
# current_page?(controller: 'shop', action: 'checkout')
-
# # => true
-
#
-
# current_page?(controller: 'shop', action: 'checkout', order: 'desc', page: '1')
-
# # => true
-
#
-
# current_page?(controller: 'shop', action: 'checkout', order: 'desc', page: '2')
-
# # => false
-
#
-
# current_page?(controller: 'shop', action: 'checkout', order: 'desc')
-
# # => false
-
#
-
# current_page?(action: 'checkout')
-
# # => true
-
#
-
# current_page?(controller: 'library', action: 'checkout')
-
# # => false
-
#
-
# Let's say we're in the <tt>http://www.example.com/products</tt> action with method POST in case of invalid product.
-
#
-
# current_page?(controller: 'product', action: 'index')
-
# # => false
-
#
-
1
def current_page?(options)
-
unless request
-
raise "You cannot use helpers that need to determine the current " \
-
"page unless your view context provides a Request object " \
-
"in a #request method"
-
end
-
-
return false unless request.get? || request.head?
-
-
url_string = URI.parser.unescape(url_for(options)).force_encoding(Encoding::BINARY)
-
-
# We ignore any extra parameters in the request_uri if the
-
# submitted url doesn't have any either. This lets the function
-
# work with things like ?order=asc
-
request_uri = url_string.index("?") ? request.fullpath : request.path
-
request_uri = URI.parser.unescape(request_uri).force_encoding(Encoding::BINARY)
-
-
if url_string =~ /^\w+:\/\//
-
url_string == "#{request.protocol}#{request.host_with_port}#{request_uri}"
-
else
-
url_string == request_uri
-
end
-
end
-
-
1
private
-
1
def convert_options_to_data_attributes(options, html_options)
-
if html_options
-
html_options = html_options.stringify_keys
-
html_options['data-remote'] = 'true' if link_to_remote_options?(options) || link_to_remote_options?(html_options)
-
-
method = html_options.delete('method')
-
-
add_method_to_attributes!(html_options, method) if method
-
-
html_options
-
else
-
link_to_remote_options?(options) ? {'data-remote' => 'true'} : {}
-
end
-
end
-
-
1
def link_to_remote_options?(options)
-
if options.is_a?(Hash)
-
options.delete('remote') || options.delete(:remote)
-
end
-
end
-
-
1
def add_method_to_attributes!(html_options, method)
-
if method && method.to_s.downcase != "get" && html_options["rel"] !~ /nofollow/
-
html_options["rel"] = "#{html_options["rel"]} nofollow".lstrip
-
end
-
html_options["data-method"] = method
-
end
-
-
# Processes the +html_options+ hash, converting the boolean
-
# attributes from true/false form into the form required by
-
# HTML/XHTML. (An attribute is considered to be boolean if
-
# its name is listed in the given +bool_attrs+ array.)
-
#
-
# More specifically, for each boolean attribute in +html_options+
-
# given as:
-
#
-
# "attr" => bool_value
-
#
-
# if the associated +bool_value+ evaluates to true, it is
-
# replaced with the attribute's name; otherwise the attribute is
-
# removed from the +html_options+ hash. (See the XHTML 1.0 spec,
-
# section 4.5 "Attribute Minimization" for more:
-
# http://www.w3.org/TR/xhtml1/#h-4.5)
-
#
-
# Returns the updated +html_options+ hash, which is also modified
-
# in place.
-
#
-
# Example:
-
#
-
# convert_boolean_attributes!( html_options,
-
# %w( checked disabled readonly ) )
-
1
def convert_boolean_attributes!(html_options, bool_attrs)
-
bool_attrs.each { |x| html_options[x] = x if html_options.delete(x) }
-
html_options
-
end
-
-
1
def token_tag(token=nil)
-
if token != false && protect_against_forgery?
-
token ||= form_authenticity_token
-
tag(:input, type: "hidden", name: request_forgery_protection_token.to_s, value: token)
-
else
-
''
-
end
-
end
-
-
1
def method_tag(method)
-
tag('input', type: 'hidden', name: '_method', value: method.to_s)
-
end
-
end
-
end
-
end
-
1
require "action_view/rendering"
-
1
require "active_support/core_ext/module/remove_method"
-
-
1
module ActionView
-
# Layouts reverse the common pattern of including shared headers and footers in many templates to isolate changes in
-
# repeated setups. The inclusion pattern has pages that look like this:
-
#
-
# <%= render "shared/header" %>
-
# Hello World
-
# <%= render "shared/footer" %>
-
#
-
# This approach is a decent way of keeping common structures isolated from the changing content, but it's verbose
-
# and if you ever want to change the structure of these two includes, you'll have to change all the templates.
-
#
-
# With layouts, you can flip it around and have the common structure know where to insert changing content. This means
-
# that the header and footer are only mentioned in one place, like this:
-
#
-
# // The header part of this layout
-
# <%= yield %>
-
# // The footer part of this layout
-
#
-
# And then you have content pages that look like this:
-
#
-
# hello world
-
#
-
# At rendering time, the content page is computed and then inserted in the layout, like this:
-
#
-
# // The header part of this layout
-
# hello world
-
# // The footer part of this layout
-
#
-
# == Accessing shared variables
-
#
-
# Layouts have access to variables specified in the content pages and vice versa. This allows you to have layouts with
-
# references that won't materialize before rendering time:
-
#
-
# <h1><%= @page_title %></h1>
-
# <%= yield %>
-
#
-
# ...and content pages that fulfill these references _at_ rendering time:
-
#
-
# <% @page_title = "Welcome" %>
-
# Off-world colonies offers you a chance to start a new life
-
#
-
# The result after rendering is:
-
#
-
# <h1>Welcome</h1>
-
# Off-world colonies offers you a chance to start a new life
-
#
-
# == Layout assignment
-
#
-
# You can either specify a layout declaratively (using the #layout class method) or give
-
# it the same name as your controller, and place it in <tt>app/views/layouts</tt>.
-
# If a subclass does not have a layout specified, it inherits its layout using normal Ruby inheritance.
-
#
-
# For instance, if you have PostsController and a template named <tt>app/views/layouts/posts.html.erb</tt>,
-
# that template will be used for all actions in PostsController and controllers inheriting
-
# from PostsController.
-
#
-
# If you use a module, for instance Weblog::PostsController, you will need a template named
-
# <tt>app/views/layouts/weblog/posts.html.erb</tt>.
-
#
-
# Since all your controllers inherit from ApplicationController, they will use
-
# <tt>app/views/layouts/application.html.erb</tt> if no other layout is specified
-
# or provided.
-
#
-
# == Inheritance Examples
-
#
-
# class BankController < ActionController::Base
-
# # bank.html.erb exists
-
#
-
# class ExchangeController < BankController
-
# # exchange.html.erb exists
-
#
-
# class CurrencyController < BankController
-
#
-
# class InformationController < BankController
-
# layout "information"
-
#
-
# class TellerController < InformationController
-
# # teller.html.erb exists
-
#
-
# class EmployeeController < InformationController
-
# # employee.html.erb exists
-
# layout nil
-
#
-
# class VaultController < BankController
-
# layout :access_level_layout
-
#
-
# class TillController < BankController
-
# layout false
-
#
-
# In these examples, we have three implicit lookup scenarios:
-
# * The BankController uses the "bank" layout.
-
# * The ExchangeController uses the "exchange" layout.
-
# * The CurrencyController inherits the layout from BankController.
-
#
-
# However, when a layout is explicitly set, the explicitly set layout wins:
-
# * The InformationController uses the "information" layout, explicitly set.
-
# * The TellerController also uses the "information" layout, because the parent explicitly set it.
-
# * The EmployeeController uses the "employee" layout, because it set the layout to nil, resetting the parent configuration.
-
# * The VaultController chooses a layout dynamically by calling the <tt>access_level_layout</tt> method.
-
# * The TillController does not use a layout at all.
-
#
-
# == Types of layouts
-
#
-
# Layouts are basically just regular templates, but the name of this template needs not be specified statically. Sometimes
-
# you want to alternate layouts depending on runtime information, such as whether someone is logged in or not. This can
-
# be done either by specifying a method reference as a symbol or using an inline method (as a proc).
-
#
-
# The method reference is the preferred approach to variable layouts and is used like this:
-
#
-
# class WeblogController < ActionController::Base
-
# layout :writers_and_readers
-
#
-
# def index
-
# # fetching posts
-
# end
-
#
-
# private
-
# def writers_and_readers
-
# logged_in? ? "writer_layout" : "reader_layout"
-
# end
-
# end
-
#
-
# Now when a new request for the index action is processed, the layout will vary depending on whether the person accessing
-
# is logged in or not.
-
#
-
# If you want to use an inline method, such as a proc, do something like this:
-
#
-
# class WeblogController < ActionController::Base
-
# layout proc { |controller| controller.logged_in? ? "writer_layout" : "reader_layout" }
-
# end
-
#
-
# If an argument isn't given to the proc, it's evaluated in the context of
-
# the current controller anyway.
-
#
-
# class WeblogController < ActionController::Base
-
# layout proc { logged_in? ? "writer_layout" : "reader_layout" }
-
# end
-
#
-
# Of course, the most common way of specifying a layout is still just as a plain template name:
-
#
-
# class WeblogController < ActionController::Base
-
# layout "weblog_standard"
-
# end
-
#
-
# The template will be looked always in <tt>app/views/layouts/</tt> folder. But you can point
-
# <tt>layouts</tt> folder direct also. <tt>layout "layouts/demo"</tt> is the same as <tt>layout "demo"</tt>.
-
#
-
# Setting the layout to nil forces it to be looked up in the filesystem and fallbacks to the parent behavior if none exists.
-
# Setting it to nil is useful to re-enable template lookup overriding a previous configuration set in the parent:
-
#
-
# class ApplicationController < ActionController::Base
-
# layout "application"
-
# end
-
#
-
# class PostsController < ApplicationController
-
# # Will use "application" layout
-
# end
-
#
-
# class CommentsController < ApplicationController
-
# # Will search for "comments" layout and fallback "application" layout
-
# layout nil
-
# end
-
#
-
# == Conditional layouts
-
#
-
# If you have a layout that by default is applied to all the actions of a controller, you still have the option of rendering
-
# a given action or set of actions without a layout, or restricting a layout to only a single action or a set of actions. The
-
# <tt>:only</tt> and <tt>:except</tt> options can be passed to the layout call. For example:
-
#
-
# class WeblogController < ActionController::Base
-
# layout "weblog_standard", except: :rss
-
#
-
# # ...
-
#
-
# end
-
#
-
# This will assign "weblog_standard" as the WeblogController's layout for all actions except for the +rss+ action, which will
-
# be rendered directly, without wrapping a layout around the rendered view.
-
#
-
# Both the <tt>:only</tt> and <tt>:except</tt> condition can accept an arbitrary number of method references, so
-
# #<tt>except: [ :rss, :text_only ]</tt> is valid, as is <tt>except: :rss</tt>.
-
#
-
# == Using a different layout in the action render call
-
#
-
# If most of your actions use the same layout, it makes perfect sense to define a controller-wide layout as described above.
-
# Sometimes you'll have exceptions where one action wants to use a different layout than the rest of the controller.
-
# You can do this by passing a <tt>:layout</tt> option to the <tt>render</tt> call. For example:
-
#
-
# class WeblogController < ActionController::Base
-
# layout "weblog_standard"
-
#
-
# def help
-
# render action: "help", layout: "help"
-
# end
-
# end
-
#
-
# This will override the controller-wide "weblog_standard" layout, and will render the help action with the "help" layout instead.
-
1
module Layouts
-
1
extend ActiveSupport::Concern
-
-
1
include ActionView::Rendering
-
-
1
included do
-
2
class_attribute :_layout, :_layout_conditions, :instance_accessor => false
-
2
self._layout = nil
-
2
self._layout_conditions = {}
-
2
_write_layout_method
-
end
-
-
1
delegate :_layout_conditions, to: :class
-
-
1
module ClassMethods
-
1
def inherited(klass) # :nodoc:
-
1
super
-
1
klass._write_layout_method
-
end
-
-
# This module is mixed in if layout conditions are provided. This means
-
# that if no layout conditions are used, this method is not used
-
1
module LayoutConditions # :nodoc:
-
1
private
-
-
# Determines whether the current action has a layout definition by
-
# checking the action name against the :only and :except conditions
-
# set by the <tt>layout</tt> method.
-
#
-
# ==== Returns
-
# * <tt> Boolean</tt> - True if the action has a layout definition, false otherwise.
-
1
def _conditional_layout?
-
return unless super
-
-
conditions = _layout_conditions
-
-
if only = conditions[:only]
-
only.include?(action_name)
-
elsif except = conditions[:except]
-
!except.include?(action_name)
-
else
-
true
-
end
-
end
-
end
-
-
# Specify the layout to use for this class.
-
#
-
# If the specified layout is a:
-
# String:: the String is the template name
-
# Symbol:: call the method specified by the symbol, which will return the template name
-
# false:: There is no layout
-
# true:: raise an ArgumentError
-
# nil:: Force default layout behavior with inheritance
-
#
-
# ==== Parameters
-
# * <tt>layout</tt> - The layout to use.
-
#
-
# ==== Options (conditions)
-
# * :only - A list of actions to apply this layout to.
-
# * :except - Apply this layout to all actions but this one.
-
1
def layout(layout, conditions = {})
-
include LayoutConditions unless conditions.empty?
-
-
conditions.each {|k, v| conditions[k] = Array(v).map {|a| a.to_s} }
-
self._layout_conditions = conditions
-
-
self._layout = layout
-
_write_layout_method
-
end
-
-
# Creates a _layout method to be called by _default_layout .
-
#
-
# If a layout is not explicitly mentioned then look for a layout with the controller's name.
-
# if nothing is found then try same procedure to find super class's layout.
-
1
def _write_layout_method # :nodoc:
-
3
remove_possible_method(:_layout)
-
-
3
prefixes = _implied_layout_name =~ /\blayouts/ ? [] : ["layouts"]
-
3
default_behavior = "lookup_context.find_all('#{_implied_layout_name}', #{prefixes.inspect}).first || super"
-
3
name_clause = if name
-
3
default_behavior
-
else
-
<<-RUBY
-
super
-
RUBY
-
end
-
-
3
layout_definition = case _layout
-
when String
-
_layout.inspect
-
when Symbol
-
<<-RUBY
-
#{_layout}.tap do |layout|
-
return #{default_behavior} if layout.nil?
-
unless layout.is_a?(String) || !layout
-
raise ArgumentError, "Your layout method :#{_layout} returned \#{layout}. It " \
-
"should have returned a String, false, or nil"
-
end
-
end
-
RUBY
-
when Proc
-
define_method :_layout_from_proc, &_layout
-
protected :_layout_from_proc
-
<<-RUBY
-
result = _layout_from_proc(#{_layout.arity == 0 ? '' : 'self'})
-
return #{default_behavior} if result.nil?
-
result
-
RUBY
-
when false
-
nil
-
when true
-
raise ArgumentError, "Layouts must be specified as a String, Symbol, Proc, false, or nil"
-
when nil
-
3
name_clause
-
end
-
-
3
self.class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def _layout
-
if _conditional_layout?
-
#{layout_definition}
-
else
-
#{name_clause}
-
end
-
end
-
private :_layout
-
RUBY
-
end
-
-
1
private
-
-
# If no layout is supplied, look for a template named the return
-
# value of this method.
-
#
-
# ==== Returns
-
# * <tt>String</tt> - A template name
-
1
def _implied_layout_name # :nodoc:
-
6
controller_path
-
end
-
end
-
-
1
def _normalize_options(options) # :nodoc:
-
super
-
-
if _include_layout?(options)
-
layout = options.delete(:layout) { :default }
-
options[:layout] = _layout_for_option(layout)
-
end
-
end
-
-
1
attr_internal_writer :action_has_layout
-
-
1
def initialize(*) # :nodoc:
-
@_action_has_layout = true
-
super
-
end
-
-
# Controls whether an action should be rendered using a layout.
-
# If you want to disable any <tt>layout</tt> settings for the
-
# current action so that it is rendered without a layout then
-
# either override this method in your controller to return false
-
# for that action or set the <tt>action_has_layout</tt> attribute
-
# to false before rendering.
-
1
def action_has_layout?
-
@_action_has_layout
-
end
-
-
1
private
-
-
1
def _conditional_layout?
-
true
-
end
-
-
# This will be overwritten by _write_layout_method
-
1
def _layout; end
-
-
# Determine the layout for a given name, taking into account the name type.
-
#
-
# ==== Parameters
-
# * <tt>name</tt> - The name of the template
-
1
def _layout_for_option(name)
-
case name
-
when String then _normalize_layout(name)
-
when Proc then name
-
when true then Proc.new { _default_layout(true) }
-
when :default then Proc.new { _default_layout(false) }
-
when false, nil then nil
-
else
-
raise ArgumentError,
-
"String, Proc, :default, true, or false, expected for `layout'; you passed #{name.inspect}"
-
end
-
end
-
-
1
def _normalize_layout(value)
-
value.is_a?(String) && value !~ /\blayouts/ ? "layouts/#{value}" : value
-
end
-
-
# Returns the default layout for this controller.
-
# Optionally raises an exception if the layout could not be found.
-
#
-
# ==== Parameters
-
# * <tt>require_layout</tt> - If set to true and layout is not found,
-
# an ArgumentError exception is raised (defaults to false)
-
#
-
# ==== Returns
-
# * <tt>template</tt> - The template object for the default layout (or nil)
-
1
def _default_layout(require_layout = false)
-
begin
-
value = _layout if action_has_layout?
-
rescue NameError => e
-
raise e, "Could not render layout: #{e.message}"
-
end
-
-
if require_layout && action_has_layout? && !value
-
raise ArgumentError,
-
"There was no default layout for #{self.class} in #{view_paths.inspect}"
-
end
-
-
_normalize_layout(value)
-
end
-
-
1
def _include_layout?(options)
-
(options.keys & [:body, :text, :plain, :html, :inline, :partial]).empty? || options.key?(:layout)
-
end
-
end
-
end
-
1
require 'active_support/log_subscriber'
-
-
1
module ActionView
-
# = Action View Log Subscriber
-
#
-
# Provides functionality so that Rails can output logs from Action View.
-
1
class LogSubscriber < ActiveSupport::LogSubscriber
-
1
VIEWS_PATTERN = /^app\/views\//
-
-
1
def initialize
-
1
@root = nil
-
1
super
-
end
-
-
1
def render_template(event)
-
return unless logger.info?
-
message = " Rendered #{from_rails_root(event.payload[:identifier])}"
-
message << " within #{from_rails_root(event.payload[:layout])}" if event.payload[:layout]
-
message << " (#{event.duration.round(1)}ms)"
-
info(message)
-
end
-
1
alias :render_partial :render_template
-
1
alias :render_collection :render_template
-
-
1
def logger
-
ActionView::Base.logger
-
end
-
-
1
protected
-
-
1
EMPTY = ''
-
1
def from_rails_root(string)
-
string = string.sub(rails_root, EMPTY)
-
string.sub!(VIEWS_PATTERN, EMPTY)
-
string
-
end
-
-
1
def rails_root
-
@root ||= "#{Rails.root}/"
-
end
-
end
-
end
-
-
1
ActionView::LogSubscriber.attach_to :action_view
-
1
require 'thread_safe'
-
1
require 'active_support/core_ext/module/remove_method'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'action_view/template/resolver'
-
-
1
module ActionView
-
# = Action View Lookup Context
-
#
-
# LookupContext is the object responsible to hold all information required to lookup
-
# templates, i.e. view paths and details. The LookupContext is also responsible to
-
# generate a key, given to view paths, used in the resolver cache lookup. Since
-
# this key is generated just once during the request, it speeds up all cache accesses.
-
1
class LookupContext #:nodoc:
-
1
attr_accessor :prefixes, :rendered_format
-
-
1
mattr_accessor :fallbacks
-
1
@@fallbacks = FallbackFileSystemResolver.instances
-
-
1
mattr_accessor :registered_details
-
1
self.registered_details = []
-
-
1
def self.register_detail(name, options = {}, &block)
-
4
self.registered_details << name
-
14
initialize = registered_details.map { |n| "@details[:#{n}] = details[:#{n}] || default_#{n}" }
-
-
4
Accessors.send :define_method, :"default_#{name}", &block
-
4
Accessors.module_eval <<-METHOD, __FILE__, __LINE__ + 1
-
def #{name}
-
@details.fetch(:#{name}, [])
-
end
-
-
def #{name}=(value)
-
value = value.present? ? Array(value) : default_#{name}
-
_set_detail(:#{name}, value) if value != @details[:#{name}]
-
end
-
-
remove_possible_method :initialize_details
-
def initialize_details(details)
-
#{initialize.join("\n")}
-
end
-
METHOD
-
end
-
-
# Holds accessors for the registered details.
-
1
module Accessors #:nodoc:
-
end
-
-
1
register_detail(:locale) do
-
locales = [I18n.locale]
-
locales.concat(I18n.fallbacks[I18n.locale]) if I18n.respond_to? :fallbacks
-
locales << I18n.default_locale
-
locales.uniq!
-
locales
-
end
-
1
register_detail(:formats) { ActionView::Base.default_formats || [:html, :text, :js, :css, :xml, :json] }
-
1
register_detail(:variants) { [] }
-
1
register_detail(:handlers){ Template::Handlers.extensions }
-
-
1
class DetailsKey #:nodoc:
-
1
alias :eql? :equal?
-
1
alias :object_hash :hash
-
-
1
attr_reader :hash
-
1
@details_keys = ThreadSafe::Cache.new
-
-
1
def self.get(details)
-
if details[:formats]
-
details = details.dup
-
syms = Set.new Mime::SET.symbols
-
details[:formats] = details[:formats].select { |v|
-
syms.include? v
-
}
-
end
-
@details_keys[details] ||= new
-
end
-
-
1
def self.clear
-
@details_keys.clear
-
end
-
-
1
def initialize
-
@hash = object_hash
-
end
-
end
-
-
# Add caching behavior on top of Details.
-
1
module DetailsCache
-
1
attr_accessor :cache
-
-
# Calculate the details key. Remove the handlers from calculation to improve performance
-
# since the user cannot modify it explicitly.
-
1
def details_key #:nodoc:
-
@details_key ||= DetailsKey.get(@details) if @cache
-
end
-
-
# Temporary skip passing the details_key forward.
-
1
def disable_cache
-
old_value, @cache = @cache, false
-
yield
-
ensure
-
@cache = old_value
-
end
-
-
1
protected
-
-
1
def _set_detail(key, value)
-
@details = @details.dup if @details_key
-
@details_key = nil
-
@details[key] = value
-
end
-
end
-
-
# Helpers related to template lookup using the lookup context information.
-
1
module ViewPaths
-
1
attr_reader :view_paths, :html_fallback_for_js
-
-
# Whenever setting view paths, makes a copy so we can manipulate then in
-
# instance objects as we wish.
-
1
def view_paths=(paths)
-
@view_paths = ActionView::PathSet.new(Array(paths))
-
end
-
-
1
def find(name, prefixes = [], partial = false, keys = [], options = {})
-
@view_paths.find(*args_for_lookup(name, prefixes, partial, keys, options))
-
end
-
1
alias :find_template :find
-
-
1
def find_all(name, prefixes = [], partial = false, keys = [], options = {})
-
@view_paths.find_all(*args_for_lookup(name, prefixes, partial, keys, options))
-
end
-
-
1
def exists?(name, prefixes = [], partial = false, keys = [], options = {})
-
@view_paths.exists?(*args_for_lookup(name, prefixes, partial, keys, options))
-
end
-
1
alias :template_exists? :exists?
-
-
# Add fallbacks to the view paths. Useful in cases you are rendering a :file.
-
1
def with_fallbacks
-
added_resolvers = 0
-
self.class.fallbacks.each do |resolver|
-
next if view_paths.include?(resolver)
-
view_paths.push(resolver)
-
added_resolvers += 1
-
end
-
yield
-
ensure
-
added_resolvers.times { view_paths.pop }
-
end
-
-
1
protected
-
-
1
def args_for_lookup(name, prefixes, partial, keys, details_options) #:nodoc:
-
name, prefixes = normalize_name(name, prefixes)
-
details, details_key = detail_args_for(details_options)
-
[name, prefixes, partial || false, details, details_key, keys]
-
end
-
-
# Compute details hash and key according to user options (e.g. passed from #render).
-
1
def detail_args_for(options)
-
return @details, details_key if options.empty? # most common path.
-
user_details = @details.merge(options)
-
-
if @cache
-
details_key = DetailsKey.get(user_details)
-
else
-
details_key = nil
-
end
-
-
[user_details, details_key]
-
end
-
-
# Support legacy foo.erb names even though we now ignore .erb
-
# as well as incorrectly putting part of the path in the template
-
# name instead of the prefix.
-
1
def normalize_name(name, prefixes) #:nodoc:
-
prefixes = prefixes.presence
-
parts = name.to_s.split('/')
-
parts.shift if parts.first.empty?
-
name = parts.pop
-
-
return name, prefixes || [""] if parts.empty?
-
-
parts = parts.join('/')
-
prefixes = prefixes ? prefixes.map { |p| "#{p}/#{parts}" } : [parts]
-
-
return name, prefixes
-
end
-
end
-
-
1
include Accessors
-
1
include DetailsCache
-
1
include ViewPaths
-
-
1
def initialize(view_paths, details = {}, prefixes = [])
-
@details, @details_key = {}, nil
-
@skip_default_locale = false
-
@cache = true
-
@prefixes = prefixes
-
@rendered_format = nil
-
-
self.view_paths = view_paths
-
initialize_details(details)
-
end
-
-
# Override formats= to expand ["*/*"] values and automatically
-
# add :html as fallback to :js.
-
1
def formats=(values)
-
if values
-
values.concat(default_formats) if values.delete "*/*"
-
if values == [:js]
-
values << :html
-
@html_fallback_for_js = true
-
end
-
end
-
super(values)
-
end
-
-
# Do not use the default locale on template lookup.
-
1
def skip_default_locale!
-
@skip_default_locale = true
-
self.locale = nil
-
end
-
-
# Override locale to return a symbol instead of array.
-
1
def locale
-
@details[:locale].first
-
end
-
-
# Overload locale= to also set the I18n.locale. If the current I18n.config object responds
-
# to original_config, it means that it's has a copy of the original I18n configuration and it's
-
# acting as proxy, which we need to skip.
-
1
def locale=(value)
-
if value
-
config = I18n.config.respond_to?(:original_config) ? I18n.config.original_config : I18n.config
-
config.locale = value
-
end
-
-
super(@skip_default_locale ? I18n.locale : default_locale)
-
end
-
-
# A method which only uses the first format in the formats array for layout lookup.
-
1
def with_layout_format
-
if formats.size == 1
-
yield
-
else
-
old_formats = formats
-
_set_detail(:formats, formats[0,1])
-
-
begin
-
yield
-
ensure
-
_set_detail(:formats, old_formats)
-
end
-
end
-
end
-
end
-
end
-
1
module ActionView
-
1
module ModelNaming
-
# Converts the given object to an ActiveModel compliant one.
-
1
def convert_to_model(object)
-
object.respond_to?(:to_model) ? object.to_model : object
-
end
-
-
1
def model_name_from_record_or_class(record_or_class)
-
(record_or_class.is_a?(Class) ? record_or_class : convert_to_model(record_or_class).class).model_name
-
end
-
end
-
end
-
1
module ActionView #:nodoc:
-
# = Action View PathSet
-
#
-
# This class is used to store and access paths in Action View. A number of
-
# operations are defined so that you can search among the paths in this
-
# set and also perform operations on other +PathSet+ objects.
-
#
-
# A +LookupContext+ will use a +PathSet+ to store the paths in its context.
-
1
class PathSet #:nodoc:
-
1
include Enumerable
-
-
1
attr_reader :paths
-
-
1
delegate :[], :include?, :pop, :size, :each, to: :paths
-
-
1
def initialize(paths = [])
-
8
@paths = typecast paths
-
end
-
-
1
def initialize_copy(other)
-
@paths = other.paths.dup
-
self
-
end
-
-
1
def to_ary
-
6
paths.dup
-
end
-
-
1
def compact
-
PathSet.new paths.compact
-
end
-
-
1
def +(array)
-
PathSet.new(paths + array)
-
end
-
-
1
%w(<< concat push insert unshift).each do |method|
-
5
class_eval <<-METHOD, __FILE__, __LINE__ + 1
-
def #{method}(*args)
-
paths.#{method}(*typecast(args))
-
end
-
METHOD
-
end
-
-
1
def find(*args)
-
find_all(*args).first || raise(MissingTemplate.new(self, *args))
-
end
-
-
1
def find_all(path, prefixes = [], *args)
-
prefixes = [prefixes] if String === prefixes
-
prefixes.each do |prefix|
-
paths.each do |resolver|
-
templates = resolver.find_all(path, prefix, *args)
-
return templates unless templates.empty?
-
end
-
end
-
[]
-
end
-
-
1
def exists?(path, prefixes, *args)
-
find_all(path, prefixes, *args).any?
-
end
-
-
1
private
-
-
1
def typecast(paths)
-
8
paths.map do |path|
-
12
case path
-
when Pathname, String
-
6
OptimizedFileSystemResolver.new path.to_s
-
else
-
6
path
-
end
-
end
-
end
-
end
-
end
-
1
require "action_view"
-
1
require "rails"
-
-
1
module ActionView
-
# = Action View Railtie
-
1
class Railtie < Rails::Railtie # :nodoc:
-
1
config.action_view = ActiveSupport::OrderedOptions.new
-
1
config.action_view.embed_authenticity_token_in_remote_forms = false
-
-
1
config.eager_load_namespaces << ActionView
-
-
1
initializer "action_view.embed_authenticity_token_in_remote_forms" do |app|
-
1
ActiveSupport.on_load(:action_view) do
-
1
ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms =
-
app.config.action_view.delete(:embed_authenticity_token_in_remote_forms)
-
end
-
end
-
-
1
initializer "action_view.logger" do
-
2
ActiveSupport.on_load(:action_view) { self.logger ||= Rails.logger }
-
end
-
-
1
initializer "action_view.set_configs" do |app|
-
1
ActiveSupport.on_load(:action_view) do
-
1
app.config.action_view.each do |k,v|
-
send "#{k}=", v
-
end
-
end
-
end
-
-
1
initializer "action_view.caching" do |app|
-
1
ActiveSupport.on_load(:action_view) do
-
1
if app.config.action_view.cache_template_loading.nil?
-
1
ActionView::Resolver.caching = app.config.cache_classes
-
end
-
end
-
end
-
-
1
initializer "action_view.setup_action_pack" do |app|
-
1
ActiveSupport.on_load(:action_controller) do
-
1
ActionView::RoutingUrlFor.send(:include, ActionDispatch::Routing::UrlFor)
-
end
-
end
-
-
1
rake_tasks do
-
load "action_view/tasks/dependencies.rake"
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module'
-
1
require 'action_view/model_naming'
-
-
1
module ActionView
-
# The record identifier encapsulates a number of naming conventions for dealing with records, like Active Records or
-
# pretty much any other model type that has an id. These patterns are then used to try elevate the view actions to
-
# a higher logical level.
-
#
-
# # routes
-
# resources :posts
-
#
-
# # view
-
# <%= div_for(post) do %> <div id="post_45" class="post">
-
# <%= post.body %> What a wonderful world!
-
# <% end %> </div>
-
#
-
# # controller
-
# def update
-
# post = Post.find(params[:id])
-
# post.update(params[:post])
-
#
-
# redirect_to(post) # Calls polymorphic_url(post) which in turn calls post_url(post)
-
# end
-
#
-
# As the example above shows, you can stop caring to a large extent what the actual id of the post is.
-
# You just know that one is being assigned and that the subsequent calls in redirect_to expect that
-
# same naming convention and allows you to write less code if you follow it.
-
1
module RecordIdentifier
-
1
extend self
-
1
extend ModelNaming
-
-
1
include ModelNaming
-
-
1
JOIN = '_'.freeze
-
1
NEW = 'new'.freeze
-
-
# The DOM class convention is to use the singular form of an object or class.
-
#
-
# dom_class(post) # => "post"
-
# dom_class(Person) # => "person"
-
#
-
# If you need to address multiple instances of the same class in the same view, you can prefix the dom_class:
-
#
-
# dom_class(post, :edit) # => "edit_post"
-
# dom_class(Person, :edit) # => "edit_person"
-
1
def dom_class(record_or_class, prefix = nil)
-
singular = model_name_from_record_or_class(record_or_class).param_key
-
prefix ? "#{prefix}#{JOIN}#{singular}" : singular
-
end
-
-
# The DOM id convention is to use the singular form of an object or class with the id following an underscore.
-
# If no id is found, prefix with "new_" instead.
-
#
-
# dom_id(Post.find(45)) # => "post_45"
-
# dom_id(Post.new) # => "new_post"
-
#
-
# If you need to address multiple instances of the same class in the same view, you can prefix the dom_id:
-
#
-
# dom_id(Post.find(45), :edit) # => "edit_post_45"
-
# dom_id(Post.new, :custom) # => "custom_post"
-
1
def dom_id(record, prefix = nil)
-
if record_id = record_key_for_dom_id(record)
-
"#{dom_class(record, prefix)}#{JOIN}#{record_id}"
-
else
-
dom_class(record, prefix || NEW)
-
end
-
end
-
-
1
protected
-
-
# Returns a string representation of the key attribute(s) that is suitable for use in an HTML DOM id.
-
# This can be overwritten to customize the default generated string representation if desired.
-
# If you need to read back a key from a dom_id in order to query for the underlying database record,
-
# you should write a helper like 'person_record_from_dom_id' that will extract the key either based
-
# on the default implementation (which just joins all key attributes with '_') or on your own
-
# overwritten version of the method. By default, this implementation passes the key string through a
-
# method that replaces all characters that are invalid inside DOM ids, with valid ones. You need to
-
# make sure yourself that your dom ids are valid, in case you overwrite this method.
-
1
def record_key_for_dom_id(record)
-
key = convert_to_model(record).to_key
-
key ? key.join('_') : key
-
end
-
end
-
end
-
1
require "action_view/view_paths"
-
-
1
module ActionView
-
# This is a class to fix I18n global state. Whenever you provide I18n.locale during a request,
-
# it will trigger the lookup_context and consequently expire the cache.
-
1
class I18nProxy < ::I18n::Config #:nodoc:
-
1
attr_reader :original_config, :lookup_context
-
-
1
def initialize(original_config, lookup_context)
-
original_config = original_config.original_config if original_config.respond_to?(:original_config)
-
@original_config, @lookup_context = original_config, lookup_context
-
end
-
-
1
def locale
-
@original_config.locale
-
end
-
-
1
def locale=(value)
-
@lookup_context.locale = value
-
end
-
end
-
-
1
module Rendering
-
1
extend ActiveSupport::Concern
-
1
include ActionView::ViewPaths
-
-
# Overwrite process to setup I18n proxy.
-
1
def process(*) #:nodoc:
-
old_config, I18n.config = I18n.config, I18nProxy.new(I18n.config, lookup_context)
-
super
-
ensure
-
I18n.config = old_config
-
end
-
-
1
module ClassMethods
-
1
def view_context_class
-
@view_context_class ||= begin
-
routes = respond_to?(:_routes) && _routes
-
helpers = respond_to?(:_helpers) && _helpers
-
-
Class.new(ActionView::Base) do
-
if routes
-
include routes.url_helpers
-
include routes.mounted_helpers
-
end
-
-
if helpers
-
include helpers
-
end
-
end
-
end
-
end
-
end
-
-
1
attr_internal_writer :view_context_class
-
-
1
def view_context_class
-
@_view_context_class ||= self.class.view_context_class
-
end
-
-
# An instance of a view class. The default view class is ActionView::Base
-
#
-
# The view class must have the following methods:
-
# View.new[lookup_context, assigns, controller]
-
# Create a new ActionView instance for a controller
-
# View#render[options]
-
# Returns String with the rendered template
-
#
-
# Override this method in a module to change the default behavior.
-
1
def view_context
-
view_context_class.new(view_renderer, view_assigns, self)
-
end
-
-
# Returns an object that is able to render templates.
-
# :api: private
-
1
def view_renderer
-
@_view_renderer ||= ActionView::Renderer.new(lookup_context)
-
end
-
-
1
def render_to_body(options = {})
-
_process_options(options)
-
_render_template(options)
-
end
-
-
1
def rendered_format
-
Mime[lookup_context.rendered_format]
-
end
-
-
1
private
-
-
# Find and render a template based on the options given.
-
# :api: private
-
1
def _render_template(options) #:nodoc:
-
variant = options[:variant]
-
-
lookup_context.rendered_format = nil if options[:formats]
-
lookup_context.variants = variant if variant
-
-
view_renderer.render(view_context, options)
-
end
-
-
# Assign the rendered format to lookup context.
-
1
def _process_format(format, options = {}) #:nodoc:
-
super
-
lookup_context.formats = [format.to_sym]
-
lookup_context.rendered_format = lookup_context.formats.first
-
end
-
-
# Normalize args by converting render "foo" to render :action => "foo" and
-
# render "foo/bar" to render :file => "foo/bar".
-
# :api: private
-
1
def _normalize_args(action=nil, options={})
-
options = super(action, options)
-
case action
-
when NilClass
-
when Hash
-
options = action
-
when String, Symbol
-
action = action.to_s
-
key = action.include?(?/) ? :file : :action
-
options[key] = action
-
else
-
options[:partial] = action
-
end
-
-
options
-
end
-
-
# Normalize options.
-
# :api: private
-
1
def _normalize_options(options)
-
options = super(options)
-
if options[:partial] == true
-
options[:partial] = action_name
-
end
-
-
if (options.keys & [:partial, :file, :template]).empty?
-
options[:prefixes] ||= _prefixes
-
end
-
-
options[:template] ||= (options[:action] || action_name).to_s
-
options
-
end
-
end
-
end
-
1
module ActionView
-
1
module RoutingUrlFor
-
-
# Returns the URL for the set of +options+ provided. This takes the
-
# same options as +url_for+ in Action Controller (see the
-
# documentation for <tt>ActionController::Base#url_for</tt>). Note that by default
-
# <tt>:only_path</tt> is <tt>true</tt> so you'll get the relative "/controller/action"
-
# instead of the fully qualified URL like "http://example.com/controller/action".
-
#
-
# ==== Options
-
# * <tt>:anchor</tt> - Specifies the anchor name to be appended to the path.
-
# * <tt>:only_path</tt> - If true, returns the relative URL (omitting the protocol, host name, and port) (<tt>true</tt> by default unless <tt>:host</tt> is specified).
-
# * <tt>:trailing_slash</tt> - If true, adds a trailing slash, as in "/archive/2005/". Note that this
-
# is currently not recommended since it breaks caching.
-
# * <tt>:host</tt> - Overrides the default (current) host if provided.
-
# * <tt>:protocol</tt> - Overrides the default (current) protocol if provided.
-
# * <tt>:user</tt> - Inline HTTP authentication (only plucked out if <tt>:password</tt> is also present).
-
# * <tt>:password</tt> - Inline HTTP authentication (only plucked out if <tt>:user</tt> is also present).
-
#
-
# ==== Relying on named routes
-
#
-
# Passing a record (like an Active Record) instead of a hash as the options parameter will
-
# trigger the named route for that record. The lookup will happen on the name of the class. So passing a
-
# Workshop object will attempt to use the +workshop_path+ route. If you have a nested route, such as
-
# +admin_workshop_path+ you'll have to call that explicitly (it's impossible for +url_for+ to guess that route).
-
#
-
# ==== Implicit Controller Namespacing
-
#
-
# Controllers passed in using the +:controller+ option will retain their namespace unless it is an absolute one.
-
#
-
# ==== Examples
-
# <%= url_for(action: 'index') %>
-
# # => /blog/
-
#
-
# <%= url_for(action: 'find', controller: 'books') %>
-
# # => /books/find
-
#
-
# <%= url_for(action: 'login', controller: 'members', only_path: false, protocol: 'https') %>
-
# # => https://www.example.com/members/login/
-
#
-
# <%= url_for(action: 'play', anchor: 'player') %>
-
# # => /messages/play/#player
-
#
-
# <%= url_for(action: 'jump', anchor: 'tax&ship') %>
-
# # => /testing/jump/#tax&ship
-
#
-
# <%= url_for(Workshop.new) %>
-
# # relies on Workshop answering a persisted? call (and in this case returning false)
-
# # => /workshops
-
#
-
# <%= url_for(@workshop) %>
-
# # calls @workshop.to_param which by default returns the id
-
# # => /workshops/5
-
#
-
# # to_param can be re-defined in a model to provide different URL names:
-
# # => /workshops/1-workshop-name
-
#
-
# <%= url_for("http://www.example.com") %>
-
# # => http://www.example.com
-
#
-
# <%= url_for(:back) %>
-
# # if request.env["HTTP_REFERER"] is set to "http://www.example.com"
-
# # => http://www.example.com
-
#
-
# <%= url_for(:back) %>
-
# # if request.env["HTTP_REFERER"] is not set or is blank
-
# # => javascript:history.back()
-
#
-
# <%= url_for(action: 'index', controller: 'users') %>
-
# # Assuming an "admin" namespace
-
# # => /admin/users
-
#
-
# <%= url_for(action: 'index', controller: '/users') %>
-
# # Specify absolute path with beginning slash
-
# # => /users
-
1
def url_for(options = nil)
-
case options
-
when String
-
options
-
when nil, Hash
-
options ||= {}
-
options = { :only_path => options[:host].nil? }.merge!(options.symbolize_keys)
-
super
-
when :back
-
_back_url
-
when Array
-
polymorphic_path(options, options.extract_options!)
-
else
-
polymorphic_path(options)
-
end
-
end
-
-
1
def url_options #:nodoc:
-
return super unless controller.respond_to?(:url_options)
-
controller.url_options
-
end
-
-
1
def _routes_context #:nodoc:
-
controller
-
end
-
1
protected :_routes_context
-
-
1
def optimize_routes_generation? #:nodoc:
-
controller.respond_to?(:optimize_routes_generation?, true) ?
-
controller.optimize_routes_generation? : super
-
end
-
1
protected :optimize_routes_generation?
-
end
-
end
-
1
require 'active_support/core_ext/object/try'
-
1
require 'active_support/core_ext/kernel/singleton_class'
-
1
require 'thread'
-
-
1
module ActionView
-
# = Action View Template
-
1
class Template
-
1
extend ActiveSupport::Autoload
-
-
# === Encodings in ActionView::Template
-
#
-
# ActionView::Template is one of a few sources of potential
-
# encoding issues in Rails. This is because the source for
-
# templates are usually read from disk, and Ruby (like most
-
# encoding-aware programming languages) assumes that the
-
# String retrieved through File IO is encoded in the
-
# <tt>default_external</tt> encoding. In Rails, the default
-
# <tt>default_external</tt> encoding is UTF-8.
-
#
-
# As a result, if a user saves their template as ISO-8859-1
-
# (for instance, using a non-Unicode-aware text editor),
-
# and uses characters outside of the ASCII range, their
-
# users will see diamonds with question marks in them in
-
# the browser.
-
#
-
# For the rest of this documentation, when we say "UTF-8",
-
# we mean "UTF-8 or whatever the default_internal encoding
-
# is set to". By default, it will be UTF-8.
-
#
-
# To mitigate this problem, we use a few strategies:
-
# 1. If the source is not valid UTF-8, we raise an exception
-
# when the template is compiled to alert the user
-
# to the problem.
-
# 2. The user can specify the encoding using Ruby-style
-
# encoding comments in any template engine. If such
-
# a comment is supplied, Rails will apply that encoding
-
# to the resulting compiled source returned by the
-
# template handler.
-
# 3. In all cases, we transcode the resulting String to
-
# the UTF-8.
-
#
-
# This means that other parts of Rails can always assume
-
# that templates are encoded in UTF-8, even if the original
-
# source of the template was not UTF-8.
-
#
-
# From a user's perspective, the easiest thing to do is
-
# to save your templates as UTF-8. If you do this, you
-
# do not need to do anything else for things to "just work".
-
#
-
# === Instructions for template handlers
-
#
-
# The easiest thing for you to do is to simply ignore
-
# encodings. Rails will hand you the template source
-
# as the default_internal (generally UTF-8), raising
-
# an exception for the user before sending the template
-
# to you if it could not determine the original encoding.
-
#
-
# For the greatest simplicity, you can support only
-
# UTF-8 as the <tt>default_internal</tt>. This means
-
# that from the perspective of your handler, the
-
# entire pipeline is just UTF-8.
-
#
-
# === Advanced: Handlers with alternate metadata sources
-
#
-
# If you want to provide an alternate mechanism for
-
# specifying encodings (like ERB does via <%# encoding: ... %>),
-
# you may indicate that you will handle encodings yourself
-
# by implementing <tt>self.handles_encoding?</tt>
-
# on your handler.
-
#
-
# If you do, Rails will not try to encode the String
-
# into the default_internal, passing you the unaltered
-
# bytes tagged with the assumed encoding (from
-
# default_external).
-
#
-
# In this case, make sure you return a String from
-
# your handler encoded in the default_internal. Since
-
# you are handling out-of-band metadata, you are
-
# also responsible for alerting the user to any
-
# problems with converting the user's data to
-
# the <tt>default_internal</tt>.
-
#
-
# To do so, simply raise +WrongEncodingError+ as follows:
-
#
-
# raise WrongEncodingError.new(
-
# problematic_string,
-
# expected_encoding
-
# )
-
-
1
eager_autoload do
-
1
autoload :Error
-
1
autoload :Handlers
-
1
autoload :HTML
-
1
autoload :Text
-
1
autoload :Types
-
end
-
-
1
extend Template::Handlers
-
-
1
attr_accessor :locals, :formats, :variants, :virtual_path
-
-
1
attr_reader :source, :identifier, :handler, :original_encoding, :updated_at
-
-
# This finalizer is needed (and exactly with a proc inside another proc)
-
# otherwise templates leak in development.
-
1
Finalizer = proc do |method_name, mod|
-
proc do
-
mod.module_eval do
-
remove_possible_method method_name
-
end
-
end
-
end
-
-
1
def initialize(source, identifier, handler, details)
-
format = details[:format] || (handler.default_format if handler.respond_to?(:default_format))
-
-
@source = source
-
@identifier = identifier
-
@handler = handler
-
@compiled = false
-
@original_encoding = nil
-
@locals = details[:locals] || []
-
@virtual_path = details[:virtual_path]
-
@updated_at = details[:updated_at] || Time.now
-
@formats = Array(format).map { |f| f.respond_to?(:ref) ? f.ref : f }
-
@variants = [details[:variant]]
-
@compile_mutex = Mutex.new
-
end
-
-
# Returns if the underlying handler supports streaming. If so,
-
# a streaming buffer *may* be passed when it start rendering.
-
1
def supports_streaming?
-
handler.respond_to?(:supports_streaming?) && handler.supports_streaming?
-
end
-
-
# Render a template. If the template was not compiled yet, it is done
-
# exactly before rendering.
-
#
-
# This method is instrumented as "!render_template.action_view". Notice that
-
# we use a bang in this instrumentation because you don't want to
-
# consume this in production. This is only slow if it's being listened to.
-
1
def render(view, locals, buffer=nil, &block)
-
instrument("!render_template") do
-
compile!(view)
-
view.send(method_name, locals, buffer, &block)
-
end
-
rescue => e
-
handle_render_error(view, e)
-
end
-
-
1
def type
-
@type ||= Types[@formats.first] if @formats.first
-
end
-
-
# Receives a view object and return a template similar to self by using @virtual_path.
-
#
-
# This method is useful if you have a template object but it does not contain its source
-
# anymore since it was already compiled. In such cases, all you need to do is to call
-
# refresh passing in the view object.
-
#
-
# Notice this method raises an error if the template to be refreshed does not have a
-
# virtual path set (true just for inline templates).
-
1
def refresh(view)
-
raise "A template needs to have a virtual path in order to be refreshed" unless @virtual_path
-
lookup = view.lookup_context
-
pieces = @virtual_path.split("/")
-
name = pieces.pop
-
partial = !!name.sub!(/^_/, "")
-
lookup.disable_cache do
-
lookup.find_template(name, [ pieces.join('/') ], partial, @locals)
-
end
-
end
-
-
1
def inspect
-
@inspect ||= defined?(Rails.root) ? identifier.sub("#{Rails.root}/", '') : identifier
-
end
-
-
# This method is responsible for properly setting the encoding of the
-
# source. Until this point, we assume that the source is BINARY data.
-
# If no additional information is supplied, we assume the encoding is
-
# the same as <tt>Encoding.default_external</tt>.
-
#
-
# The user can also specify the encoding via a comment on the first
-
# line of the template (# encoding: NAME-OF-ENCODING). This will work
-
# with any template engine, as we process out the encoding comment
-
# before passing the source on to the template engine, leaving a
-
# blank line in its stead.
-
1
def encode!
-
return unless source.encoding == Encoding::BINARY
-
-
# Look for # encoding: *. If we find one, we'll encode the
-
# String in that encoding, otherwise, we'll use the
-
# default external encoding.
-
if source.sub!(/\A#{ENCODING_FLAG}/, '')
-
encoding = magic_encoding = $1
-
else
-
encoding = Encoding.default_external
-
end
-
-
# Tag the source with the default external encoding
-
# or the encoding specified in the file
-
source.force_encoding(encoding)
-
-
# If the user didn't specify an encoding, and the handler
-
# handles encodings, we simply pass the String as is to
-
# the handler (with the default_external tag)
-
if !magic_encoding && @handler.respond_to?(:handles_encoding?) && @handler.handles_encoding?
-
source
-
# Otherwise, if the String is valid in the encoding,
-
# encode immediately to default_internal. This means
-
# that if a handler doesn't handle encodings, it will
-
# always get Strings in the default_internal
-
elsif source.valid_encoding?
-
source.encode!
-
# Otherwise, since the String is invalid in the encoding
-
# specified, raise an exception
-
else
-
raise WrongEncodingError.new(source, encoding)
-
end
-
end
-
-
1
protected
-
-
# Compile a template. This method ensures a template is compiled
-
# just once and removes the source after it is compiled.
-
1
def compile!(view) #:nodoc:
-
return if @compiled
-
-
# Templates can be used concurrently in threaded environments
-
# so compilation and any instance variable modification must
-
# be synchronized
-
@compile_mutex.synchronize do
-
# Any thread holding this lock will be compiling the template needed
-
# by the threads waiting. So re-check the @compiled flag to avoid
-
# re-compilation
-
return if @compiled
-
-
if view.is_a?(ActionView::CompiledTemplates)
-
mod = ActionView::CompiledTemplates
-
else
-
mod = view.singleton_class
-
end
-
-
instrument("!compile_template") do
-
compile(view, mod)
-
end
-
-
# Just discard the source if we have a virtual path. This
-
# means we can get the template back.
-
@source = nil if @virtual_path
-
@compiled = true
-
end
-
end
-
-
# Among other things, this method is responsible for properly setting
-
# the encoding of the compiled template.
-
#
-
# If the template engine handles encodings, we send the encoded
-
# String to the engine without further processing. This allows
-
# the template engine to support additional mechanisms for
-
# specifying the encoding. For instance, ERB supports <%# encoding: %>
-
#
-
# Otherwise, after we figure out the correct encoding, we then
-
# encode the source into <tt>Encoding.default_internal</tt>.
-
# In general, this means that templates will be UTF-8 inside of Rails,
-
# regardless of the original source encoding.
-
1
def compile(view, mod) #:nodoc:
-
encode!
-
method_name = self.method_name
-
code = @handler.call(self)
-
-
# Make sure that the resulting String to be eval'd is in the
-
# encoding of the code
-
source = <<-end_src
-
def #{method_name}(local_assigns, output_buffer)
-
_old_virtual_path, @virtual_path = @virtual_path, #{@virtual_path.inspect};_old_output_buffer = @output_buffer;#{locals_code};#{code}
-
ensure
-
@virtual_path, @output_buffer = _old_virtual_path, _old_output_buffer
-
end
-
end_src
-
-
# Make sure the source is in the encoding of the returned code
-
source.force_encoding(code.encoding)
-
-
# In case we get back a String from a handler that is not in
-
# BINARY or the default_internal, encode it to the default_internal
-
source.encode!
-
-
# Now, validate that the source we got back from the template
-
# handler is valid in the default_internal. This is for handlers
-
# that handle encoding but screw up
-
unless source.valid_encoding?
-
raise WrongEncodingError.new(@source, Encoding.default_internal)
-
end
-
-
begin
-
mod.module_eval(source, identifier, 0)
-
ObjectSpace.define_finalizer(self, Finalizer[method_name, mod])
-
rescue => e # errors from template code
-
if logger = (view && view.logger)
-
logger.debug "ERROR: compiling #{method_name} RAISED #{e}"
-
logger.debug "Function body: #{source}"
-
logger.debug "Backtrace: #{e.backtrace.join("\n")}"
-
end
-
-
raise ActionView::Template::Error.new(self, e)
-
end
-
end
-
-
1
def handle_render_error(view, e) #:nodoc:
-
if e.is_a?(Template::Error)
-
e.sub_template_of(self)
-
raise e
-
else
-
template = self
-
unless template.source
-
template = refresh(view)
-
template.encode!
-
end
-
raise Template::Error.new(template, e)
-
end
-
end
-
-
1
def locals_code #:nodoc:
-
# Double assign to suppress the dreaded 'assigned but unused variable' warning
-
@locals.map { |key| "#{key} = #{key} = local_assigns[:#{key}];" }.join
-
end
-
-
1
def method_name #:nodoc:
-
@method_name ||= "_#{identifier_method_name}__#{@identifier.hash}_#{__id__}".gsub('-', "_")
-
end
-
-
1
def identifier_method_name #:nodoc:
-
inspect.gsub(/[^a-z_]/, '_')
-
end
-
-
1
def instrument(action, &block)
-
payload = { virtual_path: @virtual_path, identifier: @identifier }
-
ActiveSupport::Notifications.instrument("#{action}.action_view", payload, &block)
-
end
-
end
-
end
-
1
module ActionView #:nodoc:
-
# = Action View Template Handlers
-
1
class Template
-
1
module Handlers #:nodoc:
-
1
autoload :ERB, 'action_view/template/handlers/erb'
-
1
autoload :Builder, 'action_view/template/handlers/builder'
-
1
autoload :Raw, 'action_view/template/handlers/raw'
-
-
1
def self.extended(base)
-
1
base.register_default_template_handler :erb, ERB.new
-
1
base.register_template_handler :builder, Builder.new
-
1
base.register_template_handler :raw, Raw.new
-
1
base.register_template_handler :ruby, :source.to_proc
-
end
-
-
1
@@template_handlers = {}
-
1
@@default_template_handlers = nil
-
-
1
def self.extensions
-
@@template_extensions ||= @@template_handlers.keys
-
end
-
-
# Register an object that knows how to handle template files with the given
-
# extensions. This can be used to implement new template types.
-
# The handler must respond to `:call`, which will be passed the template
-
# and should return the rendered template as a String.
-
1
def register_template_handler(*extensions, handler)
-
6
raise(ArgumentError, "Extension is required") if extensions.empty?
-
6
extensions.each do |extension|
-
6
@@template_handlers[extension.to_sym] = handler
-
end
-
6
@@template_extensions = nil
-
end
-
-
1
def template_handler_extensions
-
@@template_handlers.keys.map {|key| key.to_s }.sort
-
end
-
-
1
def registered_template_handler(extension)
-
extension && @@template_handlers[extension.to_sym]
-
end
-
-
1
def register_default_template_handler(extension, klass)
-
1
register_template_handler(extension, klass)
-
1
@@default_template_handlers = klass
-
end
-
-
1
def handler_for_extension(extension)
-
registered_template_handler(extension) || @@default_template_handlers
-
end
-
end
-
end
-
end
-
1
module ActionView
-
1
module Template::Handlers
-
1
class Builder
-
# Default format used by Builder.
-
1
class_attribute :default_format
-
1
self.default_format = :xml
-
-
1
def call(template)
-
require_engine
-
"xml = ::Builder::XmlMarkup.new(:indent => 2);" +
-
"self.output_buffer = xml.target!;" +
-
template.source +
-
";xml.target!;"
-
end
-
-
1
protected
-
-
1
def require_engine
-
@required ||= begin
-
require "builder"
-
true
-
end
-
end
-
end
-
end
-
end
-
1
require 'erubis'
-
-
1
module ActionView
-
1
class Template
-
1
module Handlers
-
1
class Erubis < ::Erubis::Eruby
-
1
def add_preamble(src)
-
@newline_pending = 0
-
src << "@output_buffer = output_buffer || ActionView::OutputBuffer.new;"
-
end
-
-
1
def add_text(src, text)
-
return if text.empty?
-
-
if text == "\n"
-
@newline_pending += 1
-
else
-
src << "@output_buffer.safe_append='"
-
src << "\n" * @newline_pending if @newline_pending > 0
-
src << escape_text(text)
-
src << "'.freeze;"
-
-
@newline_pending = 0
-
end
-
end
-
-
# Erubis toggles <%= and <%== behavior when escaping is enabled.
-
# We override to always treat <%== as escaped.
-
1
def add_expr(src, code, indicator)
-
case indicator
-
when '=='
-
add_expr_escaped(src, code)
-
else
-
super
-
end
-
end
-
-
1
BLOCK_EXPR = /\s+(do|\{)(\s*\|[^|]*\|)?\s*\Z/
-
-
1
def add_expr_literal(src, code)
-
flush_newline_if_pending(src)
-
if code =~ BLOCK_EXPR
-
src << '@output_buffer.append= ' << code
-
else
-
src << '@output_buffer.append=(' << code << ');'
-
end
-
end
-
-
1
def add_expr_escaped(src, code)
-
flush_newline_if_pending(src)
-
if code =~ BLOCK_EXPR
-
src << "@output_buffer.safe_append= " << code
-
else
-
src << "@output_buffer.safe_append=(" << code << ");"
-
end
-
end
-
-
1
def add_stmt(src, code)
-
flush_newline_if_pending(src)
-
super
-
end
-
-
1
def add_postamble(src)
-
flush_newline_if_pending(src)
-
src << '@output_buffer.to_s'
-
end
-
-
1
def flush_newline_if_pending(src)
-
if @newline_pending > 0
-
src << "@output_buffer.safe_append='#{"\n" * @newline_pending}'.freeze;"
-
@newline_pending = 0
-
end
-
end
-
end
-
-
1
class ERB
-
# Specify trim mode for the ERB compiler. Defaults to '-'.
-
# See ERB documentation for suitable values.
-
1
class_attribute :erb_trim_mode
-
1
self.erb_trim_mode = '-'
-
-
# Default implementation used.
-
1
class_attribute :erb_implementation
-
1
self.erb_implementation = Erubis
-
-
# Do not escape templates of these mime types.
-
1
class_attribute :escape_whitelist
-
1
self.escape_whitelist = ["text/plain"]
-
-
1
ENCODING_TAG = Regexp.new("\\A(<%#{ENCODING_FLAG}-?%>)[ \\t]*")
-
-
1
def self.call(template)
-
new.call(template)
-
end
-
-
1
def supports_streaming?
-
true
-
end
-
-
1
def handles_encoding?
-
true
-
end
-
-
1
def call(template)
-
# First, convert to BINARY, so in case the encoding is
-
# wrong, we can still find an encoding tag
-
# (<%# encoding %>) inside the String using a regular
-
# expression
-
template_source = template.source.dup.force_encoding(Encoding::ASCII_8BIT)
-
-
erb = template_source.gsub(ENCODING_TAG, '')
-
encoding = $2
-
-
erb.force_encoding valid_encoding(template.source.dup, encoding)
-
-
# Always make sure we return a String in the default_internal
-
erb.encode!
-
-
self.class.erb_implementation.new(
-
erb,
-
:escape => (self.class.escape_whitelist.include? template.type),
-
:trim => (self.class.erb_trim_mode == "-")
-
).src
-
end
-
-
1
private
-
-
1
def valid_encoding(string, encoding)
-
# If a magic encoding comment was found, tag the
-
# String with this encoding. This is for a case
-
# where the original String was assumed to be,
-
# for instance, UTF-8, but a magic comment
-
# proved otherwise
-
string.force_encoding(encoding) if encoding
-
-
# If the String is valid, return the encoding we found
-
return string.encoding if string.valid_encoding?
-
-
# Otherwise, raise an exception
-
raise WrongEncodingError.new(string, string.encoding)
-
end
-
end
-
end
-
end
-
end
-
1
module ActionView
-
1
module Template::Handlers
-
1
class Raw
-
1
def call(template)
-
escaped = template.source.gsub(':', '\:')
-
-
'%q:' + escaped + ':;'
-
end
-
end
-
end
-
end
-
1
require "pathname"
-
1
require "active_support/core_ext/class"
-
1
require "active_support/core_ext/module/attribute_accessors"
-
1
require "action_view/template"
-
1
require "thread"
-
1
require "thread_safe"
-
-
1
module ActionView
-
# = Action View Resolver
-
1
class Resolver
-
# Keeps all information about view path and builds virtual path.
-
1
class Path
-
1
attr_reader :name, :prefix, :partial, :virtual
-
1
alias_method :partial?, :partial
-
-
1
def self.build(name, prefix, partial)
-
virtual = ""
-
virtual << "#{prefix}/" unless prefix.empty?
-
virtual << (partial ? "_#{name}" : name)
-
new name, prefix, partial, virtual
-
end
-
-
1
def initialize(name, prefix, partial, virtual)
-
@name = name
-
@prefix = prefix
-
@partial = partial
-
@virtual = virtual
-
end
-
-
1
def to_str
-
@virtual
-
end
-
1
alias :to_s :to_str
-
end
-
-
# Threadsafe template cache
-
1
class Cache #:nodoc:
-
1
class SmallCache < ThreadSafe::Cache
-
1
def initialize(options = {})
-
8
super(options.merge(:initial_capacity => 2))
-
end
-
end
-
-
# preallocate all the default blocks for performance/memory consumption reasons
-
1
PARTIAL_BLOCK = lambda {|cache, partial| cache[partial] = SmallCache.new}
-
1
PREFIX_BLOCK = lambda {|cache, prefix| cache[prefix] = SmallCache.new(&PARTIAL_BLOCK)}
-
1
NAME_BLOCK = lambda {|cache, name| cache[name] = SmallCache.new(&PREFIX_BLOCK)}
-
1
KEY_BLOCK = lambda {|cache, key| cache[key] = SmallCache.new(&NAME_BLOCK)}
-
-
# usually a majority of template look ups return nothing, use this canonical preallocated array to save memory
-
1
NO_TEMPLATES = [].freeze
-
-
1
def initialize
-
8
@data = SmallCache.new(&KEY_BLOCK)
-
end
-
-
# Cache the templates returned by the block
-
1
def cache(key, name, prefix, partial, locals)
-
if Resolver.caching?
-
@data[key][name][prefix][partial][locals] ||= canonical_no_templates(yield)
-
else
-
fresh_templates = yield
-
cached_templates = @data[key][name][prefix][partial][locals]
-
-
if templates_have_changed?(cached_templates, fresh_templates)
-
@data[key][name][prefix][partial][locals] = canonical_no_templates(fresh_templates)
-
else
-
cached_templates || NO_TEMPLATES
-
end
-
end
-
end
-
-
1
def clear
-
@data.clear
-
end
-
-
1
private
-
-
1
def canonical_no_templates(templates)
-
templates.empty? ? NO_TEMPLATES : templates
-
end
-
-
1
def templates_have_changed?(cached_templates, fresh_templates)
-
# if either the old or new template list is empty, we don't need to (and can't)
-
# compare modification times, and instead just check whether the lists are different
-
if cached_templates.blank? || fresh_templates.blank?
-
return fresh_templates.blank? != cached_templates.blank?
-
end
-
-
cached_templates_max_updated_at = cached_templates.map(&:updated_at).max
-
-
# if a template has changed, it will be now be newer than all the cached templates
-
fresh_templates.any? { |t| t.updated_at > cached_templates_max_updated_at }
-
end
-
end
-
-
1
cattr_accessor :caching
-
1
self.caching = true
-
-
1
class << self
-
1
alias :caching? :caching
-
end
-
-
1
def initialize
-
8
@cache = Cache.new
-
end
-
-
1
def clear_cache
-
@cache.clear
-
end
-
-
# Normalizes the arguments and passes it on to find_templates.
-
1
def find_all(name, prefix=nil, partial=false, details={}, key=nil, locals=[])
-
cached(key, [name, prefix, partial], details, locals) do
-
find_templates(name, prefix, partial, details)
-
end
-
end
-
-
1
private
-
-
1
delegate :caching?, to: :class
-
-
# This is what child classes implement. No defaults are needed
-
# because Resolver guarantees that the arguments are present and
-
# normalized.
-
1
def find_templates(name, prefix, partial, details)
-
raise NotImplementedError, "Subclasses must implement a find_templates(name, prefix, partial, details) method"
-
end
-
-
# Helpers that builds a path. Useful for building virtual paths.
-
1
def build_path(name, prefix, partial)
-
Path.build(name, prefix, partial)
-
end
-
-
# Handles templates caching. If a key is given and caching is on
-
# always check the cache before hitting the resolver. Otherwise,
-
# it always hits the resolver but if the key is present, check if the
-
# resolver is fresher before returning it.
-
1
def cached(key, path_info, details, locals) #:nodoc:
-
name, prefix, partial = path_info
-
locals = locals.map { |x| x.to_s }.sort!
-
-
if key
-
@cache.cache(key, name, prefix, partial, locals) do
-
decorate(yield, path_info, details, locals)
-
end
-
else
-
decorate(yield, path_info, details, locals)
-
end
-
end
-
-
# Ensures all the resolver information is set in the template.
-
1
def decorate(templates, path_info, details, locals) #:nodoc:
-
cached = nil
-
templates.each do |t|
-
t.locals = locals
-
t.formats = details[:formats] || [:html] if t.formats.empty?
-
t.variants = details[:variants] || [] if t.variants.empty?
-
t.virtual_path ||= (cached ||= build_path(*path_info))
-
end
-
end
-
end
-
-
# An abstract class that implements a Resolver with path semantics.
-
1
class PathResolver < Resolver #:nodoc:
-
1
EXTENSIONS = { :locale => ".", :formats => ".", :variants => "+", :handlers => "." }
-
1
DEFAULT_PATTERN = ":prefix/:action{.:locale,}{.:formats,}{+:variants,}{.:handlers,}"
-
-
1
def initialize(pattern=nil)
-
8
@pattern = pattern || DEFAULT_PATTERN
-
8
super()
-
end
-
-
1
private
-
-
1
def find_templates(name, prefix, partial, details)
-
path = Path.build(name, prefix, partial)
-
query(path, details, details[:formats])
-
end
-
-
1
def query(path, details, formats)
-
query = build_query(path, details)
-
-
# deals with case-insensitive file systems.
-
sanitizer = Hash.new { |h,dir| h[dir] = Dir["#{dir}/*"] }
-
-
template_paths = Dir[query].reject { |filename|
-
File.directory?(filename) ||
-
!sanitizer[File.dirname(filename)].include?(filename)
-
}
-
-
template_paths.map { |template|
-
handler, format, variant = extract_handler_and_format_and_variant(template, formats)
-
contents = File.binread(template)
-
-
Template.new(contents, File.expand_path(template), handler,
-
:virtual_path => path.virtual,
-
:format => format,
-
:variant => variant,
-
:updated_at => mtime(template)
-
)
-
}
-
end
-
-
# Helper for building query glob string based on resolver's pattern.
-
1
def build_query(path, details)
-
query = @pattern.dup
-
-
prefix = path.prefix.empty? ? "" : "#{escape_entry(path.prefix)}\\1"
-
query.gsub!(/\:prefix(\/)?/, prefix)
-
-
partial = escape_entry(path.partial? ? "_#{path.name}" : path.name)
-
query.gsub!(/\:action/, partial)
-
-
details.each do |ext, variants|
-
query.gsub!(/\:#{ext}/, "{#{variants.compact.uniq.join(',')}}")
-
end
-
-
File.expand_path(query, @path)
-
end
-
-
1
def escape_entry(entry)
-
entry.gsub(/[*?{}\[\]]/, '\\\\\\&')
-
end
-
-
# Returns the file mtime from the filesystem.
-
1
def mtime(p)
-
File.mtime(p)
-
end
-
-
# Extract handler and formats from path. If a format cannot be a found neither
-
# from the path, or the handler, we should return the array of formats given
-
# to the resolver.
-
1
def extract_handler_and_format_and_variant(path, default_formats)
-
pieces = File.basename(path).split(".")
-
pieces.shift
-
-
extension = pieces.pop
-
unless extension
-
message = "The file #{path} did not specify a template handler. The default is currently ERB, " \
-
"but will change to RAW in the future."
-
ActiveSupport::Deprecation.warn message
-
end
-
-
handler = Template.handler_for_extension(extension)
-
format, variant = pieces.last.split(EXTENSIONS[:variants], 2) if pieces.last
-
format &&= Template::Types[format]
-
-
[handler, format, variant]
-
end
-
end
-
-
# A resolver that loads files from the filesystem. It allows setting your own
-
# resolving pattern. Such pattern can be a glob string supported by some variables.
-
#
-
# ==== Examples
-
#
-
# Default pattern, loads views the same way as previous versions of rails, eg. when you're
-
# looking for `users/new` it will produce query glob: `users/new{.{en},}{.{html,js},}{.{erb,haml},}`
-
#
-
# FileSystemResolver.new("/path/to/views", ":prefix/:action{.:locale,}{.:formats,}{.:handlers,}")
-
#
-
# This one allows you to keep files with different formats in separate subdirectories,
-
# eg. `users/new.html` will be loaded from `users/html/new.erb` or `users/new.html.erb`,
-
# `users/new.js` from `users/js/new.erb` or `users/new.js.erb`, etc.
-
#
-
# FileSystemResolver.new("/path/to/views", ":prefix/{:formats/,}:action{.:locale,}{.:formats,}{.:handlers,}")
-
#
-
# If you don't specify a pattern then the default will be used.
-
#
-
# In order to use any of the customized resolvers above in a Rails application, you just need
-
# to configure ActionController::Base.view_paths in an initializer, for example:
-
#
-
# ActionController::Base.view_paths = FileSystemResolver.new(
-
# Rails.root.join("app/views"),
-
# ":prefix{/:locale}/:action{.:formats,}{.:handlers,}"
-
# )
-
#
-
# ==== Pattern format and variables
-
#
-
# Pattern has to be a valid glob string, and it allows you to use the
-
# following variables:
-
#
-
# * <tt>:prefix</tt> - usually the controller path
-
# * <tt>:action</tt> - name of the action
-
# * <tt>:locale</tt> - possible locale versions
-
# * <tt>:formats</tt> - possible request formats (for example html, json, xml...)
-
# * <tt>:handlers</tt> - possible handlers (for example erb, haml, builder...)
-
#
-
1
class FileSystemResolver < PathResolver
-
1
def initialize(path, pattern=nil)
-
8
raise ArgumentError, "path already is a Resolver class" if path.is_a?(Resolver)
-
8
super(pattern)
-
8
@path = File.expand_path(path)
-
end
-
-
1
def to_s
-
@path.to_s
-
end
-
1
alias :to_path :to_s
-
-
1
def eql?(resolver)
-
self.class.equal?(resolver.class) && to_path == resolver.to_path
-
end
-
1
alias :== :eql?
-
end
-
-
# An Optimized resolver for Rails' most common case.
-
1
class OptimizedFileSystemResolver < FileSystemResolver #:nodoc:
-
1
def build_query(path, details)
-
query = escape_entry(File.join(@path, path))
-
-
exts = EXTENSIONS.map do |ext, prefix|
-
"{#{details[ext].compact.uniq.map { |e| "#{prefix}#{e}," }.join}}"
-
end.join
-
-
query + exts
-
end
-
end
-
-
# The same as FileSystemResolver but does not allow templates to store
-
# a virtual path since it is invalid for such resolvers.
-
1
class FallbackFileSystemResolver < FileSystemResolver #:nodoc:
-
1
def self.instances
-
1
[new(""), new("/")]
-
end
-
-
1
def decorate(*)
-
super.each { |t| t.virtual_path = nil }
-
end
-
end
-
end
-
1
require 'set'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
-
1
module ActionView
-
1
class Template
-
1
class Types
-
1
class Type
-
1
cattr_accessor :types
-
1
self.types = Set.new
-
-
1
def self.register(*t)
-
7
types.merge(t.map { |type| type.to_s })
-
end
-
-
1
register :html, :text, :js, :css, :xml, :json
-
-
1
def self.[](type)
-
return type if type.is_a?(self)
-
-
if type.is_a?(Symbol) || types.member?(type.to_s)
-
new(type)
-
end
-
end
-
-
1
attr_reader :symbol
-
-
1
def initialize(symbol)
-
@symbol = symbol.to_sym
-
end
-
-
1
delegate :to_s, :to_sym, :to => :symbol
-
1
alias to_str to_s
-
-
1
def ref
-
to_sym || to_s
-
end
-
-
1
def ==(type)
-
return false if type.blank?
-
symbol.to_sym == type.to_sym
-
end
-
end
-
-
1
cattr_accessor :type_klass
-
-
1
def self.delegate_to(klass)
-
2
self.type_klass = klass
-
end
-
-
1
delegate_to Type
-
-
1
def self.[](type)
-
type_klass[type]
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/remove_method'
-
1
require 'action_controller'
-
1
require 'action_controller/test_case'
-
1
require 'action_view'
-
-
1
module ActionView
-
# = Action View Test Case
-
1
class TestCase < ActiveSupport::TestCase
-
1
class TestController < ActionController::Base
-
1
include ActionDispatch::TestProcess
-
-
1
attr_accessor :request, :response, :params
-
-
1
class << self
-
1
attr_writer :controller_path
-
end
-
-
1
def controller_path=(path)
-
self.class.controller_path=(path)
-
end
-
-
1
def initialize
-
super
-
self.class.controller_path = ""
-
@request = ActionController::TestRequest.new
-
@response = ActionController::TestResponse.new
-
-
@request.env.delete('PATH_INFO')
-
@params = {}
-
end
-
end
-
-
1
module Behavior
-
1
extend ActiveSupport::Concern
-
-
1
include ActionDispatch::Assertions, ActionDispatch::TestProcess
-
1
include ActionController::TemplateAssertions
-
1
include ActionView::Context
-
-
1
include ActionDispatch::Routing::PolymorphicRoutes
-
-
1
include AbstractController::Helpers
-
1
include ActionView::Helpers
-
1
include ActionView::RecordIdentifier
-
1
include ActionView::RoutingUrlFor
-
-
1
include ActiveSupport::Testing::ConstantLookup
-
-
1
delegate :lookup_context, :to => :controller
-
1
attr_accessor :controller, :output_buffer, :rendered
-
-
1
module ClassMethods
-
1
def tests(helper_class)
-
case helper_class
-
when String, Symbol
-
self.helper_class = "#{helper_class.to_s.underscore}_helper".camelize.safe_constantize
-
when Module
-
self.helper_class = helper_class
-
end
-
end
-
-
1
def determine_default_helper_class(name)
-
determine_constant_from_test_name(name) do |constant|
-
Module === constant && !(Class === constant)
-
end
-
end
-
-
1
def helper_method(*methods)
-
# Almost a duplicate from ActionController::Helpers
-
methods.flatten.each do |method|
-
_helpers.module_eval <<-end_eval
-
def #{method}(*args, &block) # def current_user(*args, &block)
-
_test_case.send(%(#{method}), *args, &block) # _test_case.send(%(current_user), *args, &block)
-
end # end
-
end_eval
-
end
-
end
-
-
1
attr_writer :helper_class
-
-
1
def helper_class
-
@helper_class ||= determine_default_helper_class(name)
-
end
-
-
1
def new(*)
-
include_helper_modules!
-
super
-
end
-
-
1
private
-
-
1
def include_helper_modules!
-
helper(helper_class) if helper_class
-
include _helpers
-
end
-
-
end
-
-
1
def setup_with_controller
-
@controller = ActionView::TestCase::TestController.new
-
@request = @controller.request
-
@output_buffer = ActiveSupport::SafeBuffer.new
-
@rendered = ''
-
-
make_test_case_available_to_view!
-
say_no_to_protect_against_forgery!
-
end
-
-
1
def config
-
@controller.config if @controller.respond_to?(:config)
-
end
-
-
1
def render(options = {}, local_assigns = {}, &block)
-
view.assign(view_assigns)
-
@rendered << output = view.render(options, local_assigns, &block)
-
output
-
end
-
-
1
def rendered_views
-
@_rendered_views ||= RenderedViewsCollection.new
-
end
-
-
1
class RenderedViewsCollection
-
1
def initialize
-
@rendered_views ||= Hash.new { |hash, key| hash[key] = [] }
-
end
-
-
1
def add(view, locals)
-
@rendered_views[view] ||= []
-
@rendered_views[view] << locals
-
end
-
-
1
def locals_for(view)
-
@rendered_views[view]
-
end
-
-
1
def rendered_views
-
@rendered_views.keys
-
end
-
-
1
def view_rendered?(view, expected_locals)
-
locals_for(view).any? do |actual_locals|
-
expected_locals.all? {|key, value| value == actual_locals[key] }
-
end
-
end
-
end
-
-
1
included do
-
1
setup :setup_with_controller
-
end
-
-
1
private
-
-
# Support the selector assertions
-
#
-
# Need to experiment if this priority is the best one: rendered => output_buffer
-
1
def response_from_page
-
HTML::Document.new(@rendered.blank? ? @output_buffer : @rendered).root
-
end
-
-
1
def say_no_to_protect_against_forgery!
-
_helpers.module_eval do
-
remove_possible_method :protect_against_forgery?
-
def protect_against_forgery?
-
false
-
end
-
end
-
end
-
-
1
def make_test_case_available_to_view!
-
test_case_instance = self
-
_helpers.module_eval do
-
unless private_method_defined?(:_test_case)
-
define_method(:_test_case) { test_case_instance }
-
private :_test_case
-
end
-
end
-
end
-
-
1
module Locals
-
1
attr_accessor :rendered_views
-
-
1
def render(options = {}, local_assigns = {})
-
case options
-
when Hash
-
if block_given?
-
rendered_views.add options[:layout], options[:locals]
-
elsif options.key?(:partial)
-
rendered_views.add options[:partial], options[:locals]
-
end
-
else
-
rendered_views.add options, local_assigns
-
end
-
-
super
-
end
-
end
-
-
# The instance of ActionView::Base that is used by +render+.
-
1
def view
-
@view ||= begin
-
view = @controller.view_context
-
view.singleton_class.send :include, _helpers
-
view.extend(Locals)
-
view.rendered_views = self.rendered_views
-
view.output_buffer = self.output_buffer
-
view
-
end
-
end
-
-
1
alias_method :_view, :view
-
-
1
INTERNAL_IVARS = [
-
:@NAME,
-
:@failures,
-
:@assertions,
-
:@__io__,
-
:@_assertion_wrapped,
-
:@_assertions,
-
:@_result,
-
:@_routes,
-
:@controller,
-
:@_layouts,
-
:@_files,
-
:@_rendered_views,
-
:@method_name,
-
:@output_buffer,
-
:@_partials,
-
:@passed,
-
:@rendered,
-
:@request,
-
:@routes,
-
:@tagged_logger,
-
:@_templates,
-
:@options,
-
:@test_passed,
-
:@view,
-
:@view_context_class
-
]
-
-
1
def _user_defined_ivars
-
instance_variables - INTERNAL_IVARS
-
end
-
-
# Returns a Hash of instance variables and their values, as defined by
-
# the user in the test case, which are then assigned to the view being
-
# rendered. This is generally intended for internal use and extension
-
# frameworks.
-
1
def view_assigns
-
Hash[_user_defined_ivars.map do |ivar|
-
[ivar[1..-1].to_sym, instance_variable_get(ivar)]
-
end]
-
end
-
-
1
def _routes
-
@controller._routes if @controller.respond_to?(:_routes)
-
end
-
-
1
def method_missing(selector, *args)
-
if @controller.respond_to?(:_routes) &&
-
( @controller._routes.named_routes.helpers.include?(selector) ||
-
@controller._routes.mounted_helpers.method_defined?(selector) )
-
@controller.__send__(selector, *args)
-
else
-
super
-
end
-
end
-
end
-
-
1
include Behavior
-
end
-
end
-
1
require 'action_view/template/resolver'
-
-
1
module ActionView #:nodoc:
-
# Use FixtureResolver in your tests to simulate the presence of files on the
-
# file system. This is used internally by Rails' own test suite, and is
-
# useful for testing extensions that have no way of knowing what the file
-
# system will look like at runtime.
-
1
class FixtureResolver < PathResolver
-
1
attr_reader :hash
-
-
1
def initialize(hash = {}, pattern=nil)
-
super(pattern)
-
@hash = hash
-
end
-
-
1
def to_s
-
@hash.keys.join(', ')
-
end
-
-
1
private
-
-
1
def query(path, exts, formats)
-
query = ""
-
EXTENSIONS.each_key do |ext|
-
query << '(' << exts[ext].map {|e| e && Regexp.escape(".#{e}") }.join('|') << '|)'
-
end
-
query = /^(#{Regexp.escape(path)})#{query}$/
-
-
templates = []
-
@hash.each do |_path, array|
-
source, updated_at = array
-
next unless _path =~ query
-
handler, format, variant = extract_handler_and_format_and_variant(_path, formats)
-
templates << Template.new(source, _path, handler,
-
:virtual_path => path.virtual,
-
:format => format,
-
:variant => variant,
-
:updated_at => updated_at
-
)
-
end
-
-
templates.sort_by {|t| -t.identifier.match(/^#{query}$/).captures.reject(&:blank?).size }
-
end
-
end
-
-
1
class NullResolver < PathResolver
-
1
def query(path, exts, formats)
-
handler, format, variant = extract_handler_and_format_and_variant(path, formats)
-
[ActionView::Template.new("Template generated by Null Resolver", path, handler, :virtual_path => path, :format => format, :variant => variant)]
-
end
-
end
-
-
end
-
-
1
$LOAD_PATH.unshift "#{File.dirname(__FILE__)}/html-scanner"
-
-
1
module HTML
-
1
extend ActiveSupport::Autoload
-
-
1
eager_autoload do
-
1
autoload :CDATA, 'html/node'
-
1
autoload :Document, 'html/document'
-
1
autoload :FullSanitizer, 'html/sanitizer'
-
1
autoload :LinkSanitizer, 'html/sanitizer'
-
1
autoload :Node, 'html/node'
-
1
autoload :Sanitizer, 'html/sanitizer'
-
1
autoload :Selector, 'html/selector'
-
1
autoload :Tag, 'html/node'
-
1
autoload :Text, 'html/node'
-
1
autoload :Tokenizer, 'html/tokenizer'
-
1
autoload :Version, 'html/version'
-
1
autoload :WhiteListSanitizer, 'html/sanitizer'
-
end
-
end
-
1
require_relative 'gem_version'
-
-
1
module ActionView
-
# Returns the version of the currently loaded ActionView as a <tt>Gem::Version</tt>
-
1
def self.version
-
gem_version
-
end
-
end
-
1
require 'action_view/base'
-
-
1
module ActionView
-
1
module ViewPaths
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
2
class_attribute :_view_paths
-
2
self._view_paths = ActionView::PathSet.new
-
2
self._view_paths.freeze
-
end
-
-
1
delegate :template_exists?, :view_paths, :formats, :formats=,
-
:locale, :locale=, :to => :lookup_context
-
-
1
module ClassMethods
-
1
def parent_prefixes
-
@parent_prefixes ||= begin
-
parent_controller = superclass
-
prefixes = []
-
-
until parent_controller.abstract?
-
prefixes << parent_controller.controller_path
-
parent_controller = parent_controller.superclass
-
end
-
-
prefixes
-
end
-
end
-
end
-
-
# The prefixes used in render "foo" shortcuts.
-
1
def _prefixes
-
@_prefixes ||= begin
-
parent_prefixes = self.class.parent_prefixes
-
parent_prefixes.dup.unshift(controller_path)
-
end
-
end
-
-
# LookupContext is the object responsible to hold all information required to lookup
-
# templates, i.e. view paths and details. Check ActionView::LookupContext for more
-
# information.
-
1
def lookup_context
-
@_lookup_context ||=
-
ActionView::LookupContext.new(self.class._view_paths, details_for_lookup, _prefixes)
-
end
-
-
1
def details_for_lookup
-
{ }
-
end
-
-
1
def append_view_path(path)
-
lookup_context.view_paths.push(*path)
-
end
-
-
1
def prepend_view_path(path)
-
lookup_context.view_paths.unshift(*path)
-
end
-
-
1
module ClassMethods
-
# Append a path to the list of view paths for this controller.
-
#
-
# ==== Parameters
-
# * <tt>path</tt> - If a String is provided, it gets converted into
-
# the default view path. You may also provide a custom view path
-
# (see ActionView::PathSet for more information)
-
1
def append_view_path(path)
-
self._view_paths = view_paths + Array(path)
-
end
-
-
# Prepend a path to the list of view paths for this controller.
-
#
-
# ==== Parameters
-
# * <tt>path</tt> - If a String is provided, it gets converted into
-
# the default view path. You may also provide a custom view path
-
# (see ActionView::PathSet for more information)
-
1
def prepend_view_path(path)
-
6
self._view_paths = ActionView::PathSet.new(Array(path) + view_paths)
-
end
-
-
# A list of all of the default view paths for this controller.
-
1
def view_paths
-
6
_view_paths
-
end
-
-
# Set the view paths.
-
#
-
# ==== Parameters
-
# * <tt>paths</tt> - If a PathSet is provided, use that;
-
# otherwise, process the parameter into a PathSet.
-
1
def view_paths=(paths)
-
self._view_paths = ActionView::PathSet.new(Array(paths))
-
end
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2004-2014 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
1
require 'active_support'
-
1
require 'active_support/rails'
-
1
require 'active_model/version'
-
-
1
module ActiveModel
-
1
extend ActiveSupport::Autoload
-
-
1
autoload :AttributeMethods
-
1
autoload :BlockValidator, 'active_model/validator'
-
1
autoload :Callbacks
-
1
autoload :Conversion
-
1
autoload :Dirty
-
1
autoload :EachValidator, 'active_model/validator'
-
1
autoload :ForbiddenAttributesProtection
-
1
autoload :Lint
-
1
autoload :Model
-
1
autoload :Name, 'active_model/naming'
-
1
autoload :Naming
-
1
autoload :SecurePassword
-
1
autoload :Serialization
-
1
autoload :TestCase
-
1
autoload :Translation
-
1
autoload :Validations
-
1
autoload :Validator
-
-
1
eager_autoload do
-
1
autoload :Errors
-
end
-
-
1
module Serializers
-
1
extend ActiveSupport::Autoload
-
-
1
eager_autoload do
-
1
autoload :JSON
-
1
autoload :Xml
-
end
-
end
-
-
1
def self.eager_load!
-
super
-
ActiveModel::Serializers.eager_load!
-
end
-
end
-
-
1
ActiveSupport.on_load(:i18n) do
-
1
I18n.load_path << File.dirname(__FILE__) + '/active_model/locale/en.yml'
-
end
-
1
require 'thread_safe'
-
1
require 'mutex_m'
-
-
1
module ActiveModel
-
# Raised when an attribute is not defined.
-
#
-
# class User < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# user = User.first
-
# user.pets.select(:id).first.user_id
-
# # => ActiveModel::MissingAttributeError: missing attribute: user_id
-
1
class MissingAttributeError < NoMethodError
-
end
-
-
# == Active \Model \Attribute \Methods
-
#
-
# Provides a way to add prefixes and suffixes to your methods as
-
# well as handling the creation of <tt>ActiveRecord::Base</tt>-like
-
# class methods such as +table_name+.
-
#
-
# The requirements to implement <tt>ActiveModel::AttributeMethods</tt> are to:
-
#
-
# * <tt>include ActiveModel::AttributeMethods</tt> in your class.
-
# * Call each of its method you want to add, such as +attribute_method_suffix+
-
# or +attribute_method_prefix+.
-
# * Call +define_attribute_methods+ after the other methods are called.
-
# * Define the various generic +_attribute+ methods that you have declared.
-
# * Define an +attributes+ method which returns a hash with each
-
# attribute name in your model as hash key and the attribute value as hash value.
-
# Hash keys must be strings.
-
#
-
# A minimal implementation could be:
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attribute_method_affix prefix: 'reset_', suffix: '_to_default!'
-
# attribute_method_suffix '_contrived?'
-
# attribute_method_prefix 'clear_'
-
# define_attribute_methods :name
-
#
-
# attr_accessor :name
-
#
-
# def attributes
-
# { 'name' => @name }
-
# end
-
#
-
# private
-
#
-
# def attribute_contrived?(attr)
-
# true
-
# end
-
#
-
# def clear_attribute(attr)
-
# send("#{attr}=", nil)
-
# end
-
#
-
# def reset_attribute_to_default!(attr)
-
# send("#{attr}=", 'Default Name')
-
# end
-
# end
-
1
module AttributeMethods
-
1
extend ActiveSupport::Concern
-
-
1
NAME_COMPILABLE_REGEXP = /\A[a-zA-Z_]\w*[!?=]?\z/
-
1
CALL_COMPILABLE_REGEXP = /\A[a-zA-Z_]\w*[!?]?\z/
-
-
1
included do
-
1
class_attribute :attribute_aliases, :attribute_method_matchers, instance_writer: false
-
1
self.attribute_aliases = {}
-
1
self.attribute_method_matchers = [ClassMethods::AttributeMethodMatcher.new]
-
end
-
-
1
module ClassMethods
-
# Declares a method available for all attributes with the given prefix.
-
# Uses +method_missing+ and <tt>respond_to?</tt> to rewrite the method.
-
#
-
# #{prefix}#{attr}(*args, &block)
-
#
-
# to
-
#
-
# #{prefix}attribute(#{attr}, *args, &block)
-
#
-
# An instance method <tt>#{prefix}attribute</tt> must exist and accept
-
# at least the +attr+ argument.
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attr_accessor :name
-
# attribute_method_prefix 'clear_'
-
# define_attribute_methods :name
-
#
-
# private
-
#
-
# def clear_attribute(attr)
-
# send("#{attr}=", nil)
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = 'Bob'
-
# person.name # => "Bob"
-
# person.clear_name
-
# person.name # => nil
-
1
def attribute_method_prefix(*prefixes)
-
self.attribute_method_matchers += prefixes.map! { |prefix| AttributeMethodMatcher.new prefix: prefix }
-
undefine_attribute_methods
-
end
-
-
# Declares a method available for all attributes with the given suffix.
-
# Uses +method_missing+ and <tt>respond_to?</tt> to rewrite the method.
-
#
-
# #{attr}#{suffix}(*args, &block)
-
#
-
# to
-
#
-
# attribute#{suffix}(#{attr}, *args, &block)
-
#
-
# An <tt>attribute#{suffix}</tt> instance method must exist and accept at
-
# least the +attr+ argument.
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attr_accessor :name
-
# attribute_method_suffix '_short?'
-
# define_attribute_methods :name
-
#
-
# private
-
#
-
# def attribute_short?(attr)
-
# send(attr).length < 5
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = 'Bob'
-
# person.name # => "Bob"
-
# person.name_short? # => true
-
1
def attribute_method_suffix(*suffixes)
-
11
self.attribute_method_matchers += suffixes.map! { |suffix| AttributeMethodMatcher.new suffix: suffix }
-
4
undefine_attribute_methods
-
end
-
-
# Declares a method available for all attributes with the given prefix
-
# and suffix. Uses +method_missing+ and <tt>respond_to?</tt> to rewrite
-
# the method.
-
#
-
# #{prefix}#{attr}#{suffix}(*args, &block)
-
#
-
# to
-
#
-
# #{prefix}attribute#{suffix}(#{attr}, *args, &block)
-
#
-
# An <tt>#{prefix}attribute#{suffix}</tt> instance method must exist and
-
# accept at least the +attr+ argument.
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attr_accessor :name
-
# attribute_method_affix prefix: 'reset_', suffix: '_to_default!'
-
# define_attribute_methods :name
-
#
-
# private
-
#
-
# def reset_attribute_to_default!(attr)
-
# send("#{attr}=", 'Default Name')
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name # => 'Gem'
-
# person.reset_name_to_default!
-
# person.name # => 'Default Name'
-
1
def attribute_method_affix(*affixes)
-
2
self.attribute_method_matchers += affixes.map! { |affix| AttributeMethodMatcher.new prefix: affix[:prefix], suffix: affix[:suffix] }
-
1
undefine_attribute_methods
-
end
-
-
# Allows you to make aliases for attributes.
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attr_accessor :name
-
# attribute_method_suffix '_short?'
-
# define_attribute_methods :name
-
#
-
# alias_attribute :nickname, :name
-
#
-
# private
-
#
-
# def attribute_short?(attr)
-
# send(attr).length < 5
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = 'Bob'
-
# person.name # => "Bob"
-
# person.nickname # => "Bob"
-
# person.name_short? # => true
-
# person.nickname_short? # => true
-
1
def alias_attribute(new_name, old_name)
-
self.attribute_aliases = attribute_aliases.merge(new_name.to_s => old_name.to_s)
-
attribute_method_matchers.each do |matcher|
-
matcher_new = matcher.method_name(new_name).to_s
-
matcher_old = matcher.method_name(old_name).to_s
-
define_proxy_call false, self, matcher_new, matcher_old
-
end
-
end
-
-
# Is +new_name+ an alias?
-
1
def attribute_alias?(new_name)
-
attribute_aliases.key? new_name.to_s
-
end
-
-
# Returns the original name for the alias +name+
-
1
def attribute_alias(name)
-
attribute_aliases[name.to_s]
-
end
-
-
# Declares the attributes that should be prefixed and suffixed by
-
# ActiveModel::AttributeMethods.
-
#
-
# To use, pass attribute names (as strings or symbols), be sure to declare
-
# +define_attribute_methods+ after you define any prefix, suffix or affix
-
# methods, or they will not hook in.
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attr_accessor :name, :age, :address
-
# attribute_method_prefix 'clear_'
-
#
-
# # Call to define_attribute_methods must appear after the
-
# # attribute_method_prefix, attribute_method_suffix or
-
# # attribute_method_affix declares.
-
# define_attribute_methods :name, :age, :address
-
#
-
# private
-
#
-
# def clear_attribute(attr)
-
# send("#{attr}=", nil)
-
# end
-
# end
-
1
def define_attribute_methods(*attr_names)
-
attr_names.flatten.each { |attr_name| define_attribute_method(attr_name) }
-
end
-
-
# Declares an attribute that should be prefixed and suffixed by
-
# ActiveModel::AttributeMethods.
-
#
-
# To use, pass an attribute name (as string or symbol), be sure to declare
-
# +define_attribute_method+ after you define any prefix, suffix or affix
-
# method, or they will not hook in.
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attr_accessor :name
-
# attribute_method_suffix '_short?'
-
#
-
# # Call to define_attribute_method must appear after the
-
# # attribute_method_prefix, attribute_method_suffix or
-
# # attribute_method_affix declares.
-
# define_attribute_method :name
-
#
-
# private
-
#
-
# def attribute_short?(attr)
-
# send(attr).length < 5
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = 'Bob'
-
# person.name # => "Bob"
-
# person.name_short? # => true
-
1
def define_attribute_method(attr_name)
-
attribute_method_matchers.each do |matcher|
-
method_name = matcher.method_name(attr_name)
-
-
unless instance_method_already_implemented?(method_name)
-
generate_method = "define_method_#{matcher.method_missing_target}"
-
-
if respond_to?(generate_method, true)
-
send(generate_method, attr_name)
-
else
-
define_proxy_call true, generated_attribute_methods, method_name, matcher.method_missing_target, attr_name.to_s
-
end
-
end
-
end
-
attribute_method_matchers_cache.clear
-
end
-
-
# Removes all the previously dynamically defined methods from the class.
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attr_accessor :name
-
# attribute_method_suffix '_short?'
-
# define_attribute_method :name
-
#
-
# private
-
#
-
# def attribute_short?(attr)
-
# send(attr).length < 5
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = 'Bob'
-
# person.name_short? # => true
-
#
-
# Person.undefine_attribute_methods
-
#
-
# person.name_short? # => NoMethodError
-
1
def undefine_attribute_methods
-
generated_attribute_methods.module_eval do
-
instance_methods.each { |m| undef_method(m) }
-
end
-
attribute_method_matchers_cache.clear
-
end
-
-
1
def generated_attribute_methods #:nodoc:
-
@generated_attribute_methods ||= Module.new {
-
extend Mutex_m
-
5
}.tap { |mod| include mod }
-
end
-
-
1
protected
-
1
def instance_method_already_implemented?(method_name) #:nodoc:
-
generated_attribute_methods.method_defined?(method_name)
-
end
-
-
1
private
-
# The methods +method_missing+ and +respond_to?+ of this module are
-
# invoked often in a typical rails, both of which invoke the method
-
# +match_attribute_method?+. The latter method iterates through an
-
# array doing regular expression matches, which results in a lot of
-
# object creations. Most of the time it returns a +nil+ match. As the
-
# match result is always the same given a +method_name+, this cache is
-
# used to alleviate the GC, which ultimately also speeds up the app
-
# significantly (in our case our test suite finishes 10% faster with
-
# this cache).
-
1
def attribute_method_matchers_cache #:nodoc:
-
@attribute_method_matchers_cache ||= ThreadSafe::Cache.new(initial_capacity: 4)
-
end
-
-
1
def attribute_method_matcher(method_name) #:nodoc:
-
attribute_method_matchers_cache.compute_if_absent(method_name) do
-
# Must try to match prefixes/suffixes first, or else the matcher with no prefix/suffix
-
# will match every time.
-
matchers = attribute_method_matchers.partition(&:plain?).reverse.flatten(1)
-
match = nil
-
matchers.detect { |method| match = method.match(method_name) }
-
match
-
end
-
end
-
-
# Define a method `name` in `mod` that dispatches to `send`
-
# using the given `extra` args. This fallbacks `define_method`
-
# and `send` if the given names cannot be compiled.
-
1
def define_proxy_call(include_private, mod, name, send, *extra) #:nodoc:
-
defn = if name =~ NAME_COMPILABLE_REGEXP
-
"def #{name}(*args)"
-
else
-
"define_method(:'#{name}') do |*args|"
-
end
-
-
extra = (extra.map!(&:inspect) << "*args").join(", ")
-
-
target = if send =~ CALL_COMPILABLE_REGEXP
-
"#{"self." unless include_private}#{send}(#{extra})"
-
else
-
"send(:'#{send}', #{extra})"
-
end
-
-
mod.module_eval <<-RUBY, __FILE__, __LINE__ + 1
-
#{defn}
-
#{target}
-
end
-
RUBY
-
end
-
-
1
class AttributeMethodMatcher #:nodoc:
-
1
attr_reader :prefix, :suffix, :method_missing_target
-
-
1
AttributeMethodMatch = Struct.new(:target, :attr_name, :method_name)
-
-
1
def initialize(options = {})
-
9
@prefix, @suffix = options.fetch(:prefix, ''), options.fetch(:suffix, '')
-
9
@regex = /^(?:#{Regexp.escape(@prefix)})(.*)(?:#{Regexp.escape(@suffix)})$/
-
9
@method_missing_target = "#{@prefix}attribute#{@suffix}"
-
9
@method_name = "#{prefix}%s#{suffix}"
-
end
-
-
1
def match(method_name)
-
if @regex =~ method_name
-
AttributeMethodMatch.new(method_missing_target, $1, method_name)
-
end
-
end
-
-
1
def method_name(attr_name)
-
@method_name % attr_name
-
end
-
-
1
def plain?
-
prefix.empty? && suffix.empty?
-
end
-
end
-
end
-
-
# Allows access to the object attributes, which are held in the hash
-
# returned by <tt>attributes</tt>, as though they were first-class
-
# methods. So a +Person+ class with a +name+ attribute can for example use
-
# <tt>Person#name</tt> and <tt>Person#name=</tt> and never directly use
-
# the attributes hash -- except for multiple assigns with
-
# <tt>ActiveRecord::Base#attributes=</tt>.
-
#
-
# It's also possible to instantiate related objects, so a <tt>Client</tt>
-
# class belonging to the +clients+ table with a +master_id+ foreign key
-
# can instantiate master through <tt>Client#master</tt>.
-
1
def method_missing(method, *args, &block)
-
if respond_to_without_attributes?(method, true)
-
super
-
else
-
match = match_attribute_method?(method.to_s)
-
match ? attribute_missing(match, *args, &block) : super
-
end
-
end
-
-
# +attribute_missing+ is like +method_missing+, but for attributes. When
-
# +method_missing+ is called we check to see if there is a matching
-
# attribute method. If so, we tell +attribute_missing+ to dispatch the
-
# attribute. This method can be overloaded to customize the behavior.
-
1
def attribute_missing(match, *args, &block)
-
__send__(match.target, match.attr_name, *args, &block)
-
end
-
-
# A +Person+ instance with a +name+ attribute can ask
-
# <tt>person.respond_to?(:name)</tt>, <tt>person.respond_to?(:name=)</tt>,
-
# and <tt>person.respond_to?(:name?)</tt> which will all return +true+.
-
1
alias :respond_to_without_attributes? :respond_to?
-
1
def respond_to?(method, include_private_methods = false)
-
if super
-
true
-
elsif !include_private_methods && super(method, true)
-
# If we're here then we haven't found among non-private methods
-
# but found among all methods. Which means that the given method is private.
-
false
-
else
-
!match_attribute_method?(method.to_s).nil?
-
end
-
end
-
-
1
protected
-
1
def attribute_method?(attr_name) #:nodoc:
-
respond_to_without_attributes?(:attributes) && attributes.include?(attr_name)
-
end
-
-
1
private
-
# Returns a struct representing the matching attribute method.
-
# The struct's attributes are prefix, base and suffix.
-
1
def match_attribute_method?(method_name)
-
match = self.class.send(:attribute_method_matcher, method_name)
-
match if match && attribute_method?(match.attr_name)
-
end
-
-
1
def missing_attribute(attr_name, stack)
-
raise ActiveModel::MissingAttributeError, "missing attribute: #{attr_name}", stack
-
end
-
end
-
end
-
1
require 'active_support/core_ext/array/extract_options'
-
-
1
module ActiveModel
-
# == Active \Model \Callbacks
-
#
-
# Provides an interface for any class to have Active Record like callbacks.
-
#
-
# Like the Active Record methods, the callback chain is aborted as soon as
-
# one of the methods in the chain returns +false+.
-
#
-
# First, extend ActiveModel::Callbacks from the class you are creating:
-
#
-
# class MyModel
-
# extend ActiveModel::Callbacks
-
# end
-
#
-
# Then define a list of methods that you want callbacks attached to:
-
#
-
# define_model_callbacks :create, :update
-
#
-
# This will provide all three standard callbacks (before, around and after)
-
# for both the <tt>:create</tt> and <tt>:update</tt> methods. To implement,
-
# you need to wrap the methods you want callbacks on in a block so that the
-
# callbacks get a chance to fire:
-
#
-
# def create
-
# run_callbacks :create do
-
# # Your create action methods here
-
# end
-
# end
-
#
-
# Then in your class, you can use the +before_create+, +after_create+ and
-
# +around_create+ methods, just as you would in an Active Record model.
-
#
-
# before_create :action_before_create
-
#
-
# def action_before_create
-
# # Your code here
-
# end
-
#
-
# When defining an around callback remember to yield to the block, otherwise
-
# it won't be executed:
-
#
-
# around_create :log_status
-
#
-
# def log_status
-
# puts 'going to call the block...'
-
# yield
-
# puts 'block successfully called.'
-
# end
-
#
-
# You can choose not to have all three callbacks by passing a hash to the
-
# +define_model_callbacks+ method.
-
#
-
# define_model_callbacks :create, only: [:after, :before]
-
#
-
# Would only create the +after_create+ and +before_create+ callback methods in
-
# your class.
-
1
module Callbacks
-
1
def self.extended(base) #:nodoc:
-
1
base.class_eval do
-
1
include ActiveSupport::Callbacks
-
end
-
end
-
-
# define_model_callbacks accepts the same options +define_callbacks+ does,
-
# in case you want to overwrite a default. Besides that, it also accepts an
-
# <tt>:only</tt> option, where you can choose if you want all types (before,
-
# around or after) or just some.
-
#
-
# define_model_callbacks :initializer, only: :after
-
#
-
# Note, the <tt>only: <type></tt> hash will apply to all callbacks defined
-
# on that method call. To get around this you can call the define_model_callbacks
-
# method as many times as you need.
-
#
-
# define_model_callbacks :create, only: :after
-
# define_model_callbacks :update, only: :before
-
# define_model_callbacks :destroy, only: :around
-
#
-
# Would create +after_create+, +before_update+ and +around_destroy+ methods
-
# only.
-
#
-
# You can pass in a class to before_<type>, after_<type> and around_<type>,
-
# in which case the callback will call that class's <action>_<type> method
-
# passing the object that the callback is being called on.
-
#
-
# class MyModel
-
# extend ActiveModel::Callbacks
-
# define_model_callbacks :create
-
#
-
# before_create AnotherClass
-
# end
-
#
-
# class AnotherClass
-
# def self.before_create( obj )
-
# # obj is the MyModel instance that the callback is being called on
-
# end
-
# end
-
1
def define_model_callbacks(*callbacks)
-
2
options = callbacks.extract_options!
-
2
options = {
-
terminator: ->(_,result) { result == false },
-
skip_after_callbacks_if_terminated: true,
-
scope: [:kind, :name],
-
only: [:before, :around, :after]
-
}.merge!(options)
-
-
2
types = Array(options.delete(:only))
-
-
2
callbacks.each do |callback|
-
7
define_callbacks(callback, options)
-
-
7
types.each do |type|
-
15
send("_define_#{type}_model_callback", self, callback)
-
end
-
end
-
end
-
-
1
private
-
-
1
def _define_before_model_callback(klass, callback) #:nodoc:
-
4
klass.define_singleton_method("before_#{callback}") do |*args, &block|
-
11
set_callback(:"#{callback}", :before, *args, &block)
-
end
-
end
-
-
1
def _define_around_model_callback(klass, callback) #:nodoc:
-
4
klass.define_singleton_method("around_#{callback}") do |*args, &block|
-
set_callback(:"#{callback}", :around, *args, &block)
-
end
-
end
-
-
1
def _define_after_model_callback(klass, callback) #:nodoc:
-
7
klass.define_singleton_method("after_#{callback}") do |*args, &block|
-
19
options = args.extract_options!
-
19
options[:prepend] = true
-
19
conditional = ActiveSupport::Callbacks::Conditionals::Value.new { |v|
-
v != false
-
}
-
19
options[:if] = Array(options[:if]) << conditional
-
19
set_callback(:"#{callback}", :after, *(args << options), &block)
-
end
-
end
-
end
-
end
-
1
module ActiveModel
-
# == Active \Model \Conversion
-
#
-
# Handles default conversions: to_model, to_key, to_param, and to_partial_path.
-
#
-
# Let's take for example this non-persisted object.
-
#
-
# class ContactMessage
-
# include ActiveModel::Conversion
-
#
-
# # ContactMessage are never persisted in the DB
-
# def persisted?
-
# false
-
# end
-
# end
-
#
-
# cm = ContactMessage.new
-
# cm.to_model == cm # => true
-
# cm.to_key # => nil
-
# cm.to_param # => nil
-
# cm.to_partial_path # => "contact_messages/contact_message"
-
1
module Conversion
-
1
extend ActiveSupport::Concern
-
-
# If your object is already designed to implement all of the Active Model
-
# you can use the default <tt>:to_model</tt> implementation, which simply
-
# returns +self+.
-
#
-
# class Person
-
# include ActiveModel::Conversion
-
# end
-
#
-
# person = Person.new
-
# person.to_model == person # => true
-
#
-
# If your model does not act like an Active Model object, then you should
-
# define <tt>:to_model</tt> yourself returning a proxy object that wraps
-
# your object with Active Model compliant methods.
-
1
def to_model
-
self
-
end
-
-
# Returns an Enumerable of all key attributes if any is set, regardless if
-
# the object is persisted or not. Returns +nil+ if there are no key attributes.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# person = Person.create
-
# person.to_key # => [1]
-
1
def to_key
-
key = respond_to?(:id) && id
-
key ? [key] : nil
-
end
-
-
# Returns a +string+ representing the object's key suitable for use in URLs,
-
# or +nil+ if <tt>persisted?</tt> is +false+.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# person = Person.create
-
# person.to_param # => "1"
-
1
def to_param
-
(persisted? && key = to_key) ? key.join('-') : nil
-
end
-
-
# Returns a +string+ identifying the path associated with the object.
-
# ActionPack uses this to find a suitable partial to represent the object.
-
#
-
# class Person
-
# include ActiveModel::Conversion
-
# end
-
#
-
# person = Person.new
-
# person.to_partial_path # => "people/person"
-
1
def to_partial_path
-
self.class._to_partial_path
-
end
-
-
1
module ClassMethods #:nodoc:
-
# Provide a class level cache for #to_partial_path. This is an
-
# internal method and should not be accessed directly.
-
1
def _to_partial_path #:nodoc:
-
@_to_partial_path ||= begin
-
element = ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(self))
-
collection = ActiveSupport::Inflector.tableize(self)
-
"#{collection}/#{element}".freeze
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/hash_with_indifferent_access'
-
1
require 'active_support/core_ext/object/duplicable'
-
-
1
module ActiveModel
-
# == Active \Model \Dirty
-
#
-
# Provides a way to track changes in your object in the same way as
-
# Active Record does.
-
#
-
# The requirements for implementing ActiveModel::Dirty are:
-
#
-
# * <tt>include ActiveModel::Dirty</tt> in your object.
-
# * Call <tt>define_attribute_methods</tt> passing each method you want to
-
# track.
-
# * Call <tt>attr_name_will_change!</tt> before each change to the tracked
-
# attribute.
-
# * Call <tt>changes_applied</tt> after the changes are persisted.
-
# * Call <tt>reset_changes</tt> when you want to reset the changes
-
# information.
-
#
-
# A minimal implementation could be:
-
#
-
# class Person
-
# include ActiveModel::Dirty
-
#
-
# define_attribute_methods :name
-
#
-
# def name
-
# @name
-
# end
-
#
-
# def name=(val)
-
# name_will_change! unless val == @name
-
# @name = val
-
# end
-
#
-
# def save
-
# # do persistence work
-
# changes_applied
-
# end
-
#
-
# def reload!
-
# reset_changes
-
# end
-
# end
-
#
-
# A newly instantiated object is unchanged:
-
#
-
# person = Person.find_by(name: 'Uncle Bob')
-
# person.changed? # => false
-
#
-
# Change the name:
-
#
-
# person.name = 'Bob'
-
# person.changed? # => true
-
# person.name_changed? # => true
-
# person.name_changed?(from: "Uncle Bob", to: "Bob") # => true
-
# person.name_was # => "Uncle Bob"
-
# person.name_change # => ["Uncle Bob", "Bob"]
-
# person.name = 'Bill'
-
# person.name_change # => ["Uncle Bob", "Bill"]
-
#
-
# Save the changes:
-
#
-
# person.save
-
# person.changed? # => false
-
# person.name_changed? # => false
-
#
-
# Reset the changes:
-
#
-
# person.previous_changes # => {"name" => ["Uncle Bob", "Bill"]}
-
# person.reload!
-
# person.previous_changes # => {}
-
#
-
# Assigning the same value leaves the attribute unchanged:
-
#
-
# person.name = 'Bill'
-
# person.name_changed? # => false
-
# person.name_change # => nil
-
#
-
# Which attributes have changed?
-
#
-
# person.name = 'Bob'
-
# person.changed # => ["name"]
-
# person.changes # => {"name" => ["Bill", "Bob"]}
-
#
-
# If an attribute is modified in-place then make use of <tt>[attribute_name]_will_change!</tt>
-
# to mark that the attribute is changing. Otherwise ActiveModel can't track
-
# changes to in-place attributes.
-
#
-
# person.name_will_change!
-
# person.name_change # => ["Bill", "Bill"]
-
# person.name << 'y'
-
# person.name_change # => ["Bill", "Billy"]
-
1
module Dirty
-
1
extend ActiveSupport::Concern
-
1
include ActiveModel::AttributeMethods
-
-
1
included do
-
1
attribute_method_suffix '_changed?', '_change', '_will_change!', '_was'
-
1
attribute_method_affix prefix: 'reset_', suffix: '!'
-
end
-
-
# Returns +true+ if any attribute have unsaved changes, +false+ otherwise.
-
#
-
# person.changed? # => false
-
# person.name = 'bob'
-
# person.changed? # => true
-
1
def changed?
-
changed_attributes.present?
-
end
-
-
# Returns an array with the name of the attributes with unsaved changes.
-
#
-
# person.changed # => []
-
# person.name = 'bob'
-
# person.changed # => ["name"]
-
1
def changed
-
changed_attributes.keys
-
end
-
-
# Returns a hash of changed attributes indicating their original
-
# and new values like <tt>attr => [original value, new value]</tt>.
-
#
-
# person.changes # => {}
-
# person.name = 'bob'
-
# person.changes # => { "name" => ["bill", "bob"] }
-
1
def changes
-
ActiveSupport::HashWithIndifferentAccess[changed.map { |attr| [attr, attribute_change(attr)] }]
-
end
-
-
# Returns a hash of attributes that were changed before the model was saved.
-
#
-
# person.name # => "bob"
-
# person.name = 'robert'
-
# person.save
-
# person.previous_changes # => {"name" => ["bob", "robert"]}
-
1
def previous_changes
-
@previously_changed ||= ActiveSupport::HashWithIndifferentAccess.new
-
end
-
-
# Returns a hash of the attributes with unsaved changes indicating their original
-
# values like <tt>attr => original value</tt>.
-
#
-
# person.name # => "bob"
-
# person.name = 'robert'
-
# person.changed_attributes # => {"name" => "bob"}
-
1
def changed_attributes
-
@changed_attributes ||= ActiveSupport::HashWithIndifferentAccess.new
-
end
-
-
# Handle <tt>*_changed?</tt> for +method_missing+.
-
1
def attribute_changed?(attr, options = {}) #:nodoc:
-
result = changed_attributes.include?(attr)
-
result &&= options[:to] == __send__(attr) if options.key?(:to)
-
result &&= options[:from] == changed_attributes[attr] if options.key?(:from)
-
result
-
end
-
-
# Handle <tt>*_was</tt> for +method_missing+.
-
1
def attribute_was(attr) # :nodoc:
-
attribute_changed?(attr) ? changed_attributes[attr] : __send__(attr)
-
end
-
-
1
private
-
-
# Removes current changes and makes them accessible through +previous_changes+.
-
1
def changes_applied
-
@previously_changed = changes
-
@changed_attributes = ActiveSupport::HashWithIndifferentAccess.new
-
end
-
-
# Removes all dirty data: current changes and previous changes
-
1
def reset_changes
-
@previously_changed = ActiveSupport::HashWithIndifferentAccess.new
-
@changed_attributes = ActiveSupport::HashWithIndifferentAccess.new
-
end
-
-
# Handle <tt>*_change</tt> for +method_missing+.
-
1
def attribute_change(attr)
-
[changed_attributes[attr], __send__(attr)] if attribute_changed?(attr)
-
end
-
-
# Handle <tt>*_will_change!</tt> for +method_missing+.
-
1
def attribute_will_change!(attr)
-
return if attribute_changed?(attr)
-
-
begin
-
value = __send__(attr)
-
value = value.duplicable? ? value.clone : value
-
rescue TypeError, NoMethodError
-
end
-
-
changed_attributes[attr] = value
-
end
-
-
# Handle <tt>reset_*!</tt> for +method_missing+.
-
1
def reset_attribute!(attr)
-
if attribute_changed?(attr)
-
__send__("#{attr}=", changed_attributes[attr])
-
changed_attributes.delete(attr)
-
end
-
end
-
end
-
end
-
1
module ActiveModel
-
# Raised when forbidden attributes are used for mass assignment.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# params = ActionController::Parameters.new(name: 'Bob')
-
# Person.new(params)
-
# # => ActiveModel::ForbiddenAttributesError
-
#
-
# params.permit!
-
# Person.new(params)
-
# # => #<Person id: nil, name: "Bob">
-
1
class ForbiddenAttributesError < StandardError
-
end
-
-
1
module ForbiddenAttributesProtection # :nodoc:
-
1
protected
-
1
def sanitize_for_mass_assignment(attributes)
-
if attributes.respond_to?(:permitted?) && !attributes.permitted?
-
raise ActiveModel::ForbiddenAttributesError
-
else
-
attributes
-
end
-
end
-
end
-
end
-
1
module ActiveModel
-
# Returns the version of the currently loaded ActiveModel as a <tt>Gem::Version</tt>
-
1
def self.gem_version
-
Gem::Version.new VERSION::STRING
-
end
-
-
1
module VERSION
-
1
MAJOR = 4
-
1
MINOR = 1
-
1
TINY = 0
-
1
PRE = nil
-
-
1
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
-
end
-
end
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/module/introspection'
-
-
1
module ActiveModel
-
1
class Name
-
1
include Comparable
-
-
1
attr_reader :singular, :plural, :element, :collection,
-
:singular_route_key, :route_key, :param_key, :i18n_key,
-
:name
-
-
1
alias_method :cache_key, :collection
-
-
##
-
# :method: ==
-
#
-
# :call-seq:
-
# ==(other)
-
#
-
# Equivalent to <tt>String#==</tt>. Returns +true+ if the class name and
-
# +other+ are equal, otherwise +false+.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name == 'BlogPost' # => true
-
# BlogPost.model_name == 'Blog Post' # => false
-
-
##
-
# :method: ===
-
#
-
# :call-seq:
-
# ===(other)
-
#
-
# Equivalent to <tt>#==</tt>.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name === 'BlogPost' # => true
-
# BlogPost.model_name === 'Blog Post' # => false
-
-
##
-
# :method: <=>
-
#
-
# :call-seq:
-
# ==(other)
-
#
-
# Equivalent to <tt>String#<=></tt>.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name <=> 'BlogPost' # => 0
-
# BlogPost.model_name <=> 'Blog' # => 1
-
# BlogPost.model_name <=> 'BlogPosts' # => -1
-
-
##
-
# :method: =~
-
#
-
# :call-seq:
-
# =~(regexp)
-
#
-
# Equivalent to <tt>String#=~</tt>. Match the class name against the given
-
# regexp. Returns the position where the match starts or +nil+ if there is
-
# no match.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name =~ /Post/ # => 4
-
# BlogPost.model_name =~ /\d/ # => nil
-
-
##
-
# :method: !~
-
#
-
# :call-seq:
-
# !~(regexp)
-
#
-
# Equivalent to <tt>String#!~</tt>. Match the class name against the given
-
# regexp. Returns +true+ if there is no match, otherwise +false+.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name !~ /Post/ # => false
-
# BlogPost.model_name !~ /\d/ # => true
-
-
##
-
# :method: eql?
-
#
-
# :call-seq:
-
# eql?(other)
-
#
-
# Equivalent to <tt>String#eql?</tt>. Returns +true+ if the class name and
-
# +other+ have the same length and content, otherwise +false+.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name.eql?('BlogPost') # => true
-
# BlogPost.model_name.eql?('Blog Post') # => false
-
-
##
-
# :method: to_s
-
#
-
# :call-seq:
-
# to_s()
-
#
-
# Returns the class name.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name.to_s # => "BlogPost"
-
-
##
-
# :method: to_str
-
#
-
# :call-seq:
-
# to_str()
-
#
-
# Equivalent to +to_s+.
-
1
delegate :==, :===, :<=>, :=~, :"!~", :eql?, :to_s,
-
:to_str, to: :name
-
-
# Returns a new ActiveModel::Name instance. By default, the +namespace+
-
# and +name+ option will take the namespace and name of the given class
-
# respectively.
-
#
-
# module Foo
-
# class Bar
-
# end
-
# end
-
#
-
# ActiveModel::Name.new(Foo::Bar).to_s
-
# # => "Foo::Bar"
-
1
def initialize(klass, namespace = nil, name = nil)
-
@name = name || klass.name
-
-
raise ArgumentError, "Class name cannot be blank. You need to supply a name argument when anonymous class given" if @name.blank?
-
-
@unnamespaced = @name.sub(/^#{namespace.name}::/, '') if namespace
-
@klass = klass
-
@singular = _singularize(@name)
-
@plural = ActiveSupport::Inflector.pluralize(@singular)
-
@element = ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(@name))
-
@human = ActiveSupport::Inflector.humanize(@element)
-
@collection = ActiveSupport::Inflector.tableize(@name)
-
@param_key = (namespace ? _singularize(@unnamespaced) : @singular)
-
@i18n_key = @name.underscore.to_sym
-
-
@route_key = (namespace ? ActiveSupport::Inflector.pluralize(@param_key) : @plural.dup)
-
@singular_route_key = ActiveSupport::Inflector.singularize(@route_key)
-
@route_key << "_index" if @plural == @singular
-
end
-
-
# Transform the model name into a more humane format, using I18n. By default,
-
# it will underscore then humanize the class name.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name.human # => "Blog post"
-
#
-
# Specify +options+ with additional translating options.
-
1
def human(options={})
-
return @human unless @klass.respond_to?(:lookup_ancestors) &&
-
@klass.respond_to?(:i18n_scope)
-
-
defaults = @klass.lookup_ancestors.map do |klass|
-
klass.model_name.i18n_key
-
end
-
-
defaults << options[:default] if options[:default]
-
defaults << @human
-
-
options = { scope: [@klass.i18n_scope, :models], count: 1, default: defaults }.merge!(options.except(:default))
-
I18n.translate(defaults.shift, options)
-
end
-
-
1
private
-
-
1
def _singularize(string, replacement='_')
-
ActiveSupport::Inflector.underscore(string).tr('/', replacement)
-
end
-
end
-
-
# == Active \Model \Naming
-
#
-
# Creates a +model_name+ method on your object.
-
#
-
# To implement, just extend ActiveModel::Naming in your object:
-
#
-
# class BookCover
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BookCover.model_name # => "BookCover"
-
# BookCover.model_name.human # => "Book cover"
-
#
-
# BookCover.model_name.i18n_key # => :book_cover
-
# BookModule::BookCover.model_name.i18n_key # => :"book_module/book_cover"
-
#
-
# Providing the functionality that ActiveModel::Naming provides in your object
-
# is required to pass the Active Model Lint test. So either extending the
-
# provided method below, or rolling your own is required.
-
1
module Naming
-
# Returns an ActiveModel::Name object for module. It can be
-
# used to retrieve all kinds of naming-related information
-
# (See ActiveModel::Name for more information).
-
#
-
# class Person < ActiveModel::Model
-
# end
-
#
-
# Person.model_name # => Person
-
# Person.model_name.class # => ActiveModel::Name
-
# Person.model_name.singular # => "person"
-
# Person.model_name.plural # => "people"
-
1
def model_name
-
@_model_name ||= begin
-
namespace = self.parents.detect do |n|
-
n.respond_to?(:use_relative_model_naming?) && n.use_relative_model_naming?
-
end
-
ActiveModel::Name.new(self, namespace)
-
end
-
end
-
-
# Returns the plural class name of a record or class.
-
#
-
# ActiveModel::Naming.plural(post) # => "posts"
-
# ActiveModel::Naming.plural(Highrise::Person) # => "highrise_people"
-
1
def self.plural(record_or_class)
-
model_name_from_record_or_class(record_or_class).plural
-
end
-
-
# Returns the singular class name of a record or class.
-
#
-
# ActiveModel::Naming.singular(post) # => "post"
-
# ActiveModel::Naming.singular(Highrise::Person) # => "highrise_person"
-
1
def self.singular(record_or_class)
-
model_name_from_record_or_class(record_or_class).singular
-
end
-
-
# Identifies whether the class name of a record or class is uncountable.
-
#
-
# ActiveModel::Naming.uncountable?(Sheep) # => true
-
# ActiveModel::Naming.uncountable?(Post) # => false
-
1
def self.uncountable?(record_or_class)
-
plural(record_or_class) == singular(record_or_class)
-
end
-
-
# Returns string to use while generating route names. It differs for
-
# namespaced models regarding whether it's inside isolated engine.
-
#
-
# # For isolated engine:
-
# ActiveModel::Naming.singular_route_key(Blog::Post) # => "post"
-
#
-
# # For shared engine:
-
# ActiveModel::Naming.singular_route_key(Blog::Post) # => "blog_post"
-
1
def self.singular_route_key(record_or_class)
-
model_name_from_record_or_class(record_or_class).singular_route_key
-
end
-
-
# Returns string to use while generating route names. It differs for
-
# namespaced models regarding whether it's inside isolated engine.
-
#
-
# # For isolated engine:
-
# ActiveModel::Naming.route_key(Blog::Post) # => "posts"
-
#
-
# # For shared engine:
-
# ActiveModel::Naming.route_key(Blog::Post) # => "blog_posts"
-
#
-
# The route key also considers if the noun is uncountable and, in
-
# such cases, automatically appends _index.
-
1
def self.route_key(record_or_class)
-
model_name_from_record_or_class(record_or_class).route_key
-
end
-
-
# Returns string to use for params names. It differs for
-
# namespaced models regarding whether it's inside isolated engine.
-
#
-
# # For isolated engine:
-
# ActiveModel::Naming.param_key(Blog::Post) # => "post"
-
#
-
# # For shared engine:
-
# ActiveModel::Naming.param_key(Blog::Post) # => "blog_post"
-
1
def self.param_key(record_or_class)
-
model_name_from_record_or_class(record_or_class).param_key
-
end
-
-
1
def self.model_name_from_record_or_class(record_or_class) #:nodoc:
-
if record_or_class.respond_to?(:model_name)
-
record_or_class.model_name
-
elsif record_or_class.respond_to?(:to_model)
-
record_or_class.to_model.class.model_name
-
else
-
record_or_class.class.model_name
-
end
-
end
-
1
private_class_method :model_name_from_record_or_class
-
end
-
end
-
1
require "active_model"
-
1
require "rails"
-
-
1
module ActiveModel
-
1
class Railtie < Rails::Railtie # :nodoc:
-
1
config.eager_load_namespaces << ActiveModel
-
-
1
initializer "active_model.secure_password" do
-
1
ActiveModel::SecurePassword.min_cost = Rails.env.test?
-
end
-
end
-
end
-
1
module ActiveModel
-
1
module SecurePassword
-
1
extend ActiveSupport::Concern
-
-
1
class << self
-
1
attr_accessor :min_cost # :nodoc:
-
end
-
1
self.min_cost = false
-
-
1
module ClassMethods
-
# Adds methods to set and authenticate against a BCrypt password.
-
# This mechanism requires you to have a +password_digest+ attribute.
-
#
-
# Validations for presence of password on create, confirmation of password
-
# (using a +password_confirmation+ attribute) are automatically added. If
-
# you wish to turn off validations, pass <tt>validations: false</tt> as an
-
# argument. You can add more validations by hand if need be.
-
#
-
# If you don't need the confirmation validation, just don't set any
-
# value to the password_confirmation attribute and the validation
-
# will not be triggered.
-
#
-
# You need to add bcrypt (~> 3.1.7) to Gemfile to use #has_secure_password:
-
#
-
# gem 'bcrypt', '~> 3.1.7'
-
#
-
# Example using Active Record (which automatically includes ActiveModel::SecurePassword):
-
#
-
# # Schema: User(name:string, password_digest:string)
-
# class User < ActiveRecord::Base
-
# has_secure_password
-
# end
-
#
-
# user = User.new(name: 'david', password: '', password_confirmation: 'nomatch')
-
# user.save # => false, password required
-
# user.password = 'mUc3m00RsqyRe'
-
# user.save # => false, confirmation doesn't match
-
# user.password_confirmation = 'mUc3m00RsqyRe'
-
# user.save # => true
-
# user.authenticate('notright') # => false
-
# user.authenticate('mUc3m00RsqyRe') # => user
-
# User.find_by(name: 'david').try(:authenticate, 'notright') # => false
-
# User.find_by(name: 'david').try(:authenticate, 'mUc3m00RsqyRe') # => user
-
1
def has_secure_password(options = {})
-
# Load bcrypt gem only when has_secure_password is used.
-
# This is to avoid ActiveModel (and by extension the entire framework)
-
# being dependent on a binary library.
-
begin
-
require 'bcrypt'
-
rescue LoadError
-
$stderr.puts "You don't have bcrypt installed in your application. Please add it to your Gemfile and run bundle install"
-
raise
-
end
-
-
attr_reader :password
-
-
include InstanceMethodsOnActivation
-
-
if options.fetch(:validations, true)
-
# This ensures the model has a password by checking whether the password_digest
-
# is present, so that this works with both new and existing records. However,
-
# when there is an error, the message is added to the password attribute instead
-
# so that the error message will make sense to the end-user.
-
validate do |record|
-
record.errors.add(:password, :blank) unless record.password_digest.present?
-
end
-
-
validates_confirmation_of :password, if: ->{ password.present? }
-
end
-
-
if respond_to?(:attributes_protected_by_default)
-
def self.attributes_protected_by_default #:nodoc:
-
super + ['password_digest']
-
end
-
end
-
end
-
end
-
-
1
module InstanceMethodsOnActivation
-
# Returns +self+ if the password is correct, otherwise +false+.
-
#
-
# class User < ActiveRecord::Base
-
# has_secure_password validations: false
-
# end
-
#
-
# user = User.new(name: 'david', password: 'mUc3m00RsqyRe')
-
# user.save
-
# user.authenticate('notright') # => false
-
# user.authenticate('mUc3m00RsqyRe') # => user
-
1
def authenticate(unencrypted_password)
-
BCrypt::Password.new(password_digest) == unencrypted_password && self
-
end
-
-
# Encrypts the password into the +password_digest+ attribute, only if the
-
# new password is not blank.
-
#
-
# class User < ActiveRecord::Base
-
# has_secure_password validations: false
-
# end
-
#
-
# user = User.new
-
# user.password = nil
-
# user.password_digest # => nil
-
# user.password = 'mUc3m00RsqyRe'
-
# user.password_digest # => "$2a$10$4LEA7r4YmNHtvlAvHhsYAeZmk/xeUVtMTYqwIvYY76EW5GUqDiP4."
-
1
def password=(unencrypted_password)
-
if unencrypted_password.nil?
-
self.password_digest = nil
-
elsif unencrypted_password.present?
-
@password = unencrypted_password
-
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost
-
self.password_digest = BCrypt::Password.create(unencrypted_password, cost: cost)
-
end
-
end
-
-
1
def password_confirmation=(unencrypted_password)
-
@password_confirmation = unencrypted_password
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/hash/slice'
-
-
1
module ActiveModel
-
# == Active \Model \Serialization
-
#
-
# Provides a basic serialization to a serializable_hash for your object.
-
#
-
# A minimal implementation could be:
-
#
-
# class Person
-
# include ActiveModel::Serialization
-
#
-
# attr_accessor :name
-
#
-
# def attributes
-
# {'name' => nil}
-
# end
-
# end
-
#
-
# Which would provide you with:
-
#
-
# person = Person.new
-
# person.serializable_hash # => {"name"=>nil}
-
# person.name = "Bob"
-
# person.serializable_hash # => {"name"=>"Bob"}
-
#
-
# You need to declare an attributes hash which contains the attributes you
-
# want to serialize. Attributes must be strings, not symbols. When called,
-
# serializable hash will use instance methods that match the name of the
-
# attributes hash's keys. In order to override this behavior, take a look at
-
# the private method +read_attribute_for_serialization+.
-
#
-
# Most of the time though, you will want to include the JSON or XML
-
# serializations. Both of these modules automatically include the
-
# <tt>ActiveModel::Serialization</tt> module, so there is no need to
-
# explicitly include it.
-
#
-
# A minimal implementation including XML and JSON would be:
-
#
-
# class Person
-
# include ActiveModel::Serializers::JSON
-
# include ActiveModel::Serializers::Xml
-
#
-
# attr_accessor :name
-
#
-
# def attributes
-
# {'name' => nil}
-
# end
-
# end
-
#
-
# Which would provide you with:
-
#
-
# person = Person.new
-
# person.serializable_hash # => {"name"=>nil}
-
# person.as_json # => {"name"=>nil}
-
# person.to_json # => "{\"name\":null}"
-
# person.to_xml # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<serial-person...
-
#
-
# person.name = "Bob"
-
# person.serializable_hash # => {"name"=>"Bob"}
-
# person.as_json # => {"name"=>"Bob"}
-
# person.to_json # => "{\"name\":\"Bob\"}"
-
# person.to_xml # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<serial-person...
-
#
-
# Valid options are <tt>:only</tt>, <tt>:except</tt>, <tt>:methods</tt> and
-
# <tt>:include</tt>. The following are all valid examples:
-
#
-
# person.serializable_hash(only: 'name')
-
# person.serializable_hash(include: :address)
-
# person.serializable_hash(include: { address: { only: 'city' }})
-
1
module Serialization
-
# Returns a serialized hash of your object.
-
#
-
# class Person
-
# include ActiveModel::Serialization
-
#
-
# attr_accessor :name, :age
-
#
-
# def attributes
-
# {'name' => nil, 'age' => nil}
-
# end
-
#
-
# def capitalized_name
-
# name.capitalize
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = 'bob'
-
# person.age = 22
-
# person.serializable_hash # => {"name"=>"bob", "age"=>22}
-
# person.serializable_hash(only: :name) # => {"name"=>"bob"}
-
# person.serializable_hash(except: :name) # => {"age"=>22}
-
# person.serializable_hash(methods: :capitalized_name)
-
# # => {"name"=>"bob", "age"=>22, "capitalized_name"=>"Bob"}
-
1
def serializable_hash(options = nil)
-
options ||= {}
-
-
attribute_names = attributes.keys
-
if only = options[:only]
-
attribute_names &= Array(only).map(&:to_s)
-
elsif except = options[:except]
-
attribute_names -= Array(except).map(&:to_s)
-
end
-
-
hash = {}
-
attribute_names.each { |n| hash[n] = read_attribute_for_serialization(n) }
-
-
Array(options[:methods]).each { |m| hash[m.to_s] = send(m) if respond_to?(m) }
-
-
serializable_add_includes(options) do |association, records, opts|
-
hash[association.to_s] = if records.respond_to?(:to_ary)
-
records.to_ary.map { |a| a.serializable_hash(opts) }
-
else
-
records.serializable_hash(opts)
-
end
-
end
-
-
hash
-
end
-
-
1
private
-
-
# Hook method defining how an attribute value should be retrieved for
-
# serialization. By default this is assumed to be an instance named after
-
# the attribute. Override this method in subclasses should you need to
-
# retrieve the value for a given attribute differently:
-
#
-
# class MyClass
-
# include ActiveModel::Serialization
-
#
-
# def initialize(data = {})
-
# @data = data
-
# end
-
#
-
# def read_attribute_for_serialization(key)
-
# @data[key]
-
# end
-
# end
-
1
alias :read_attribute_for_serialization :send
-
-
# Add associations specified via the <tt>:include</tt> option.
-
#
-
# Expects a block that takes as arguments:
-
# +association+ - name of the association
-
# +records+ - the association record(s) to be serialized
-
# +opts+ - options for the association records
-
1
def serializable_add_includes(options = {}) #:nodoc:
-
return unless includes = options[:include]
-
-
unless includes.is_a?(Hash)
-
includes = Hash[Array(includes).map { |n| n.is_a?(Hash) ? n.to_a.first : [n, {}] }]
-
end
-
-
includes.each do |association, opts|
-
if records = send(association)
-
yield association, records, opts
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/json'
-
-
1
module ActiveModel
-
1
module Serializers
-
# == Active \Model \JSON \Serializer
-
1
module JSON
-
1
extend ActiveSupport::Concern
-
1
include ActiveModel::Serialization
-
-
1
included do
-
1
extend ActiveModel::Naming
-
-
1
class_attribute :include_root_in_json
-
1
self.include_root_in_json = false
-
end
-
-
# Returns a hash representing the model. Some configuration can be
-
# passed through +options+.
-
#
-
# The option <tt>include_root_in_json</tt> controls the top-level behavior
-
# of +as_json+. If +true+, +as_json+ will emit a single root node named
-
# after the object's type. The default value for <tt>include_root_in_json</tt>
-
# option is +false+.
-
#
-
# user = User.find(1)
-
# user.as_json
-
# # => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
-
# # "created_at" => "2006/08/01", "awesome" => true}
-
#
-
# ActiveRecord::Base.include_root_in_json = true
-
#
-
# user.as_json
-
# # => { "user" => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
-
# # "created_at" => "2006/08/01", "awesome" => true } }
-
#
-
# This behavior can also be achieved by setting the <tt>:root</tt> option
-
# to +true+ as in:
-
#
-
# user = User.find(1)
-
# user.as_json(root: true)
-
# # => { "user" => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
-
# # "created_at" => "2006/08/01", "awesome" => true } }
-
#
-
# Without any +options+, the returned Hash will include all the model's
-
# attributes.
-
#
-
# user = User.find(1)
-
# user.as_json
-
# # => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
-
# # "created_at" => "2006/08/01", "awesome" => true}
-
#
-
# The <tt>:only</tt> and <tt>:except</tt> options can be used to limit
-
# the attributes included, and work similar to the +attributes+ method.
-
#
-
# user.as_json(only: [:id, :name])
-
# # => { "id" => 1, "name" => "Konata Izumi" }
-
#
-
# user.as_json(except: [:id, :created_at, :age])
-
# # => { "name" => "Konata Izumi", "awesome" => true }
-
#
-
# To include the result of some method calls on the model use <tt>:methods</tt>:
-
#
-
# user.as_json(methods: :permalink)
-
# # => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
-
# # "created_at" => "2006/08/01", "awesome" => true,
-
# # "permalink" => "1-konata-izumi" }
-
#
-
# To include associations use <tt>:include</tt>:
-
#
-
# user.as_json(include: :posts)
-
# # => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
-
# # "created_at" => "2006/08/01", "awesome" => true,
-
# # "posts" => [ { "id" => 1, "author_id" => 1, "title" => "Welcome to the weblog" },
-
# # { "id" => 2, "author_id" => 1, "title" => "So I was thinking" } ] }
-
#
-
# Second level and higher order associations work as well:
-
#
-
# user.as_json(include: { posts: {
-
# include: { comments: {
-
# only: :body } },
-
# only: :title } })
-
# # => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
-
# # "created_at" => "2006/08/01", "awesome" => true,
-
# # "posts" => [ { "comments" => [ { "body" => "1st post!" }, { "body" => "Second!" } ],
-
# # "title" => "Welcome to the weblog" },
-
# # { "comments" => [ { "body" => "Don't think too hard" } ],
-
# # "title" => "So I was thinking" } ] }
-
1
def as_json(options = nil)
-
root = if options && options.key?(:root)
-
options[:root]
-
else
-
include_root_in_json
-
end
-
-
if root
-
root = self.class.model_name.element if root == true
-
{ root => serializable_hash(options) }
-
else
-
serializable_hash(options)
-
end
-
end
-
-
# Sets the model +attributes+ from a JSON string. Returns +self+.
-
#
-
# class Person
-
# include ActiveModel::Serializers::JSON
-
#
-
# attr_accessor :name, :age, :awesome
-
#
-
# def attributes=(hash)
-
# hash.each do |key, value|
-
# send("#{key}=", value)
-
# end
-
# end
-
#
-
# def attributes
-
# instance_values
-
# end
-
# end
-
#
-
# json = { name: 'bob', age: 22, awesome:true }.to_json
-
# person = Person.new
-
# person.from_json(json) # => #<Person:0x007fec5e7a0088 @age=22, @awesome=true, @name="bob">
-
# person.name # => "bob"
-
# person.age # => 22
-
# person.awesome # => true
-
#
-
# The default value for +include_root+ is +false+. You can change it to
-
# +true+ if the given JSON string includes a single root node.
-
#
-
# json = { person: { name: 'bob', age: 22, awesome:true } }.to_json
-
# person = Person.new
-
# person.from_json(json) # => #<Person:0x007fec5e7a0088 @age=22, @awesome=true, @name="bob">
-
# person.name # => "bob"
-
# person.age # => 22
-
# person.awesome # => true
-
1
def from_json(json, include_root=include_root_in_json)
-
hash = ActiveSupport::JSON.decode(json)
-
hash = hash.values.first if include_root
-
self.attributes = hash
-
self
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/array/conversions'
-
1
require 'active_support/core_ext/hash/conversions'
-
1
require 'active_support/core_ext/hash/slice'
-
1
require 'active_support/core_ext/time/acts_like'
-
-
1
module ActiveModel
-
1
module Serializers
-
# == Active Model XML Serializer
-
1
module Xml
-
1
extend ActiveSupport::Concern
-
1
include ActiveModel::Serialization
-
-
1
included do
-
1
extend ActiveModel::Naming
-
end
-
-
1
class Serializer #:nodoc:
-
1
class Attribute #:nodoc:
-
1
attr_reader :name, :value, :type
-
-
1
def initialize(name, serializable, value)
-
@name, @serializable = name, serializable
-
-
if value.acts_like?(:time) && value.respond_to?(:in_time_zone)
-
value = value.in_time_zone
-
end
-
-
@value = value
-
@type = compute_type
-
end
-
-
1
def decorations
-
decorations = {}
-
decorations[:encoding] = 'base64' if type == :binary
-
decorations[:type] = (type == :string) ? nil : type
-
decorations[:nil] = true if value.nil?
-
decorations
-
end
-
-
1
protected
-
-
1
def compute_type
-
return if value.nil?
-
type = ActiveSupport::XmlMini::TYPE_NAMES[value.class.name]
-
type ||= :string if value.respond_to?(:to_str)
-
type ||= :yaml
-
type
-
end
-
end
-
-
1
class MethodAttribute < Attribute #:nodoc:
-
end
-
-
1
attr_reader :options
-
-
1
def initialize(serializable, options = nil)
-
@serializable = serializable
-
@options = options ? options.dup : {}
-
end
-
-
1
def serializable_hash
-
@serializable.serializable_hash(@options.except(:include))
-
end
-
-
1
def serializable_collection
-
methods = Array(options[:methods]).map(&:to_s)
-
serializable_hash.map do |name, value|
-
name = name.to_s
-
if methods.include?(name)
-
self.class::MethodAttribute.new(name, @serializable, value)
-
else
-
self.class::Attribute.new(name, @serializable, value)
-
end
-
end
-
end
-
-
1
def serialize
-
require 'builder' unless defined? ::Builder
-
-
options[:indent] ||= 2
-
options[:builder] ||= ::Builder::XmlMarkup.new(indent: options[:indent])
-
-
@builder = options[:builder]
-
@builder.instruct! unless options[:skip_instruct]
-
-
root = (options[:root] || @serializable.class.model_name.element).to_s
-
root = ActiveSupport::XmlMini.rename_key(root, options)
-
-
args = [root]
-
args << { xmlns: options[:namespace] } if options[:namespace]
-
args << { type: options[:type] } if options[:type] && !options[:skip_types]
-
-
@builder.tag!(*args) do
-
add_attributes_and_methods
-
add_includes
-
add_extra_behavior
-
add_procs
-
yield @builder if block_given?
-
end
-
end
-
-
1
private
-
-
1
def add_extra_behavior
-
end
-
-
1
def add_attributes_and_methods
-
serializable_collection.each do |attribute|
-
key = ActiveSupport::XmlMini.rename_key(attribute.name, options)
-
ActiveSupport::XmlMini.to_tag(key, attribute.value,
-
options.merge(attribute.decorations))
-
end
-
end
-
-
1
def add_includes
-
@serializable.send(:serializable_add_includes, options) do |association, records, opts|
-
add_associations(association, records, opts)
-
end
-
end
-
-
# TODO: This can likely be cleaned up to simple use ActiveSupport::XmlMini.to_tag as well.
-
1
def add_associations(association, records, opts)
-
merged_options = opts.merge(options.slice(:builder, :indent))
-
merged_options[:skip_instruct] = true
-
-
[:skip_types, :dasherize, :camelize].each do |key|
-
merged_options[key] = options[key] if merged_options[key].nil? && !options[key].nil?
-
end
-
-
if records.respond_to?(:to_ary)
-
records = records.to_ary
-
-
tag = ActiveSupport::XmlMini.rename_key(association.to_s, options)
-
type = options[:skip_types] ? { } : { type: "array" }
-
association_name = association.to_s.singularize
-
merged_options[:root] = association_name
-
-
if records.empty?
-
@builder.tag!(tag, type)
-
else
-
@builder.tag!(tag, type) do
-
records.each do |record|
-
if options[:skip_types]
-
record_type = {}
-
else
-
record_class = (record.class.to_s.underscore == association_name) ? nil : record.class.name
-
record_type = { type: record_class }
-
end
-
-
record.to_xml merged_options.merge(record_type)
-
end
-
end
-
end
-
else
-
merged_options[:root] = association.to_s
-
-
unless records.class.to_s.underscore == association.to_s
-
merged_options[:type] = records.class.name
-
end
-
-
records.to_xml merged_options
-
end
-
end
-
-
1
def add_procs
-
if procs = options.delete(:procs)
-
Array(procs).each do |proc|
-
if proc.arity == 1
-
proc.call(options)
-
else
-
proc.call(options, @serializable)
-
end
-
end
-
end
-
end
-
end
-
-
# Returns XML representing the model. Configuration can be
-
# passed through +options+.
-
#
-
# Without any +options+, the returned XML string will include all the
-
# model's attributes.
-
#
-
# user = User.find(1)
-
# user.to_xml
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <user>
-
# <id type="integer">1</id>
-
# <name>David</name>
-
# <age type="integer">16</age>
-
# <created-at type="dateTime">2011-01-30T22:29:23Z</created-at>
-
# </user>
-
#
-
# The <tt>:only</tt> and <tt>:except</tt> options can be used to limit the
-
# attributes included, and work similar to the +attributes+ method.
-
#
-
# To include the result of some method calls on the model use <tt>:methods</tt>.
-
#
-
# To include associations use <tt>:include</tt>.
-
#
-
# For further documentation, see <tt>ActiveRecord::Serialization#to_xml</tt>
-
1
def to_xml(options = {}, &block)
-
Serializer.new(self, options).serialize(&block)
-
end
-
-
# Sets the model +attributes+ from an XML string. Returns +self+.
-
#
-
# class Person
-
# include ActiveModel::Serializers::Xml
-
#
-
# attr_accessor :name, :age, :awesome
-
#
-
# def attributes=(hash)
-
# hash.each do |key, value|
-
# instance_variable_set("@#{key}", value)
-
# end
-
# end
-
#
-
# def attributes
-
# instance_values
-
# end
-
# end
-
#
-
# xml = { name: 'bob', age: 22, awesome:true }.to_xml
-
# person = Person.new
-
# person.from_xml(xml) # => #<Person:0x007fec5e3b3c40 @age=22, @awesome=true, @name="bob">
-
# person.name # => "bob"
-
# person.age # => 22
-
# person.awesome # => true
-
1
def from_xml(xml)
-
self.attributes = Hash.from_xml(xml).values.first
-
self
-
end
-
end
-
end
-
end
-
1
module ActiveModel
-
-
# == Active \Model \Translation
-
#
-
# Provides integration between your object and the Rails internationalization
-
# (i18n) framework.
-
#
-
# A minimal implementation could be:
-
#
-
# class TranslatedPerson
-
# extend ActiveModel::Translation
-
# end
-
#
-
# TranslatedPerson.human_attribute_name('my_attribute')
-
# # => "My attribute"
-
#
-
# This also provides the required class methods for hooking into the
-
# Rails internationalization API, including being able to define a
-
# class based +i18n_scope+ and +lookup_ancestors+ to find translations in
-
# parent classes.
-
1
module Translation
-
1
include ActiveModel::Naming
-
-
# Returns the +i18n_scope+ for the class. Overwrite if you want custom lookup.
-
1
def i18n_scope
-
:activemodel
-
end
-
-
# When localizing a string, it goes through the lookup returned by this
-
# method, which is used in ActiveModel::Name#human,
-
# ActiveModel::Errors#full_messages and
-
# ActiveModel::Translation#human_attribute_name.
-
1
def lookup_ancestors
-
self.ancestors.select { |x| x.respond_to?(:model_name) }
-
end
-
-
# Transforms attribute names into a more human format, such as "First name"
-
# instead of "first_name".
-
#
-
# Person.human_attribute_name("first_name") # => "First name"
-
#
-
# Specify +options+ with additional translating options.
-
1
def human_attribute_name(attribute, options = {})
-
options = { count: 1 }.merge!(options)
-
parts = attribute.to_s.split(".")
-
attribute = parts.pop
-
namespace = parts.join("/") unless parts.empty?
-
attributes_scope = "#{self.i18n_scope}.attributes"
-
-
if namespace
-
defaults = lookup_ancestors.map do |klass|
-
:"#{attributes_scope}.#{klass.model_name.i18n_key}/#{namespace}.#{attribute}"
-
end
-
defaults << :"#{attributes_scope}.#{namespace}.#{attribute}"
-
else
-
defaults = lookup_ancestors.map do |klass|
-
:"#{attributes_scope}.#{klass.model_name.i18n_key}.#{attribute}"
-
end
-
end
-
-
defaults << :"attributes.#{attribute}"
-
defaults << options.delete(:default) if options[:default]
-
defaults << attribute.humanize
-
-
options[:default] = defaults
-
I18n.translate(defaults.shift, options)
-
end
-
end
-
end
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'active_support/core_ext/hash/keys'
-
1
require 'active_support/core_ext/hash/except'
-
-
1
module ActiveModel
-
-
# == Active \Model \Validations
-
#
-
# Provides a full validation framework to your objects.
-
#
-
# A minimal implementation could be:
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :first_name, :last_name
-
#
-
# validates_each :first_name, :last_name do |record, attr, value|
-
# record.errors.add attr, 'starts with z.' if value.to_s[0] == ?z
-
# end
-
# end
-
#
-
# Which provides you with the full standard validation stack that you
-
# know from Active Record:
-
#
-
# person = Person.new
-
# person.valid? # => true
-
# person.invalid? # => false
-
#
-
# person.first_name = 'zoolander'
-
# person.valid? # => false
-
# person.invalid? # => true
-
# person.errors.messages # => {first_name:["starts with z."]}
-
#
-
# Note that <tt>ActiveModel::Validations</tt> automatically adds an +errors+
-
# method to your instances initialized with a new <tt>ActiveModel::Errors</tt>
-
# object, so there is no need for you to do this manually.
-
1
module Validations
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
extend ActiveModel::Callbacks
-
1
extend ActiveModel::Translation
-
-
1
extend HelperMethods
-
1
include HelperMethods
-
-
1
attr_accessor :validation_context
-
1
define_callbacks :validate, scope: :name
-
-
1
class_attribute :_validators
-
4
self._validators = Hash.new { |h,k| h[k] = [] }
-
end
-
-
1
module ClassMethods
-
# Validates each attribute against a block.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :first_name, :last_name
-
#
-
# validates_each :first_name, :last_name, allow_blank: true do |record, attr, value|
-
# record.errors.add attr, 'starts with z.' if value.to_s[0] == ?z
-
# end
-
# end
-
#
-
# Options:
-
# * <tt>:on</tt> - Specifies the contexts where this validation is active.
-
# You can pass a symbol or an array of symbols.
-
# (e.g. <tt>on: :create</tt> or <tt>on: :custom_validation_context</tt> or
-
# <tt>on: [:create, :custom_validation_context]</tt>)
-
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
-
# * <tt>:allow_blank</tt> - Skip validation if attribute is blank.
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
-
# or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
-
# proc or string should return or evaluate to a +true+ or +false+ value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to
-
# determine if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>,
-
# or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The
-
# method, proc or string should return or evaluate to a +true+ or +false+
-
# value.
-
1
def validates_each(*attr_names, &block)
-
validates_with BlockValidator, _merge_attributes(attr_names), &block
-
end
-
-
# Adds a validation method or block to the class. This is useful when
-
# overriding the +validate+ instance method becomes too unwieldy and
-
# you're looking for more descriptive declaration of your validations.
-
#
-
# This can be done with a symbol pointing to a method:
-
#
-
# class Comment
-
# include ActiveModel::Validations
-
#
-
# validate :must_be_friends
-
#
-
# def must_be_friends
-
# errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee)
-
# end
-
# end
-
#
-
# With a block which is passed with the current record to be validated:
-
#
-
# class Comment
-
# include ActiveModel::Validations
-
#
-
# validate do |comment|
-
# comment.must_be_friends
-
# end
-
#
-
# def must_be_friends
-
# errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee)
-
# end
-
# end
-
#
-
# Or with a block where self points to the current record to be validated:
-
#
-
# class Comment
-
# include ActiveModel::Validations
-
#
-
# validate do
-
# errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee)
-
# end
-
# end
-
#
-
# Options:
-
# * <tt>:on</tt> - Specifies the contexts where this validation is active.
-
# You can pass a symbol or an array of symbols.
-
# (e.g. <tt>on: :create</tt> or <tt>on: :custom_validation_context</tt> or
-
# <tt>on: [:create, :custom_validation_context]</tt>)
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
-
# or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
-
# proc or string should return or evaluate to a +true+ or +false+ value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to
-
# determine if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>,
-
# or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The
-
# method, proc or string should return or evaluate to a +true+ or +false+
-
# value.
-
1
def validate(*args, &block)
-
20
options = args.extract_options!
-
20
if options.key?(:on)
-
options = options.dup
-
options[:if] = Array(options[:if])
-
options[:if].unshift lambda { |o|
-
Array(options[:on]).include?(o.validation_context)
-
}
-
end
-
20
args << options
-
20
set_callback(:validate, *args, &block)
-
end
-
-
# List all validators that are being used to validate the model using
-
# +validates_with+ method.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# validates_with MyValidator
-
# validates_with OtherValidator, on: :create
-
# validates_with StrictValidator, strict: true
-
# end
-
#
-
# Person.validators
-
# # => [
-
# # #<MyValidator:0x007fbff403e808 @options={}>,
-
# # #<OtherValidator:0x007fbff403d930 @options={on: :create}>,
-
# # #<StrictValidator:0x007fbff3204a30 @options={strict:true}>
-
# # ]
-
1
def validators
-
_validators.values.flatten.uniq
-
end
-
-
# Clears all of the validators and validations.
-
#
-
# Note that this will clear anything that is being used to validate
-
# the model for both the +validates_with+ and +validate+ methods.
-
# It clears the validators that are created with an invocation of
-
# +validates_with+ and the callbacks that are set by an invocation
-
# of +validate+.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# validates_with MyValidator
-
# validates_with OtherValidator, on: :create
-
# validates_with StrictValidator, strict: true
-
# validate :cannot_be_robot
-
#
-
# def cannot_be_robot
-
# errors.add(:base, 'A person cannot be a robot') if person_is_robot
-
# end
-
# end
-
#
-
# Person.validators
-
# # => [
-
# # #<MyValidator:0x007fbff403e808 @options={}>,
-
# # #<OtherValidator:0x007fbff403d930 @options={on: :create}>,
-
# # #<StrictValidator:0x007fbff3204a30 @options={strict:true}>
-
# # ]
-
#
-
# If one runs <tt>Person.clear_validators!</tt> and then checks to see what
-
# validators this class has, you would obtain:
-
#
-
# Person.validators # => []
-
#
-
# Also, the callback set by <tt>validate :cannot_be_robot</tt> will be erased
-
# so that:
-
#
-
# Person._validate_callbacks.empty? # => true
-
#
-
1
def clear_validators!
-
reset_callbacks(:validate)
-
_validators.clear
-
end
-
-
# List all validators that are being used to validate a specific attribute.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name , :age
-
#
-
# validates_presence_of :name
-
# validates_inclusion_of :age, in: 0..99
-
# end
-
#
-
# Person.validators_on(:name)
-
# # => [
-
# # #<ActiveModel::Validations::PresenceValidator:0x007fe604914e60 @attributes=[:name], @options={}>,
-
# # ]
-
1
def validators_on(*attributes)
-
attributes.flat_map do |attribute|
-
_validators[attribute.to_sym]
-
end
-
end
-
-
# Returns +true+ if +attribute+ is an attribute method, +false+ otherwise.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
# end
-
#
-
# User.attribute_method?(:name) # => true
-
# User.attribute_method?(:age) # => false
-
1
def attribute_method?(attribute)
-
method_defined?(attribute)
-
end
-
-
# Copy validators on inheritance.
-
1
def inherited(base) #:nodoc:
-
2
dup = _validators.dup
-
2
base._validators = dup.each { |k, v| dup[k] = v.dup }
-
2
super
-
end
-
end
-
-
# Clean the +Errors+ object if instance is duped.
-
1
def initialize_dup(other) #:nodoc:
-
@errors = nil
-
super
-
end
-
-
# Returns the +Errors+ object that holds all information about attribute
-
# error messages.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
# validates_presence_of :name
-
# end
-
#
-
# person = Person.new
-
# person.valid? # => false
-
# person.errors # => #<ActiveModel::Errors:0x007fe603816640 @messages={name:["can't be blank"]}>
-
1
def errors
-
@errors ||= Errors.new(self)
-
end
-
-
# Runs all the specified validations and returns +true+ if no errors were
-
# added otherwise +false+.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
# validates_presence_of :name
-
# end
-
#
-
# person = Person.new
-
# person.name = ''
-
# person.valid? # => false
-
# person.name = 'david'
-
# person.valid? # => true
-
#
-
# Context can optionally be supplied to define which callbacks to test
-
# against (the context is defined on the validations using <tt>:on</tt>).
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
# validates_presence_of :name, on: :new
-
# end
-
#
-
# person = Person.new
-
# person.valid? # => true
-
# person.valid?(:new) # => false
-
1
def valid?(context = nil)
-
current_context, self.validation_context = validation_context, context
-
errors.clear
-
run_validations!
-
ensure
-
self.validation_context = current_context
-
end
-
-
# Performs the opposite of <tt>valid?</tt>. Returns +true+ if errors were
-
# added, +false+ otherwise.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
# validates_presence_of :name
-
# end
-
#
-
# person = Person.new
-
# person.name = ''
-
# person.invalid? # => true
-
# person.name = 'david'
-
# person.invalid? # => false
-
#
-
# Context can optionally be supplied to define which callbacks to test
-
# against (the context is defined on the validations using <tt>:on</tt>).
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
# validates_presence_of :name, on: :new
-
# end
-
#
-
# person = Person.new
-
# person.invalid? # => false
-
# person.invalid?(:new) # => true
-
1
def invalid?(context = nil)
-
!valid?(context)
-
end
-
-
# Hook method defining how an attribute value should be retrieved. By default
-
# this is assumed to be an instance named after the attribute. Override this
-
# method in subclasses should you need to retrieve the value for a given
-
# attribute differently:
-
#
-
# class MyClass
-
# include ActiveModel::Validations
-
#
-
# def initialize(data = {})
-
# @data = data
-
# end
-
#
-
# def read_attribute_for_validation(key)
-
# @data[key]
-
# end
-
# end
-
1
alias :read_attribute_for_validation :send
-
-
1
protected
-
-
1
def run_validations! #:nodoc:
-
run_callbacks :validate
-
errors.empty?
-
end
-
end
-
end
-
-
14
Dir[File.dirname(__FILE__) + "/validations/*.rb"].each { |file| require file }
-
1
module ActiveModel
-
1
module Validations
-
# == Active Model Absence Validator
-
1
class AbsenceValidator < EachValidator #:nodoc:
-
1
def validate_each(record, attr_name, value)
-
record.errors.add(attr_name, :present, options) if value.present?
-
end
-
end
-
-
1
module HelperMethods
-
# Validates that the specified attributes are blank (as defined by
-
# Object#blank?). Happens by default on save.
-
#
-
# class Person < ActiveRecord::Base
-
# validates_absence_of :first_name
-
# end
-
#
-
# The first_name attribute must be in the object and it must be blank.
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "must be blank").
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
1
def validates_absence_of(*attr_names)
-
validates_with AbsenceValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
1
module ActiveModel
-
-
1
module Validations
-
1
class AcceptanceValidator < EachValidator # :nodoc:
-
1
def initialize(options)
-
super({ allow_nil: true, accept: "1" }.merge!(options))
-
setup!(options[:class])
-
end
-
-
1
def validate_each(record, attribute, value)
-
unless value == options[:accept]
-
record.errors.add(attribute, :accepted, options.except(:accept, :allow_nil))
-
end
-
end
-
-
1
private
-
1
def setup!(klass)
-
attr_readers = attributes.reject { |name| klass.attribute_method?(name) }
-
attr_writers = attributes.reject { |name| klass.attribute_method?("#{name}=") }
-
klass.send(:attr_reader, *attr_readers)
-
klass.send(:attr_writer, *attr_writers)
-
end
-
end
-
-
1
module HelperMethods
-
# Encapsulates the pattern of wanting to validate the acceptance of a
-
# terms of service check box (or similar agreement).
-
#
-
# class Person < ActiveRecord::Base
-
# validates_acceptance_of :terms_of_service
-
# validates_acceptance_of :eula, message: 'must be abided'
-
# end
-
#
-
# If the database column does not exist, the +terms_of_service+ attribute
-
# is entirely virtual. This check is performed only if +terms_of_service+
-
# is not +nil+ and by default on save.
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "must be
-
# accepted").
-
# * <tt>:accept</tt> - Specifies value that is considered accepted.
-
# The default value is a string "1", which makes it easy to relate to
-
# an HTML checkbox. This should be set to +true+ if you are validating
-
# a database column, since the attribute is typecast from "1" to +true+
-
# before validation.
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information.
-
1
def validates_acceptance_of(*attr_names)
-
validates_with AcceptanceValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
1
module ActiveModel
-
1
module Validations
-
# == Active \Model \Validation \Callbacks
-
#
-
# Provides an interface for any class to have +before_validation+ and
-
# +after_validation+ callbacks.
-
#
-
# First, include ActiveModel::Validations::Callbacks from the class you are
-
# creating:
-
#
-
# class MyModel
-
# include ActiveModel::Validations::Callbacks
-
#
-
# before_validation :do_stuff_before_validation
-
# after_validation :do_stuff_after_validation
-
# end
-
#
-
# Like other <tt>before_*</tt> callbacks if +before_validation+ returns
-
# +false+ then <tt>valid?</tt> will not be called.
-
1
module Callbacks
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
include ActiveSupport::Callbacks
-
1
define_callbacks :validation,
-
terminator: ->(_,result) { result == false },
-
skip_after_callbacks_if_terminated: true,
-
scope: [:kind, :name]
-
end
-
-
1
module ClassMethods
-
# Defines a callback that will get called right before validation
-
# happens.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# include ActiveModel::Validations::Callbacks
-
#
-
# attr_accessor :name
-
#
-
# validates_length_of :name, maximum: 6
-
#
-
# before_validation :remove_whitespaces
-
#
-
# private
-
#
-
# def remove_whitespaces
-
# name.strip!
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = ' bob '
-
# person.valid? # => true
-
# person.name # => "bob"
-
1
def before_validation(*args, &block)
-
2
options = args.last
-
2
if options.is_a?(Hash) && options[:on]
-
options[:if] = Array(options[:if])
-
options[:on] = Array(options[:on])
-
options[:if].unshift lambda { |o|
-
options[:on].include? o.validation_context
-
}
-
end
-
2
set_callback(:validation, :before, *args, &block)
-
end
-
-
# Defines a callback that will get called right after validation
-
# happens.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# include ActiveModel::Validations::Callbacks
-
#
-
# attr_accessor :name, :status
-
#
-
# validates_presence_of :name
-
#
-
# after_validation :set_status
-
#
-
# private
-
#
-
# def set_status
-
# self.status = errors.empty?
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = ''
-
# person.valid? # => false
-
# person.status # => false
-
# person.name = 'bob'
-
# person.valid? # => true
-
# person.status # => true
-
1
def after_validation(*args, &block)
-
options = args.extract_options!
-
options[:prepend] = true
-
options[:if] = Array(options[:if])
-
if options[:on]
-
options[:on] = Array(options[:on])
-
options[:if].unshift("#{options[:on]}.include? self.validation_context")
-
end
-
set_callback(:validation, :after, *(args << options), &block)
-
end
-
end
-
-
1
protected
-
-
# Overwrite run validations to include callbacks.
-
1
def run_validations! #:nodoc:
-
run_callbacks(:validation) { super }
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/range'
-
-
1
module ActiveModel
-
1
module Validations
-
1
module Clusivity #:nodoc:
-
1
ERROR_MESSAGE = "An object with the method #include? or a proc, lambda or symbol is required, " \
-
"and must be supplied as the :in (or :within) option of the configuration hash"
-
-
1
def check_validity!
-
unless delimiter.respond_to?(:include?) || delimiter.respond_to?(:call) || delimiter.respond_to?(:to_sym)
-
raise ArgumentError, ERROR_MESSAGE
-
end
-
end
-
-
1
private
-
-
1
def include?(record, value)
-
members = if delimiter.respond_to?(:call)
-
delimiter.call(record)
-
elsif delimiter.respond_to?(:to_sym)
-
record.send(delimiter)
-
else
-
delimiter
-
end
-
-
members.send(inclusion_method(members), value)
-
end
-
-
1
def delimiter
-
@delimiter ||= options[:in] || options[:within]
-
end
-
-
# In Ruby 1.9 <tt>Range#include?</tt> on non-number-or-time-ish ranges checks all
-
# possible values in the range for equality, which is slower but more accurate.
-
# <tt>Range#cover?</tt> uses the previous logic of comparing a value with the range
-
# endpoints, which is fast but is only accurate on Numeric, Time, or DateTime ranges.
-
1
def inclusion_method(enumerable)
-
if enumerable.is_a? Range
-
case enumerable.first
-
when Numeric, Time, DateTime
-
:cover?
-
else
-
:include?
-
end
-
else
-
:include?
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveModel
-
-
1
module Validations
-
1
class ConfirmationValidator < EachValidator # :nodoc:
-
1
def initialize(options)
-
1
super
-
1
setup!(options[:class])
-
end
-
-
1
def validate_each(record, attribute, value)
-
if (confirmed = record.send("#{attribute}_confirmation")) && (value != confirmed)
-
human_attribute_name = record.class.human_attribute_name(attribute)
-
record.errors.add(:"#{attribute}_confirmation", :confirmation, options.merge(attribute: human_attribute_name))
-
end
-
end
-
-
1
private
-
1
def setup!(klass)
-
1
klass.send(:attr_reader, *attributes.map do |attribute|
-
1
:"#{attribute}_confirmation" unless klass.method_defined?(:"#{attribute}_confirmation")
-
end.compact)
-
-
1
klass.send(:attr_writer, *attributes.map do |attribute|
-
1
:"#{attribute}_confirmation" unless klass.method_defined?(:"#{attribute}_confirmation=")
-
end.compact)
-
end
-
end
-
-
1
module HelperMethods
-
# Encapsulates the pattern of wanting to validate a password or email
-
# address field with a confirmation.
-
#
-
# Model:
-
# class Person < ActiveRecord::Base
-
# validates_confirmation_of :user_name, :password
-
# validates_confirmation_of :email_address,
-
# message: 'should match confirmation'
-
# end
-
#
-
# View:
-
# <%= password_field "person", "password" %>
-
# <%= password_field "person", "password_confirmation" %>
-
#
-
# The added +password_confirmation+ attribute is virtual; it exists only
-
# as an in-memory attribute for validating the password. To achieve this,
-
# the validation adds accessors to the model for the confirmation
-
# attribute.
-
#
-
# NOTE: This check is performed only if +password_confirmation+ is not
-
# +nil+. To require confirmation, make sure to add a presence check for
-
# the confirmation attribute:
-
#
-
# validates_presence_of :password_confirmation, if: :password_changed?
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "doesn't match
-
# confirmation").
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
1
def validates_confirmation_of(*attr_names)
-
1
validates_with ConfirmationValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
1
require "active_model/validations/clusivity"
-
-
1
module ActiveModel
-
-
1
module Validations
-
1
class ExclusionValidator < EachValidator # :nodoc:
-
1
include Clusivity
-
-
1
def validate_each(record, attribute, value)
-
if include?(record, value)
-
record.errors.add(attribute, :exclusion, options.except(:in, :within).merge!(value: value))
-
end
-
end
-
end
-
-
1
module HelperMethods
-
# Validates that the value of the specified attribute is not in a
-
# particular enumerable object.
-
#
-
# class Person < ActiveRecord::Base
-
# validates_exclusion_of :username, in: %w( admin superuser ), message: "You don't belong here"
-
# validates_exclusion_of :age, in: 30..60, message: 'This site is only for under 30 and over 60'
-
# validates_exclusion_of :format, in: %w( mov avi ), message: "extension %{value} is not allowed"
-
# validates_exclusion_of :password, in: ->(person) { [person.username, person.first_name] },
-
# message: 'should not be the same as your username or first name'
-
# validates_exclusion_of :karma, in: :reserved_karmas
-
# end
-
#
-
# Configuration options:
-
# * <tt>:in</tt> - An enumerable object of items that the value shouldn't
-
# be part of. This can be supplied as a proc, lambda or symbol which returns an
-
# enumerable. If the enumerable is a range the test is performed with
-
# * <tt>:within</tt> - A synonym(or alias) for <tt>:in</tt>
-
# <tt>Range#cover?</tt>, otherwise with <tt>include?</tt>.
-
# * <tt>:message</tt> - Specifies a custom error message (default is: "is
-
# reserved").
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
1
def validates_exclusion_of(*attr_names)
-
validates_with ExclusionValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
1
module ActiveModel
-
-
1
module Validations
-
1
class FormatValidator < EachValidator # :nodoc:
-
1
def validate_each(record, attribute, value)
-
if options[:with]
-
regexp = option_call(record, :with)
-
record_error(record, attribute, :with, value) if value.to_s !~ regexp
-
elsif options[:without]
-
regexp = option_call(record, :without)
-
record_error(record, attribute, :without, value) if value.to_s =~ regexp
-
end
-
end
-
-
1
def check_validity!
-
2
unless options.include?(:with) ^ options.include?(:without) # ^ == xor, or "exclusive or"
-
raise ArgumentError, "Either :with or :without must be supplied (but not both)"
-
end
-
-
2
check_options_validity :with
-
2
check_options_validity :without
-
end
-
-
1
private
-
-
1
def option_call(record, name)
-
option = options[name]
-
option.respond_to?(:call) ? option.call(record) : option
-
end
-
-
1
def record_error(record, attribute, name, value)
-
record.errors.add(attribute, :invalid, options.except(name).merge!(value: value))
-
end
-
-
1
def check_options_validity(name)
-
4
if option = options[name]
-
2
if option.is_a?(Regexp)
-
2
if options[:multiline] != true && regexp_using_multiline_anchors?(option)
-
raise ArgumentError, "The provided regular expression is using multiline anchors (^ or $), " \
-
"which may present a security risk. Did you mean to use \\A and \\z, or forgot to add the " \
-
":multiline => true option?"
-
end
-
elsif !option.respond_to?(:call)
-
raise ArgumentError, "A regular expression or a proc or lambda must be supplied as :#{name}"
-
end
-
end
-
end
-
-
1
def regexp_using_multiline_anchors?(regexp)
-
2
source = regexp.source
-
2
source.start_with?("^") || (source.end_with?("$") && !source.end_with?("\\$"))
-
end
-
end
-
-
1
module HelperMethods
-
# Validates whether the value of the specified attribute is of the correct
-
# form, going by the regular expression provided.You can require that the
-
# attribute matches the regular expression:
-
#
-
# class Person < ActiveRecord::Base
-
# validates_format_of :email, with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create
-
# end
-
#
-
# Alternatively, you can require that the specified attribute does _not_
-
# match the regular expression:
-
#
-
# class Person < ActiveRecord::Base
-
# validates_format_of :email, without: /NOSPAM/
-
# end
-
#
-
# You can also provide a proc or lambda which will determine the regular
-
# expression that will be used to validate the attribute.
-
#
-
# class Person < ActiveRecord::Base
-
# # Admin can have number as a first letter in their screen name
-
# validates_format_of :screen_name,
-
# with: ->(person) { person.admin? ? /\A[a-z0-9][a-z0-9_\-]*\z/i : /\A[a-z][a-z0-9_\-]*\z/i }
-
# end
-
#
-
# Note: use <tt>\A</tt> and <tt>\Z</tt> to match the start and end of the
-
# string, <tt>^</tt> and <tt>$</tt> match the start/end of a line.
-
#
-
# Due to frequent misuse of <tt>^</tt> and <tt>$</tt>, you need to pass
-
# the <tt>multiline: true</tt> option in case you use any of these two
-
# anchors in the provided regular expression. In most cases, you should be
-
# using <tt>\A</tt> and <tt>\z</tt>.
-
#
-
# You must pass either <tt>:with</tt> or <tt>:without</tt> as an option.
-
# In addition, both must be a regular expression or a proc or lambda, or
-
# else an exception will be raised.
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "is invalid").
-
# * <tt>:with</tt> - Regular expression that if the attribute matches will
-
# result in a successful validation. This can be provided as a proc or
-
# lambda returning regular expression which will be called at runtime.
-
# * <tt>:without</tt> - Regular expression that if the attribute does not
-
# match will result in a successful validation. This can be provided as
-
# a proc or lambda returning regular expression which will be called at
-
# runtime.
-
# * <tt>:multiline</tt> - Set to true if your regular expression contains
-
# anchors that match the beginning or end of lines as opposed to the
-
# beginning or end of the string. These anchors are <tt>^</tt> and <tt>$</tt>.
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
1
def validates_format_of(*attr_names)
-
2
validates_with FormatValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
1
require "active_model/validations/clusivity"
-
-
1
module ActiveModel
-
-
1
module Validations
-
1
class InclusionValidator < EachValidator # :nodoc:
-
1
include Clusivity
-
-
1
def validate_each(record, attribute, value)
-
unless include?(record, value)
-
record.errors.add(attribute, :inclusion, options.except(:in, :within).merge!(value: value))
-
end
-
end
-
end
-
-
1
module HelperMethods
-
# Validates whether the value of the specified attribute is available in a
-
# particular enumerable object.
-
#
-
# class Person < ActiveRecord::Base
-
# validates_inclusion_of :gender, in: %w( m f )
-
# validates_inclusion_of :age, in: 0..99
-
# validates_inclusion_of :format, in: %w( jpg gif png ), message: "extension %{value} is not included in the list"
-
# validates_inclusion_of :states, in: ->(person) { STATES[person.country] }
-
# validates_inclusion_of :karma, in: :available_karmas
-
# end
-
#
-
# Configuration options:
-
# * <tt>:in</tt> - An enumerable object of available items. This can be
-
# supplied as a proc, lambda or symbol which returns an enumerable. If the
-
# enumerable is a numerical range the test is performed with <tt>Range#cover?</tt>,
-
# otherwise with <tt>include?</tt>. When using a proc or lambda the instance
-
# under validation is passed as an argument.
-
# * <tt>:within</tt> - A synonym(or alias) for <tt>:in</tt>
-
# * <tt>:message</tt> - Specifies a custom error message (default is: "is
-
# not included in the list").
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
1
def validates_inclusion_of(*attr_names)
-
validates_with InclusionValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
1
module ActiveModel
-
-
# == Active \Model Length Validator
-
1
module Validations
-
1
class LengthValidator < EachValidator # :nodoc:
-
1
MESSAGES = { is: :wrong_length, minimum: :too_short, maximum: :too_long }.freeze
-
1
CHECKS = { is: :==, minimum: :>=, maximum: :<= }.freeze
-
-
1
RESERVED_OPTIONS = [:minimum, :maximum, :within, :is, :tokenizer, :too_short, :too_long]
-
-
1
def initialize(options)
-
1
if range = (options.delete(:in) || options.delete(:within))
-
1
raise ArgumentError, ":in and :within must be a Range" unless range.is_a?(Range)
-
1
options[:minimum], options[:maximum] = range.min, range.max
-
end
-
-
1
if options[:allow_blank] == false && options[:minimum].nil? && options[:is].nil?
-
options[:minimum] = 1
-
end
-
-
1
super
-
end
-
-
1
def check_validity!
-
1
keys = CHECKS.keys & options.keys
-
-
1
if keys.empty?
-
raise ArgumentError, 'Range unspecified. Specify the :in, :within, :maximum, :minimum, or :is option.'
-
end
-
-
1
keys.each do |key|
-
2
value = options[key]
-
-
2
unless (value.is_a?(Integer) && value >= 0) || value == Float::INFINITY
-
raise ArgumentError, ":#{key} must be a nonnegative Integer or Infinity"
-
end
-
end
-
end
-
-
1
def validate_each(record, attribute, value)
-
value = tokenize(value)
-
value_length = value.respond_to?(:length) ? value.length : value.to_s.length
-
errors_options = options.except(*RESERVED_OPTIONS)
-
-
CHECKS.each do |key, validity_check|
-
next unless check_value = options[key]
-
-
if !value.nil? || skip_nil_check?(key)
-
next if value_length.send(validity_check, check_value)
-
end
-
-
errors_options[:count] = check_value
-
-
default_message = options[MESSAGES[key]]
-
errors_options[:message] ||= default_message if default_message
-
-
record.errors.add(attribute, MESSAGES[key], errors_options)
-
end
-
end
-
-
1
private
-
-
1
def tokenize(value)
-
if options[:tokenizer] && value.kind_of?(String)
-
options[:tokenizer].call(value)
-
end || value
-
end
-
-
1
def skip_nil_check?(key)
-
key == :maximum && options[:allow_nil].nil? && options[:allow_blank].nil?
-
end
-
end
-
-
1
module HelperMethods
-
-
# Validates that the specified attribute matches the length restrictions
-
# supplied. Only one option can be used at a time:
-
#
-
# class Person < ActiveRecord::Base
-
# validates_length_of :first_name, maximum: 30
-
# validates_length_of :last_name, maximum: 30, message: "less than 30 if you don't mind"
-
# validates_length_of :fax, in: 7..32, allow_nil: true
-
# validates_length_of :phone, in: 7..32, allow_blank: true
-
# validates_length_of :user_name, within: 6..20, too_long: 'pick a shorter name', too_short: 'pick a longer name'
-
# validates_length_of :zip_code, minimum: 5, too_short: 'please enter at least 5 characters'
-
# validates_length_of :smurf_leader, is: 4, message: "papa is spelled with 4 characters... don't play me."
-
# validates_length_of :essay, minimum: 100, too_short: 'Your essay must be at least 100 words.',
-
# tokenizer: ->(str) { str.scan(/\w+/) }
-
# end
-
#
-
# Configuration options:
-
# * <tt>:minimum</tt> - The minimum size of the attribute.
-
# * <tt>:maximum</tt> - The maximum size of the attribute. Allows +nil+ by
-
# default if not used with :minimum.
-
# * <tt>:is</tt> - The exact size of the attribute.
-
# * <tt>:within</tt> - A range specifying the minimum and maximum size of
-
# the attribute.
-
# * <tt>:in</tt> - A synonym (or alias) for <tt>:within</tt>.
-
# * <tt>:allow_nil</tt> - Attribute may be +nil+; skip validation.
-
# * <tt>:allow_blank</tt> - Attribute may be blank; skip validation.
-
# * <tt>:too_long</tt> - The error message if the attribute goes over the
-
# maximum (default is: "is too long (maximum is %{count} characters)").
-
# * <tt>:too_short</tt> - The error message if the attribute goes under the
-
# minimum (default is: "is too short (min is %{count} characters)").
-
# * <tt>:wrong_length</tt> - The error message if using the <tt>:is</tt>
-
# method and the attribute is the wrong size (default is: "is the wrong
-
# length (should be %{count} characters)").
-
# * <tt>:message</tt> - The error message to use for a <tt>:minimum</tt>,
-
# <tt>:maximum</tt>, or <tt>:is</tt> violation. An alias of the appropriate
-
# <tt>too_long</tt>/<tt>too_short</tt>/<tt>wrong_length</tt> message.
-
# * <tt>:tokenizer</tt> - Specifies how to split up the attribute string.
-
# (e.g. <tt>tokenizer: ->(str) { str.scan(/\w+/) }</tt> to count words
-
# as in above example). Defaults to <tt>->(value) { value.split(//) }</tt>
-
# which counts individual characters.
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+ and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
1
def validates_length_of(*attr_names)
-
1
validates_with LengthValidator, _merge_attributes(attr_names)
-
end
-
-
1
alias_method :validates_size_of, :validates_length_of
-
end
-
end
-
end
-
1
module ActiveModel
-
-
1
module Validations
-
1
class NumericalityValidator < EachValidator # :nodoc:
-
1
CHECKS = { greater_than: :>, greater_than_or_equal_to: :>=,
-
equal_to: :==, less_than: :<, less_than_or_equal_to: :<=,
-
odd: :odd?, even: :even?, other_than: :!= }.freeze
-
-
1
RESERVED_OPTIONS = CHECKS.keys + [:only_integer]
-
-
1
def check_validity!
-
keys = CHECKS.keys - [:odd, :even]
-
options.slice(*keys).each do |option, value|
-
unless value.is_a?(Numeric) || value.is_a?(Proc) || value.is_a?(Symbol)
-
raise ArgumentError, ":#{option} must be a number, a symbol or a proc"
-
end
-
end
-
end
-
-
1
def validate_each(record, attr_name, value)
-
before_type_cast = :"#{attr_name}_before_type_cast"
-
-
raw_value = record.send(before_type_cast) if record.respond_to?(before_type_cast)
-
raw_value ||= value
-
-
return if options[:allow_nil] && raw_value.nil?
-
-
unless value = parse_raw_value_as_a_number(raw_value)
-
record.errors.add(attr_name, :not_a_number, filtered_options(raw_value))
-
return
-
end
-
-
if options[:only_integer]
-
unless value = parse_raw_value_as_an_integer(raw_value)
-
record.errors.add(attr_name, :not_an_integer, filtered_options(raw_value))
-
return
-
end
-
end
-
-
options.slice(*CHECKS.keys).each do |option, option_value|
-
case option
-
when :odd, :even
-
unless value.to_i.send(CHECKS[option])
-
record.errors.add(attr_name, option, filtered_options(value))
-
end
-
else
-
case option_value
-
when Proc
-
option_value = option_value.call(record)
-
when Symbol
-
option_value = record.send(option_value)
-
end
-
-
unless value.send(CHECKS[option], option_value)
-
record.errors.add(attr_name, option, filtered_options(value).merge!(count: option_value))
-
end
-
end
-
end
-
end
-
-
1
protected
-
-
1
def parse_raw_value_as_a_number(raw_value)
-
Kernel.Float(raw_value) if raw_value !~ /\A0[xX]/
-
rescue ArgumentError, TypeError
-
nil
-
end
-
-
1
def parse_raw_value_as_an_integer(raw_value)
-
raw_value.to_i if raw_value.to_s =~ /\A[+-]?\d+\Z/
-
end
-
-
1
def filtered_options(value)
-
filtered = options.except(*RESERVED_OPTIONS)
-
filtered[:value] = value
-
filtered
-
end
-
end
-
-
1
module HelperMethods
-
# Validates whether the value of the specified attribute is numeric by
-
# trying to convert it to a float with Kernel.Float (if <tt>only_integer</tt>
-
# is +false+) or applying it to the regular expression <tt>/\A[\+\-]?\d+\Z/</tt>
-
# (if <tt>only_integer</tt> is set to +true+).
-
#
-
# class Person < ActiveRecord::Base
-
# validates_numericality_of :value, on: :create
-
# end
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "is not a number").
-
# * <tt>:only_integer</tt> - Specifies whether the value has to be an
-
# integer, e.g. an integral value (default is +false+).
-
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default is
-
# +false+). Notice that for fixnum and float columns empty strings are
-
# converted to +nil+.
-
# * <tt>:greater_than</tt> - Specifies the value must be greater than the
-
# supplied value.
-
# * <tt>:greater_than_or_equal_to</tt> - Specifies the value must be
-
# greater than or equal the supplied value.
-
# * <tt>:equal_to</tt> - Specifies the value must be equal to the supplied
-
# value.
-
# * <tt>:less_than</tt> - Specifies the value must be less than the
-
# supplied value.
-
# * <tt>:less_than_or_equal_to</tt> - Specifies the value must be less
-
# than or equal the supplied value.
-
# * <tt>:other_than</tt> - Specifies the value must be other than the
-
# supplied value.
-
# * <tt>:odd</tt> - Specifies the value must be an odd number.
-
# * <tt>:even</tt> - Specifies the value must be an even number.
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+ .
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
#
-
# The following checks can also be supplied with a proc or a symbol which
-
# corresponds to a method:
-
#
-
# * <tt>:greater_than</tt>
-
# * <tt>:greater_than_or_equal_to</tt>
-
# * <tt>:equal_to</tt>
-
# * <tt>:less_than</tt>
-
# * <tt>:less_than_or_equal_to</tt>
-
#
-
# For example:
-
#
-
# class Person < ActiveRecord::Base
-
# validates_numericality_of :width, less_than: ->(person) { person.height }
-
# validates_numericality_of :width, greater_than: :minimum_weight
-
# end
-
1
def validates_numericality_of(*attr_names)
-
validates_with NumericalityValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
-
1
module ActiveModel
-
-
1
module Validations
-
1
class PresenceValidator < EachValidator # :nodoc:
-
1
def validate_each(record, attr_name, value)
-
record.errors.add(attr_name, :blank, options) if value.blank?
-
end
-
end
-
-
1
module HelperMethods
-
# Validates that the specified attributes are not blank (as defined by
-
# Object#blank?). Happens by default on save.
-
#
-
# class Person < ActiveRecord::Base
-
# validates_presence_of :first_name
-
# end
-
#
-
# The first_name attribute must be in the object and it cannot be blank.
-
#
-
# If you want to validate the presence of a boolean field (where the real
-
# values are +true+ and +false+), you will want to use
-
# <tt>validates_inclusion_of :field_name, in: [true, false]</tt>.
-
#
-
# This is due to the way Object#blank? handles boolean values:
-
# <tt>false.blank? # => true</tt>.
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "can't be blank").
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
1
def validates_presence_of(*attr_names)
-
validates_with PresenceValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/slice'
-
-
1
module ActiveModel
-
1
module Validations
-
1
module ClassMethods
-
# This method is a shortcut to all default validators and any custom
-
# validator classes ending in 'Validator'. Note that Rails default
-
# validators can be overridden inside specific classes by creating
-
# custom validator classes in their place such as PresenceValidator.
-
#
-
# Examples of using the default rails validators:
-
#
-
# validates :terms, acceptance: true
-
# validates :password, confirmation: true
-
# validates :username, exclusion: { in: %w(admin superuser) }
-
# validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create }
-
# validates :age, inclusion: { in: 0..9 }
-
# validates :first_name, length: { maximum: 30 }
-
# validates :age, numericality: true
-
# validates :username, presence: true
-
# validates :username, uniqueness: true
-
#
-
# The power of the +validates+ method comes when using custom validators
-
# and default validators in one call for a given attribute.
-
#
-
# class EmailValidator < ActiveModel::EachValidator
-
# def validate_each(record, attribute, value)
-
# record.errors.add attribute, (options[:message] || "is not an email") unless
-
# value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
-
# end
-
# end
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# attr_accessor :name, :email
-
#
-
# validates :name, presence: true, uniqueness: true, length: { maximum: 100 }
-
# validates :email, presence: true, email: true
-
# end
-
#
-
# Validator classes may also exist within the class being validated
-
# allowing custom modules of validators to be included as needed.
-
#
-
# class Film
-
# include ActiveModel::Validations
-
#
-
# class TitleValidator < ActiveModel::EachValidator
-
# def validate_each(record, attribute, value)
-
# record.errors.add attribute, "must start with 'the'" unless value =~ /\Athe/i
-
# end
-
# end
-
#
-
# validates :name, title: true
-
# end
-
#
-
# Additionally validator classes may be in another namespace and still
-
# used within any class.
-
#
-
# validates :name, :'film/title' => true
-
#
-
# The validators hash can also handle regular expressions, ranges, arrays
-
# and strings in shortcut form.
-
#
-
# validates :email, format: /@/
-
# validates :gender, inclusion: %w(male female)
-
# validates :password, length: 6..20
-
#
-
# When using shortcut form, ranges and arrays are passed to your
-
# validator's initializer as <tt>options[:in]</tt> while other types
-
# including regular expressions and strings are passed as <tt>options[:with]</tt>.
-
#
-
# There is also a list of options that could be used along with validators:
-
#
-
# * <tt>:on</tt> - Specifies when this validation is active. Runs in all
-
# validation contexts by default (+nil+), other options are <tt>:create</tt>
-
# and <tt>:update</tt>.
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
-
# or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
-
# proc or string should return or evaluate to a +true+ or +false+ value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>,
-
# or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The
-
# method, proc or string should return or evaluate to a +true+ or
-
# +false+ value.
-
# * <tt>:allow_nil</tt> - Skip validation if the attribute is +nil+.
-
# * <tt>:allow_blank</tt> - Skip validation if the attribute is blank.
-
# * <tt>:strict</tt> - If the <tt>:strict</tt> option is set to true
-
# will raise ActiveModel::StrictValidationFailed instead of adding the error.
-
# <tt>:strict</tt> option can also be set to any other exception.
-
#
-
# Example:
-
#
-
# validates :password, presence: true, confirmation: true, if: :password_required?
-
# validates :token, uniqueness: true, strict: TokenGenerationException
-
#
-
#
-
# Finally, the options +:if+, +:unless+, +:on+, +:allow_blank+, +:allow_nil+, +:strict+
-
# and +:message+ can be given to one specific validator, as a hash:
-
#
-
# validates :password, presence: { if: :password_required?, message: 'is forgotten.' }, confirmation: true
-
1
def validates(*attributes)
-
defaults = attributes.extract_options!.dup
-
validations = defaults.slice!(*_validates_default_keys)
-
-
raise ArgumentError, "You need to supply at least one attribute" if attributes.empty?
-
raise ArgumentError, "You need to supply at least one validation" if validations.empty?
-
-
defaults[:attributes] = attributes
-
-
validations.each do |key, options|
-
next unless options
-
key = "#{key.to_s.camelize}Validator"
-
-
begin
-
validator = key.include?('::') ? key.constantize : const_get(key)
-
rescue NameError
-
raise ArgumentError, "Unknown validator: '#{key}'"
-
end
-
-
validates_with(validator, defaults.merge(_parse_validates_options(options)))
-
end
-
end
-
-
# This method is used to define validations that cannot be corrected by end
-
# users and are considered exceptional. So each validator defined with bang
-
# or <tt>:strict</tt> option set to <tt>true</tt> will always raise
-
# <tt>ActiveModel::StrictValidationFailed</tt> instead of adding error
-
# when validation fails. See <tt>validates</tt> for more information about
-
# the validation itself.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
# validates! :name, presence: true
-
# end
-
#
-
# person = Person.new
-
# person.name = ''
-
# person.valid?
-
# # => ActiveModel::StrictValidationFailed: Name can't be blank
-
1
def validates!(*attributes)
-
options = attributes.extract_options!
-
options[:strict] = true
-
validates(*(attributes << options))
-
end
-
-
1
protected
-
-
# When creating custom validators, it might be useful to be able to specify
-
# additional default keys. This can be done by overwriting this method.
-
1
def _validates_default_keys # :nodoc:
-
[:if, :unless, :on, :allow_blank, :allow_nil , :strict]
-
end
-
-
1
def _parse_validates_options(options) # :nodoc:
-
case options
-
when TrueClass
-
{}
-
when Hash
-
options
-
when Range, Array
-
{ in: options }
-
else
-
{ with: options }
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveModel
-
1
module Validations
-
1
module HelperMethods
-
1
private
-
1
def _merge_attributes(attr_names)
-
12
options = attr_names.extract_options!.symbolize_keys
-
12
attr_names.flatten!
-
12
options[:attributes] = attr_names
-
12
options
-
end
-
end
-
-
1
class WithValidator < EachValidator # :nodoc:
-
1
def validate_each(record, attr, val)
-
method_name = options[:with]
-
-
if record.method(method_name).arity == 0
-
record.send method_name
-
else
-
record.send method_name, attr
-
end
-
end
-
end
-
-
1
module ClassMethods
-
# Passes the record off to the class or classes specified and allows them
-
# to add errors based on more complex conditions.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# validates_with MyValidator
-
# end
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def validate(record)
-
# if some_complex_logic
-
# record.errors.add :base, 'This record is invalid'
-
# end
-
# end
-
#
-
# private
-
# def some_complex_logic
-
# # ...
-
# end
-
# end
-
#
-
# You may also pass it multiple classes, like so:
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# validates_with MyValidator, MyOtherValidator, on: :create
-
# end
-
#
-
# Configuration options:
-
# * <tt>:on</tt> - Specifies when this validation is active
-
# (<tt>:create</tt> or <tt>:update</tt>.
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
-
# or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>).
-
# The method, proc or string should return or evaluate to a +true+ or
-
# +false+ value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to
-
# determine if the validation should not occur
-
# (e.g. <tt>unless: :skip_validation</tt>, or
-
# <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>).
-
# The method, proc or string should return or evaluate to a +true+ or
-
# +false+ value.
-
# * <tt>:strict</tt> - Specifies whether validation should be strict.
-
# See <tt>ActiveModel::Validation#validates!</tt> for more information.
-
#
-
# If you pass any additional configuration options, they will be passed
-
# to the class and available as +options+:
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# validates_with MyValidator, my_custom_key: 'my custom value'
-
# end
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def validate(record)
-
# options[:my_custom_key] # => "my custom value"
-
# end
-
# end
-
1
def validates_with(*args, &block)
-
12
options = args.extract_options!
-
12
options[:class] = self
-
-
12
args.each do |klass|
-
12
validator = klass.new(options, &block)
-
-
12
if validator.respond_to?(:attributes) && !validator.attributes.empty?
-
12
validator.attributes.each do |attribute|
-
12
_validators[attribute.to_sym] << validator
-
end
-
else
-
_validators[nil] << validator
-
end
-
-
12
validate(validator, options)
-
end
-
end
-
end
-
-
# Passes the record off to the class or classes specified and allows them
-
# to add errors based on more complex conditions.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# validate :instance_validations
-
#
-
# def instance_validations
-
# validates_with MyValidator
-
# end
-
# end
-
#
-
# Please consult the class method documentation for more information on
-
# creating your own validator.
-
#
-
# You may also pass it multiple classes, like so:
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# validate :instance_validations, on: :create
-
#
-
# def instance_validations
-
# validates_with MyValidator, MyOtherValidator
-
# end
-
# end
-
#
-
# Standard configuration options (<tt>:on</tt>, <tt>:if</tt> and
-
# <tt>:unless</tt>), which are available on the class version of
-
# +validates_with+, should instead be placed on the +validates+ method
-
# as these are applied and tested in the callback.
-
#
-
# If you pass any additional configuration options, they will be passed
-
# to the class and available as +options+, please refer to the
-
# class version of this method for more information.
-
1
def validates_with(*args, &block)
-
options = args.extract_options!
-
options[:class] = self.class
-
-
args.each do |klass|
-
validator = klass.new(options, &block)
-
validator.validate(self)
-
end
-
end
-
end
-
end
-
1
require "active_support/core_ext/module/anonymous"
-
-
1
module ActiveModel
-
-
# == Active \Model \Validator
-
#
-
# A simple base class that can be used along with
-
# ActiveModel::Validations::ClassMethods.validates_with
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# validates_with MyValidator
-
# end
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def validate(record)
-
# if some_complex_logic
-
# record.errors[:base] = "This record is invalid"
-
# end
-
# end
-
#
-
# private
-
# def some_complex_logic
-
# # ...
-
# end
-
# end
-
#
-
# Any class that inherits from ActiveModel::Validator must implement a method
-
# called +validate+ which accepts a +record+.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# validates_with MyValidator
-
# end
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def validate(record)
-
# record # => The person instance being validated
-
# options # => Any non-standard options passed to validates_with
-
# end
-
# end
-
#
-
# To cause a validation error, you must add to the +record+'s errors directly
-
# from within the validators message.
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def validate(record)
-
# record.errors.add :base, "This is some custom error message"
-
# record.errors.add :first_name, "This is some complex validation"
-
# # etc...
-
# end
-
# end
-
#
-
# To add behavior to the initialize method, use the following signature:
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def initialize(options)
-
# super
-
# @my_custom_field = options[:field_name] || :first_name
-
# end
-
# end
-
#
-
# Note that the validator is initialized only once for the whole application
-
# life cycle, and not on each validation run.
-
#
-
# The easiest way to add custom validators for validating individual attributes
-
# is with the convenient <tt>ActiveModel::EachValidator</tt>.
-
#
-
# class TitleValidator < ActiveModel::EachValidator
-
# def validate_each(record, attribute, value)
-
# record.errors.add attribute, 'must be Mr., Mrs., or Dr.' unless %w(Mr. Mrs. Dr.).include?(value)
-
# end
-
# end
-
#
-
# This can now be used in combination with the +validates+ method
-
# (see <tt>ActiveModel::Validations::ClassMethods.validates</tt> for more on this).
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# attr_accessor :title
-
#
-
# validates :title, presence: true
-
# end
-
#
-
# It can be useful to access the class that is using that validator when there are prerequisites such
-
# as an +attr_accessor+ being present. This class is accessible via +options[:class]+ in the constructor.
-
# To setup your validator override the constructor.
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def initialize(options={})
-
# super
-
# options[:class].send :attr_accessor, :custom_attribute
-
# end
-
# end
-
1
class Validator
-
1
attr_reader :options
-
-
# Returns the kind of the validator.
-
#
-
# PresenceValidator.kind # => :presence
-
# UniquenessValidator.kind # => :uniqueness
-
1
def self.kind
-
@kind ||= name.split('::').last.underscore.sub(/_validator$/, '').to_sym unless anonymous?
-
end
-
-
# Accepts options that will be made available through the +options+ reader.
-
1
def initialize(options = {})
-
12
@options = options.except(:class).freeze
-
12
deprecated_setup(options)
-
end
-
-
# Returns the kind for this validator.
-
#
-
# PresenceValidator.new.kind # => :presence
-
# UniquenessValidator.new.kind # => :uniqueness
-
1
def kind
-
self.class.kind
-
end
-
-
# Override this method in subclasses with validation logic, adding errors
-
# to the records +errors+ array where necessary.
-
1
def validate(record)
-
raise NotImplementedError, "Subclasses must implement a validate(record) method."
-
end
-
-
1
private
-
1
def deprecated_setup(options) # TODO: remove me in 4.2.
-
12
return unless respond_to?(:setup)
-
ActiveSupport::Deprecation.warn "The `Validator#setup` instance method is deprecated and will be removed on Rails 4.2. Do your setup in the constructor instead:
-
-
class MyValidator < ActiveModel::Validator
-
def initialize(options={})
-
super
-
options[:class].send :attr_accessor, :custom_attribute
-
end
-
end
-
"
-
setup(options[:class])
-
end
-
end
-
-
# +EachValidator+ is a validator which iterates through the attributes given
-
# in the options hash invoking the <tt>validate_each</tt> method passing in the
-
# record, attribute and value.
-
#
-
# All Active Model validations are built on top of this validator.
-
1
class EachValidator < Validator #:nodoc:
-
1
attr_reader :attributes
-
-
# Returns a new validator instance. All options will be available via the
-
# +options+ reader, however the <tt>:attributes</tt> option will be removed
-
# and instead be made available through the +attributes+ reader.
-
1
def initialize(options)
-
12
@attributes = Array(options.delete(:attributes))
-
12
raise ArgumentError, ":attributes cannot be blank" if @attributes.empty?
-
12
super
-
12
check_validity!
-
end
-
-
# Performs validation on the supplied record. By default this will call
-
# +validates_each+ to determine validity therefore subclasses should
-
# override +validates_each+ with validation logic.
-
1
def validate(record)
-
attributes.each do |attribute|
-
value = record.read_attribute_for_validation(attribute)
-
next if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank])
-
validate_each(record, attribute, value)
-
end
-
end
-
-
# Override this method in subclasses with the validation logic, adding
-
# errors to the records +errors+ array where necessary.
-
1
def validate_each(record, attribute, value)
-
raise NotImplementedError, "Subclasses must implement a validate_each(record, attribute, value) method"
-
end
-
-
# Hook method that gets called by the initializer allowing verification
-
# that the arguments supplied are valid. You could for example raise an
-
# +ArgumentError+ when invalid options are supplied.
-
1
def check_validity!
-
end
-
end
-
-
# +BlockValidator+ is a special +EachValidator+ which receives a block on initialization
-
# and call this block for each attribute being validated. +validates_each+ uses this validator.
-
1
class BlockValidator < EachValidator #:nodoc:
-
1
def initialize(options, &block)
-
@block = block
-
super
-
end
-
-
1
private
-
-
1
def validate_each(record, attribute, value)
-
@block.call(record, attribute, value)
-
end
-
end
-
end
-
1
require_relative 'gem_version'
-
-
1
module ActiveModel
-
# Returns the version of the currently loaded ActiveModel as a <tt>Gem::Version</tt>
-
1
def self.version
-
gem_version
-
end
-
end
-
#--
-
# Copyright (c) 2004-2014 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
1
require 'active_support'
-
1
require 'active_support/rails'
-
1
require 'active_model'
-
1
require 'arel'
-
-
1
require 'active_record/version'
-
-
1
module ActiveRecord
-
1
extend ActiveSupport::Autoload
-
-
1
autoload :Base
-
1
autoload :Callbacks
-
1
autoload :Core
-
1
autoload :ConnectionHandling
-
1
autoload :CounterCache
-
1
autoload :DynamicMatchers
-
1
autoload :Enum
-
1
autoload :Explain
-
1
autoload :Inheritance
-
1
autoload :Integration
-
1
autoload :Migration
-
1
autoload :Migrator, 'active_record/migration'
-
1
autoload :ModelSchema
-
1
autoload :NestedAttributes
-
1
autoload :NoTouching
-
1
autoload :Persistence
-
1
autoload :QueryCache
-
1
autoload :Querying
-
1
autoload :ReadonlyAttributes
-
1
autoload :Reflection
-
1
autoload :RuntimeRegistry
-
1
autoload :Sanitization
-
1
autoload :Schema
-
1
autoload :SchemaDumper
-
1
autoload :SchemaMigration
-
1
autoload :Scoping
-
1
autoload :Serialization
-
1
autoload :StatementCache
-
1
autoload :Store
-
1
autoload :Timestamp
-
1
autoload :Transactions
-
1
autoload :Translation
-
1
autoload :Validations
-
-
1
eager_autoload do
-
1
autoload :ActiveRecordError, 'active_record/errors'
-
1
autoload :ConnectionNotEstablished, 'active_record/errors'
-
1
autoload :ConnectionAdapters, 'active_record/connection_adapters/abstract_adapter'
-
-
1
autoload :Aggregations
-
1
autoload :Associations
-
1
autoload :AttributeAssignment
-
1
autoload :AttributeMethods
-
1
autoload :AutosaveAssociation
-
-
1
autoload :Relation
-
1
autoload :AssociationRelation
-
1
autoload :NullRelation
-
-
1
autoload_under 'relation' do
-
1
autoload :QueryMethods
-
1
autoload :FinderMethods
-
1
autoload :Calculations
-
1
autoload :PredicateBuilder
-
1
autoload :SpawnMethods
-
1
autoload :Batches
-
1
autoload :Delegation
-
end
-
-
1
autoload :Result
-
end
-
-
1
module Coders
-
1
autoload :YAMLColumn, 'active_record/coders/yaml_column'
-
end
-
-
1
module AttributeMethods
-
1
extend ActiveSupport::Autoload
-
-
1
eager_autoload do
-
1
autoload :BeforeTypeCast
-
1
autoload :Dirty
-
1
autoload :PrimaryKey
-
1
autoload :Query
-
1
autoload :Read
-
1
autoload :TimeZoneConversion
-
1
autoload :Write
-
1
autoload :Serialization
-
end
-
end
-
-
1
module Locking
-
1
extend ActiveSupport::Autoload
-
-
1
eager_autoload do
-
1
autoload :Optimistic
-
1
autoload :Pessimistic
-
end
-
end
-
-
1
module ConnectionAdapters
-
1
extend ActiveSupport::Autoload
-
-
1
eager_autoload do
-
1
autoload :AbstractAdapter
-
1
autoload :ConnectionManagement, "active_record/connection_adapters/abstract/connection_pool"
-
end
-
end
-
-
1
module Scoping
-
1
extend ActiveSupport::Autoload
-
-
1
eager_autoload do
-
1
autoload :Named
-
1
autoload :Default
-
end
-
end
-
-
1
module Tasks
-
1
extend ActiveSupport::Autoload
-
-
1
autoload :DatabaseTasks
-
1
autoload :SQLiteDatabaseTasks, 'active_record/tasks/sqlite_database_tasks'
-
1
autoload :MySQLDatabaseTasks, 'active_record/tasks/mysql_database_tasks'
-
1
autoload :PostgreSQLDatabaseTasks,
-
'active_record/tasks/postgresql_database_tasks'
-
end
-
-
1
autoload :TestFixtures, 'active_record/fixtures'
-
-
1
def self.eager_load!
-
super
-
ActiveRecord::Locking.eager_load!
-
ActiveRecord::Scoping.eager_load!
-
ActiveRecord::Associations.eager_load!
-
ActiveRecord::AttributeMethods.eager_load!
-
ActiveRecord::ConnectionAdapters.eager_load!
-
end
-
end
-
-
1
ActiveSupport.on_load(:active_record) do
-
1
Arel::Table.engine = self
-
end
-
-
1
ActiveSupport.on_load(:i18n) do
-
1
I18n.load_path << File.dirname(__FILE__) + '/active_record/locale/en.yml'
-
end
-
1
module ActiveRecord
-
# = Active Record Aggregations
-
1
module Aggregations # :nodoc:
-
1
extend ActiveSupport::Concern
-
-
1
def clear_aggregation_cache #:nodoc:
-
@aggregation_cache.clear if persisted?
-
end
-
-
# Active Record implements aggregation through a macro-like class method called +composed_of+
-
# for representing attributes as value objects. It expresses relationships like "Account [is]
-
# composed of Money [among other things]" or "Person [is] composed of [an] address". Each call
-
# to the macro adds a description of how the value objects are created from the attributes of
-
# the entity object (when the entity is initialized either as a new object or from finding an
-
# existing object) and how it can be turned back into attributes (when the entity is saved to
-
# the database).
-
#
-
# class Customer < ActiveRecord::Base
-
# composed_of :balance, class_name: "Money", mapping: %w(balance amount)
-
# composed_of :address, mapping: [ %w(address_street street), %w(address_city city) ]
-
# end
-
#
-
# The customer class now has the following methods to manipulate the value objects:
-
# * <tt>Customer#balance, Customer#balance=(money)</tt>
-
# * <tt>Customer#address, Customer#address=(address)</tt>
-
#
-
# These methods will operate with value objects like the ones described below:
-
#
-
# class Money
-
# include Comparable
-
# attr_reader :amount, :currency
-
# EXCHANGE_RATES = { "USD_TO_DKK" => 6 }
-
#
-
# def initialize(amount, currency = "USD")
-
# @amount, @currency = amount, currency
-
# end
-
#
-
# def exchange_to(other_currency)
-
# exchanged_amount = (amount * EXCHANGE_RATES["#{currency}_TO_#{other_currency}"]).floor
-
# Money.new(exchanged_amount, other_currency)
-
# end
-
#
-
# def ==(other_money)
-
# amount == other_money.amount && currency == other_money.currency
-
# end
-
#
-
# def <=>(other_money)
-
# if currency == other_money.currency
-
# amount <=> other_money.amount
-
# else
-
# amount <=> other_money.exchange_to(currency).amount
-
# end
-
# end
-
# end
-
#
-
# class Address
-
# attr_reader :street, :city
-
# def initialize(street, city)
-
# @street, @city = street, city
-
# end
-
#
-
# def close_to?(other_address)
-
# city == other_address.city
-
# end
-
#
-
# def ==(other_address)
-
# city == other_address.city && street == other_address.street
-
# end
-
# end
-
#
-
# Now it's possible to access attributes from the database through the value objects instead. If
-
# you choose to name the composition the same as the attribute's name, it will be the only way to
-
# access that attribute. That's the case with our +balance+ attribute. You interact with the value
-
# objects just like you would with any other attribute:
-
#
-
# customer.balance = Money.new(20) # sets the Money value object and the attribute
-
# customer.balance # => Money value object
-
# customer.balance.exchange_to("DKK") # => Money.new(120, "DKK")
-
# customer.balance > Money.new(10) # => true
-
# customer.balance == Money.new(20) # => true
-
# customer.balance < Money.new(5) # => false
-
#
-
# Value objects can also be composed of multiple attributes, such as the case of Address. The order
-
# of the mappings will determine the order of the parameters.
-
#
-
# customer.address_street = "Hyancintvej"
-
# customer.address_city = "Copenhagen"
-
# customer.address # => Address.new("Hyancintvej", "Copenhagen")
-
#
-
# customer.address_street = "Vesterbrogade"
-
# customer.address # => Address.new("Hyancintvej", "Copenhagen")
-
# customer.clear_aggregation_cache
-
# customer.address # => Address.new("Vesterbrogade", "Copenhagen")
-
#
-
# customer.address = Address.new("May Street", "Chicago")
-
# customer.address_street # => "May Street"
-
# customer.address_city # => "Chicago"
-
#
-
# == Writing value objects
-
#
-
# Value objects are immutable and interchangeable objects that represent a given value, such as
-
# a Money object representing $5. Two Money objects both representing $5 should be equal (through
-
# methods such as <tt>==</tt> and <tt><=></tt> from Comparable if ranking makes sense). This is
-
# unlike entity objects where equality is determined by identity. An entity class such as Customer can
-
# easily have two different objects that both have an address on Hyancintvej. Entity identity is
-
# determined by object or relational unique identifiers (such as primary keys). Normal
-
# ActiveRecord::Base classes are entity objects.
-
#
-
# It's also important to treat the value objects as immutable. Don't allow the Money object to have
-
# its amount changed after creation. Create a new Money object with the new value instead. The
-
# Money#exchange_to method is an example of this. It returns a new value object instead of changing
-
# its own values. Active Record won't persist value objects that have been changed through means
-
# other than the writer method.
-
#
-
# The immutable requirement is enforced by Active Record by freezing any object assigned as a value
-
# object. Attempting to change it afterwards will result in a RuntimeError.
-
#
-
# Read more about value objects on http://c2.com/cgi/wiki?ValueObject and on the dangers of not
-
# keeping value objects immutable on http://c2.com/cgi/wiki?ValueObjectsShouldBeImmutable
-
#
-
# == Custom constructors and converters
-
#
-
# By default value objects are initialized by calling the <tt>new</tt> constructor of the value
-
# class passing each of the mapped attributes, in the order specified by the <tt>:mapping</tt>
-
# option, as arguments. If the value class doesn't support this convention then +composed_of+ allows
-
# a custom constructor to be specified.
-
#
-
# When a new value is assigned to the value object, the default assumption is that the new value
-
# is an instance of the value class. Specifying a custom converter allows the new value to be automatically
-
# converted to an instance of value class if necessary.
-
#
-
# For example, the NetworkResource model has +network_address+ and +cidr_range+ attributes that
-
# should be aggregated using the NetAddr::CIDR value class (http://netaddr.rubyforge.org). The constructor
-
# for the value class is called +create+ and it expects a CIDR address string as a parameter. New
-
# values can be assigned to the value object using either another NetAddr::CIDR object, a string
-
# or an array. The <tt>:constructor</tt> and <tt>:converter</tt> options can be used to meet
-
# these requirements:
-
#
-
# class NetworkResource < ActiveRecord::Base
-
# composed_of :cidr,
-
# class_name: 'NetAddr::CIDR',
-
# mapping: [ %w(network_address network), %w(cidr_range bits) ],
-
# allow_nil: true,
-
# constructor: Proc.new { |network_address, cidr_range| NetAddr::CIDR.create("#{network_address}/#{cidr_range}") },
-
# converter: Proc.new { |value| NetAddr::CIDR.create(value.is_a?(Array) ? value.join('/') : value) }
-
# end
-
#
-
# # This calls the :constructor
-
# network_resource = NetworkResource.new(network_address: '192.168.0.1', cidr_range: 24)
-
#
-
# # These assignments will both use the :converter
-
# network_resource.cidr = [ '192.168.2.1', 8 ]
-
# network_resource.cidr = '192.168.0.1/24'
-
#
-
# # This assignment won't use the :converter as the value is already an instance of the value class
-
# network_resource.cidr = NetAddr::CIDR.create('192.168.2.1/8')
-
#
-
# # Saving and then reloading will use the :constructor on reload
-
# network_resource.save
-
# network_resource.reload
-
#
-
# == Finding records by a value object
-
#
-
# Once a +composed_of+ relationship is specified for a model, records can be loaded from the database
-
# by specifying an instance of the value object in the conditions hash. The following example
-
# finds all customers with +balance_amount+ equal to 20 and +balance_currency+ equal to "USD":
-
#
-
# Customer.where(balance: Money.new(20, "USD"))
-
#
-
1
module ClassMethods
-
# Adds reader and writer methods for manipulating a value object:
-
# <tt>composed_of :address</tt> adds <tt>address</tt> and <tt>address=(new_address)</tt> methods.
-
#
-
# Options are:
-
# * <tt>:class_name</tt> - Specifies the class name of the association. Use it only if that name
-
# can't be inferred from the part id. So <tt>composed_of :address</tt> will by default be linked
-
# to the Address class, but if the real class name is CompanyAddress, you'll have to specify it
-
# with this option.
-
# * <tt>:mapping</tt> - Specifies the mapping of entity attributes to attributes of the value
-
# object. Each mapping is represented as an array where the first item is the name of the
-
# entity attribute and the second item is the name of the attribute in the value object. The
-
# order in which mappings are defined determines the order in which attributes are sent to the
-
# value class constructor.
-
# * <tt>:allow_nil</tt> - Specifies that the value object will not be instantiated when all mapped
-
# attributes are +nil+. Setting the value object to +nil+ has the effect of writing +nil+ to all
-
# mapped attributes.
-
# This defaults to +false+.
-
# * <tt>:constructor</tt> - A symbol specifying the name of the constructor method or a Proc that
-
# is called to initialize the value object. The constructor is passed all of the mapped attributes,
-
# in the order that they are defined in the <tt>:mapping option</tt>, as arguments and uses them
-
# to instantiate a <tt>:class_name</tt> object.
-
# The default is <tt>:new</tt>.
-
# * <tt>:converter</tt> - A symbol specifying the name of a class method of <tt>:class_name</tt>
-
# or a Proc that is called when a new value is assigned to the value object. The converter is
-
# passed the single value that is used in the assignment and is only called if the new value is
-
# not an instance of <tt>:class_name</tt>. If <tt>:allow_nil</tt> is set to true, the converter
-
# can return nil to skip the assignment.
-
#
-
# Option examples:
-
# composed_of :temperature, mapping: %w(reading celsius)
-
# composed_of :balance, class_name: "Money", mapping: %w(balance amount),
-
# converter: Proc.new { |balance| balance.to_money }
-
# composed_of :address, mapping: [ %w(address_street street), %w(address_city city) ]
-
# composed_of :gps_location
-
# composed_of :gps_location, allow_nil: true
-
# composed_of :ip_address,
-
# class_name: 'IPAddr',
-
# mapping: %w(ip to_i),
-
# constructor: Proc.new { |ip| IPAddr.new(ip, Socket::AF_INET) },
-
# converter: Proc.new { |ip| ip.is_a?(Integer) ? IPAddr.new(ip, Socket::AF_INET) : IPAddr.new(ip.to_s) }
-
#
-
1
def composed_of(part_id, options = {})
-
options.assert_valid_keys(:class_name, :mapping, :allow_nil, :constructor, :converter)
-
-
name = part_id.id2name
-
class_name = options[:class_name] || name.camelize
-
mapping = options[:mapping] || [ name, name ]
-
mapping = [ mapping ] unless mapping.first.is_a?(Array)
-
allow_nil = options[:allow_nil] || false
-
constructor = options[:constructor] || :new
-
converter = options[:converter]
-
-
reader_method(name, class_name, mapping, allow_nil, constructor)
-
writer_method(name, class_name, mapping, allow_nil, converter)
-
-
reflection = ActiveRecord::Reflection.create(:composed_of, part_id, nil, options, self)
-
Reflection.add_aggregate_reflection self, part_id, reflection
-
end
-
-
1
private
-
1
def reader_method(name, class_name, mapping, allow_nil, constructor)
-
define_method(name) do
-
if @aggregation_cache[name].nil? && (!allow_nil || mapping.any? {|pair| !read_attribute(pair.first).nil? })
-
attrs = mapping.collect {|pair| read_attribute(pair.first)}
-
object = constructor.respond_to?(:call) ?
-
constructor.call(*attrs) :
-
class_name.constantize.send(constructor, *attrs)
-
@aggregation_cache[name] = object
-
end
-
@aggregation_cache[name]
-
end
-
end
-
-
1
def writer_method(name, class_name, mapping, allow_nil, converter)
-
define_method("#{name}=") do |part|
-
klass = class_name.constantize
-
unless part.is_a?(klass) || converter.nil? || part.nil?
-
part = converter.respond_to?(:call) ? converter.call(part) : klass.send(converter, part)
-
end
-
-
if part.nil? && allow_nil
-
mapping.each { |pair| self[pair.first] = nil }
-
@aggregation_cache[name] = nil
-
else
-
mapping.each { |pair| self[pair.first] = part.send(pair.last) }
-
@aggregation_cache[name] = part.freeze
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
class AssociationRelation < Relation
-
1
def initialize(klass, table, association)
-
super(klass, table)
-
@association = association
-
end
-
-
1
def proxy_association
-
@association
-
end
-
-
1
private
-
-
1
def exec_queries
-
super.each { |r| @association.set_inverse_instance r }
-
end
-
end
-
end
-
1
require 'active_support/core_ext/enumerable'
-
1
require 'active_support/core_ext/string/conversions'
-
1
require 'active_support/core_ext/module/remove_method'
-
1
require 'active_record/errors'
-
-
1
module ActiveRecord
-
1
class InverseOfAssociationNotFoundError < ActiveRecordError #:nodoc:
-
1
def initialize(reflection, associated_class = nil)
-
super("Could not find the inverse association for #{reflection.name} (#{reflection.options[:inverse_of].inspect} in #{associated_class.nil? ? reflection.class_name : associated_class.name})")
-
end
-
end
-
-
1
class HasManyThroughAssociationNotFoundError < ActiveRecordError #:nodoc:
-
1
def initialize(owner_class_name, reflection)
-
super("Could not find the association #{reflection.options[:through].inspect} in model #{owner_class_name}")
-
end
-
end
-
-
1
class HasManyThroughAssociationPolymorphicSourceError < ActiveRecordError #:nodoc:
-
1
def initialize(owner_class_name, reflection, source_reflection)
-
super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' on the polymorphic object '#{source_reflection.class_name}##{source_reflection.name}' without 'source_type'. Try adding 'source_type: \"#{reflection.name.to_s.classify}\"' to 'has_many :through' definition.")
-
end
-
end
-
-
1
class HasManyThroughAssociationPolymorphicThroughError < ActiveRecordError #:nodoc:
-
1
def initialize(owner_class_name, reflection)
-
super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' which goes through the polymorphic association '#{owner_class_name}##{reflection.through_reflection.name}'.")
-
end
-
end
-
-
1
class HasManyThroughAssociationPointlessSourceTypeError < ActiveRecordError #:nodoc:
-
1
def initialize(owner_class_name, reflection, source_reflection)
-
super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' with a :source_type option if the '#{reflection.through_reflection.class_name}##{source_reflection.name}' is not polymorphic. Try removing :source_type on your association.")
-
end
-
end
-
-
1
class HasOneThroughCantAssociateThroughCollection < ActiveRecordError #:nodoc:
-
1
def initialize(owner_class_name, reflection, through_reflection)
-
super("Cannot have a has_one :through association '#{owner_class_name}##{reflection.name}' where the :through association '#{owner_class_name}##{through_reflection.name}' is a collection. Specify a has_one or belongs_to association in the :through option instead.")
-
end
-
end
-
-
1
class HasManyThroughSourceAssociationNotFoundError < ActiveRecordError #:nodoc:
-
1
def initialize(reflection)
-
through_reflection = reflection.through_reflection
-
source_reflection_names = reflection.source_reflection_names
-
source_associations = reflection.through_reflection.klass.reflect_on_all_associations.collect { |a| a.name.inspect }
-
super("Could not find the source association(s) #{source_reflection_names.collect{ |a| a.inspect }.to_sentence(:two_words_connector => ' or ', :last_word_connector => ', or ', :locale => :en)} in model #{through_reflection.klass}. Try 'has_many #{reflection.name.inspect}, :through => #{through_reflection.name.inspect}, :source => <name>'. Is it one of #{source_associations.to_sentence(:two_words_connector => ' or ', :last_word_connector => ', or ', :locale => :en)}?")
-
end
-
end
-
-
1
class HasManyThroughCantAssociateThroughHasOneOrManyReflection < ActiveRecordError #:nodoc:
-
1
def initialize(owner, reflection)
-
super("Cannot modify association '#{owner.class.name}##{reflection.name}' because the source reflection class '#{reflection.source_reflection.class_name}' is associated to '#{reflection.through_reflection.class_name}' via :#{reflection.source_reflection.macro}.")
-
end
-
end
-
-
1
class HasManyThroughCantAssociateNewRecords < ActiveRecordError #:nodoc:
-
1
def initialize(owner, reflection)
-
super("Cannot associate new records through '#{owner.class.name}##{reflection.name}' on '#{reflection.source_reflection.class_name rescue nil}##{reflection.source_reflection.name rescue nil}'. Both records must have an id in order to create the has_many :through record associating them.")
-
end
-
end
-
-
1
class HasManyThroughCantDissociateNewRecords < ActiveRecordError #:nodoc:
-
1
def initialize(owner, reflection)
-
super("Cannot dissociate new records through '#{owner.class.name}##{reflection.name}' on '#{reflection.source_reflection.class_name rescue nil}##{reflection.source_reflection.name rescue nil}'. Both records must have an id in order to delete the has_many :through record associating them.")
-
end
-
end
-
-
1
class HasManyThroughNestedAssociationsAreReadonly < ActiveRecordError #:nodoc:
-
1
def initialize(owner, reflection)
-
super("Cannot modify association '#{owner.class.name}##{reflection.name}' because it goes through more than one other association.")
-
end
-
end
-
-
1
class EagerLoadPolymorphicError < ActiveRecordError #:nodoc:
-
1
def initialize(reflection)
-
super("Cannot eagerly load the polymorphic association #{reflection.name.inspect}")
-
end
-
end
-
-
1
class ReadOnlyAssociation < ActiveRecordError #:nodoc:
-
1
def initialize(reflection)
-
super("Cannot add to a has_many :through association. Try adding to #{reflection.through_reflection.name.inspect}.")
-
end
-
end
-
-
# This error is raised when trying to destroy a parent instance in N:1 or 1:1 associations
-
# (has_many, has_one) when there is at least 1 child associated instance.
-
# ex: if @project.tasks.size > 0, DeleteRestrictionError will be raised when trying to destroy @project
-
1
class DeleteRestrictionError < ActiveRecordError #:nodoc:
-
1
def initialize(name)
-
super("Cannot delete record because of dependent #{name}")
-
end
-
end
-
-
# See ActiveRecord::Associations::ClassMethods for documentation.
-
1
module Associations # :nodoc:
-
1
extend ActiveSupport::Autoload
-
1
extend ActiveSupport::Concern
-
-
# These classes will be loaded when associations are created.
-
# So there is no need to eager load them.
-
1
autoload :Association, 'active_record/associations/association'
-
1
autoload :SingularAssociation, 'active_record/associations/singular_association'
-
1
autoload :CollectionAssociation, 'active_record/associations/collection_association'
-
1
autoload :CollectionProxy, 'active_record/associations/collection_proxy'
-
-
1
autoload :BelongsToAssociation, 'active_record/associations/belongs_to_association'
-
1
autoload :BelongsToPolymorphicAssociation, 'active_record/associations/belongs_to_polymorphic_association'
-
1
autoload :HasManyAssociation, 'active_record/associations/has_many_association'
-
1
autoload :HasManyThroughAssociation, 'active_record/associations/has_many_through_association'
-
1
autoload :HasOneAssociation, 'active_record/associations/has_one_association'
-
1
autoload :HasOneThroughAssociation, 'active_record/associations/has_one_through_association'
-
1
autoload :ThroughAssociation, 'active_record/associations/through_association'
-
-
1
module Builder #:nodoc:
-
1
autoload :Association, 'active_record/associations/builder/association'
-
1
autoload :SingularAssociation, 'active_record/associations/builder/singular_association'
-
1
autoload :CollectionAssociation, 'active_record/associations/builder/collection_association'
-
-
1
autoload :BelongsTo, 'active_record/associations/builder/belongs_to'
-
1
autoload :HasOne, 'active_record/associations/builder/has_one'
-
1
autoload :HasMany, 'active_record/associations/builder/has_many'
-
1
autoload :HasAndBelongsToMany, 'active_record/associations/builder/has_and_belongs_to_many'
-
end
-
-
1
eager_autoload do
-
1
autoload :Preloader, 'active_record/associations/preloader'
-
1
autoload :JoinDependency, 'active_record/associations/join_dependency'
-
1
autoload :AssociationScope, 'active_record/associations/association_scope'
-
1
autoload :AliasTracker, 'active_record/associations/alias_tracker'
-
end
-
-
# Clears out the association cache.
-
1
def clear_association_cache #:nodoc:
-
@association_cache.clear if persisted?
-
end
-
-
# :nodoc:
-
1
attr_reader :association_cache
-
-
# Returns the association instance for the given name, instantiating it if it doesn't already exist
-
1
def association(name) #:nodoc:
-
association = association_instance_get(name)
-
-
if association.nil?
-
reflection = self.class.reflect_on_association(name)
-
association = reflection.association_class.new(self, reflection)
-
association_instance_set(name, association)
-
end
-
-
association
-
end
-
-
1
private
-
# Returns the specified association instance if it responds to :loaded?, nil otherwise.
-
1
def association_instance_get(name)
-
@association_cache[name]
-
end
-
-
# Set the specified association instance.
-
1
def association_instance_set(name, association)
-
@association_cache[name] = association
-
end
-
-
# \Associations are a set of macro-like class methods for tying objects together through
-
# foreign keys. They express relationships like "Project has one Project Manager"
-
# or "Project belongs to a Portfolio". Each macro adds a number of methods to the
-
# class which are specialized according to the collection or association symbol and the
-
# options hash. It works much the same way as Ruby's own <tt>attr*</tt>
-
# methods.
-
#
-
# class Project < ActiveRecord::Base
-
# belongs_to :portfolio
-
# has_one :project_manager
-
# has_many :milestones
-
# has_and_belongs_to_many :categories
-
# end
-
#
-
# The project class now has the following methods (and more) to ease the traversal and
-
# manipulation of its relationships:
-
# * <tt>Project#portfolio, Project#portfolio=(portfolio), Project#portfolio.nil?</tt>
-
# * <tt>Project#project_manager, Project#project_manager=(project_manager), Project#project_manager.nil?,</tt>
-
# * <tt>Project#milestones.empty?, Project#milestones.size, Project#milestones, Project#milestones<<(milestone),</tt>
-
# <tt>Project#milestones.delete(milestone), Project#milestones.destroy(milestone), Project#milestones.find(milestone_id),</tt>
-
# <tt>Project#milestones.build, Project#milestones.create</tt>
-
# * <tt>Project#categories.empty?, Project#categories.size, Project#categories, Project#categories<<(category1),</tt>
-
# <tt>Project#categories.delete(category1), Project#categories.destroy(category1)</tt>
-
#
-
# === A word of warning
-
#
-
# Don't create associations that have the same name as instance methods of
-
# <tt>ActiveRecord::Base</tt>. Since the association adds a method with that name to
-
# its model, it will override the inherited method and break things.
-
# For instance, +attributes+ and +connection+ would be bad choices for association names.
-
#
-
# == Auto-generated methods
-
#
-
# === Singular associations (one-to-one)
-
# | | belongs_to |
-
# generated methods | belongs_to | :polymorphic | has_one
-
# ----------------------------------+------------+--------------+---------
-
# other | X | X | X
-
# other=(other) | X | X | X
-
# build_other(attributes={}) | X | | X
-
# create_other(attributes={}) | X | | X
-
# create_other!(attributes={}) | X | | X
-
#
-
# ===Collection associations (one-to-many / many-to-many)
-
# | | | has_many
-
# generated methods | habtm | has_many | :through
-
# ----------------------------------+-------+----------+----------
-
# others | X | X | X
-
# others=(other,other,...) | X | X | X
-
# other_ids | X | X | X
-
# other_ids=(id,id,...) | X | X | X
-
# others<< | X | X | X
-
# others.push | X | X | X
-
# others.concat | X | X | X
-
# others.build(attributes={}) | X | X | X
-
# others.create(attributes={}) | X | X | X
-
# others.create!(attributes={}) | X | X | X
-
# others.size | X | X | X
-
# others.length | X | X | X
-
# others.count | X | X | X
-
# others.sum(*args) | X | X | X
-
# others.empty? | X | X | X
-
# others.clear | X | X | X
-
# others.delete(other,other,...) | X | X | X
-
# others.delete_all | X | X | X
-
# others.destroy(other,other,...) | X | X | X
-
# others.destroy_all | X | X | X
-
# others.find(*args) | X | X | X
-
# others.exists? | X | X | X
-
# others.distinct | X | X | X
-
# others.uniq | X | X | X
-
# others.reset | X | X | X
-
#
-
# === Overriding generated methods
-
#
-
# Association methods are generated in a module that is included into the model class,
-
# which allows you to easily override with your own methods and call the original
-
# generated method with +super+. For example:
-
#
-
# class Car < ActiveRecord::Base
-
# belongs_to :owner
-
# belongs_to :old_owner
-
# def owner=(new_owner)
-
# self.old_owner = self.owner
-
# super
-
# end
-
# end
-
#
-
# If your model class is <tt>Project</tt>, the module is
-
# named <tt>Project::GeneratedFeatureMethods</tt>. The GeneratedFeatureMethods module is
-
# included in the model class immediately after the (anonymous) generated attributes methods
-
# module, meaning an association will override the methods for an attribute with the same name.
-
#
-
# == Cardinality and associations
-
#
-
# Active Record associations can be used to describe one-to-one, one-to-many and many-to-many
-
# relationships between models. Each model uses an association to describe its role in
-
# the relation. The +belongs_to+ association is always used in the model that has
-
# the foreign key.
-
#
-
# === One-to-one
-
#
-
# Use +has_one+ in the base, and +belongs_to+ in the associated model.
-
#
-
# class Employee < ActiveRecord::Base
-
# has_one :office
-
# end
-
# class Office < ActiveRecord::Base
-
# belongs_to :employee # foreign key - employee_id
-
# end
-
#
-
# === One-to-many
-
#
-
# Use +has_many+ in the base, and +belongs_to+ in the associated model.
-
#
-
# class Manager < ActiveRecord::Base
-
# has_many :employees
-
# end
-
# class Employee < ActiveRecord::Base
-
# belongs_to :manager # foreign key - manager_id
-
# end
-
#
-
# === Many-to-many
-
#
-
# There are two ways to build a many-to-many relationship.
-
#
-
# The first way uses a +has_many+ association with the <tt>:through</tt> option and a join model, so
-
# there are two stages of associations.
-
#
-
# class Assignment < ActiveRecord::Base
-
# belongs_to :programmer # foreign key - programmer_id
-
# belongs_to :project # foreign key - project_id
-
# end
-
# class Programmer < ActiveRecord::Base
-
# has_many :assignments
-
# has_many :projects, through: :assignments
-
# end
-
# class Project < ActiveRecord::Base
-
# has_many :assignments
-
# has_many :programmers, through: :assignments
-
# end
-
#
-
# For the second way, use +has_and_belongs_to_many+ in both models. This requires a join table
-
# that has no corresponding model or primary key.
-
#
-
# class Programmer < ActiveRecord::Base
-
# has_and_belongs_to_many :projects # foreign keys in the join table
-
# end
-
# class Project < ActiveRecord::Base
-
# has_and_belongs_to_many :programmers # foreign keys in the join table
-
# end
-
#
-
# Choosing which way to build a many-to-many relationship is not always simple.
-
# If you need to work with the relationship model as its own entity,
-
# use <tt>has_many :through</tt>. Use +has_and_belongs_to_many+ when working with legacy schemas or when
-
# you never work directly with the relationship itself.
-
#
-
# == Is it a +belongs_to+ or +has_one+ association?
-
#
-
# Both express a 1-1 relationship. The difference is mostly where to place the foreign
-
# key, which goes on the table for the class declaring the +belongs_to+ relationship.
-
#
-
# class User < ActiveRecord::Base
-
# # I reference an account.
-
# belongs_to :account
-
# end
-
#
-
# class Account < ActiveRecord::Base
-
# # One user references me.
-
# has_one :user
-
# end
-
#
-
# The tables for these classes could look something like:
-
#
-
# CREATE TABLE users (
-
# id int(11) NOT NULL auto_increment,
-
# account_id int(11) default NULL,
-
# name varchar default NULL,
-
# PRIMARY KEY (id)
-
# )
-
#
-
# CREATE TABLE accounts (
-
# id int(11) NOT NULL auto_increment,
-
# name varchar default NULL,
-
# PRIMARY KEY (id)
-
# )
-
#
-
# == Unsaved objects and associations
-
#
-
# You can manipulate objects and associations before they are saved to the database, but
-
# there is some special behavior you should be aware of, mostly involving the saving of
-
# associated objects.
-
#
-
# You can set the <tt>:autosave</tt> option on a <tt>has_one</tt>, <tt>belongs_to</tt>,
-
# <tt>has_many</tt>, or <tt>has_and_belongs_to_many</tt> association. Setting it
-
# to +true+ will _always_ save the members, whereas setting it to +false+ will
-
# _never_ save the members. More details about <tt>:autosave</tt> option is available at
-
# AutosaveAssociation.
-
#
-
# === One-to-one associations
-
#
-
# * Assigning an object to a +has_one+ association automatically saves that object and
-
# the object being replaced (if there is one), in order to update their foreign
-
# keys - except if the parent object is unsaved (<tt>new_record? == true</tt>).
-
# * If either of these saves fail (due to one of the objects being invalid), an
-
# <tt>ActiveRecord::RecordNotSaved</tt> exception is raised and the assignment is
-
# cancelled.
-
# * If you wish to assign an object to a +has_one+ association without saving it,
-
# use the <tt>build_association</tt> method (documented below). The object being
-
# replaced will still be saved to update its foreign key.
-
# * Assigning an object to a +belongs_to+ association does not save the object, since
-
# the foreign key field belongs on the parent. It does not save the parent either.
-
#
-
# === Collections
-
#
-
# * Adding an object to a collection (+has_many+ or +has_and_belongs_to_many+) automatically
-
# saves that object, except if the parent object (the owner of the collection) is not yet
-
# stored in the database.
-
# * If saving any of the objects being added to a collection (via <tt>push</tt> or similar)
-
# fails, then <tt>push</tt> returns +false+.
-
# * If saving fails while replacing the collection (via <tt>association=</tt>), an
-
# <tt>ActiveRecord::RecordNotSaved</tt> exception is raised and the assignment is
-
# cancelled.
-
# * You can add an object to a collection without automatically saving it by using the
-
# <tt>collection.build</tt> method (documented below).
-
# * All unsaved (<tt>new_record? == true</tt>) members of the collection are automatically
-
# saved when the parent is saved.
-
#
-
# == Customizing the query
-
#
-
# \Associations are built from <tt>Relation</tt>s, and you can use the <tt>Relation</tt> syntax
-
# to customize them. For example, to add a condition:
-
#
-
# class Blog < ActiveRecord::Base
-
# has_many :published_posts, -> { where published: true }, class_name: 'Post'
-
# end
-
#
-
# Inside the <tt>-> { ... }</tt> block you can use all of the usual <tt>Relation</tt> methods.
-
#
-
# === Accessing the owner object
-
#
-
# Sometimes it is useful to have access to the owner object when building the query. The owner
-
# is passed as a parameter to the block. For example, the following association would find all
-
# events that occur on the user's birthday:
-
#
-
# class User < ActiveRecord::Base
-
# has_many :birthday_events, ->(user) { where starts_on: user.birthday }, class_name: 'Event'
-
# end
-
#
-
# == Association callbacks
-
#
-
# Similar to the normal callbacks that hook into the life cycle of an Active Record object,
-
# you can also define callbacks that get triggered when you add an object to or remove an
-
# object from an association collection.
-
#
-
# class Project
-
# has_and_belongs_to_many :developers, after_add: :evaluate_velocity
-
#
-
# def evaluate_velocity(developer)
-
# ...
-
# end
-
# end
-
#
-
# It's possible to stack callbacks by passing them as an array. Example:
-
#
-
# class Project
-
# has_and_belongs_to_many :developers,
-
# after_add: [:evaluate_velocity, Proc.new { |p, d| p.shipping_date = Time.now}]
-
# end
-
#
-
# Possible callbacks are: +before_add+, +after_add+, +before_remove+ and +after_remove+.
-
#
-
# Should any of the +before_add+ callbacks throw an exception, the object does not get
-
# added to the collection. Same with the +before_remove+ callbacks; if an exception is
-
# thrown the object doesn't get removed.
-
#
-
# == Association extensions
-
#
-
# The proxy objects that control the access to associations can be extended through anonymous
-
# modules. This is especially beneficial for adding new finders, creators, and other
-
# factory-type methods that are only used as part of this association.
-
#
-
# class Account < ActiveRecord::Base
-
# has_many :people do
-
# def find_or_create_by_name(name)
-
# first_name, last_name = name.split(" ", 2)
-
# find_or_create_by(first_name: first_name, last_name: last_name)
-
# end
-
# end
-
# end
-
#
-
# person = Account.first.people.find_or_create_by_name("David Heinemeier Hansson")
-
# person.first_name # => "David"
-
# person.last_name # => "Heinemeier Hansson"
-
#
-
# If you need to share the same extensions between many associations, you can use a named
-
# extension module.
-
#
-
# module FindOrCreateByNameExtension
-
# def find_or_create_by_name(name)
-
# first_name, last_name = name.split(" ", 2)
-
# find_or_create_by(first_name: first_name, last_name: last_name)
-
# end
-
# end
-
#
-
# class Account < ActiveRecord::Base
-
# has_many :people, -> { extending FindOrCreateByNameExtension }
-
# end
-
#
-
# class Company < ActiveRecord::Base
-
# has_many :people, -> { extending FindOrCreateByNameExtension }
-
# end
-
#
-
# Some extensions can only be made to work with knowledge of the association's internals.
-
# Extensions can access relevant state using the following methods (where +items+ is the
-
# name of the association):
-
#
-
# * <tt>record.association(:items).owner</tt> - Returns the object the association is part of.
-
# * <tt>record.association(:items).reflection</tt> - Returns the reflection object that describes the association.
-
# * <tt>record.association(:items).target</tt> - Returns the associated object for +belongs_to+ and +has_one+, or
-
# the collection of associated objects for +has_many+ and +has_and_belongs_to_many+.
-
#
-
# However, inside the actual extension code, you will not have access to the <tt>record</tt> as
-
# above. In this case, you can access <tt>proxy_association</tt>. For example,
-
# <tt>record.association(:items)</tt> and <tt>record.items.proxy_association</tt> will return
-
# the same object, allowing you to make calls like <tt>proxy_association.owner</tt> inside
-
# association extensions.
-
#
-
# == Association Join Models
-
#
-
# Has Many associations can be configured with the <tt>:through</tt> option to use an
-
# explicit join model to retrieve the data. This operates similarly to a
-
# +has_and_belongs_to_many+ association. The advantage is that you're able to add validations,
-
# callbacks, and extra attributes on the join model. Consider the following schema:
-
#
-
# class Author < ActiveRecord::Base
-
# has_many :authorships
-
# has_many :books, through: :authorships
-
# end
-
#
-
# class Authorship < ActiveRecord::Base
-
# belongs_to :author
-
# belongs_to :book
-
# end
-
#
-
# @author = Author.first
-
# @author.authorships.collect { |a| a.book } # selects all books that the author's authorships belong to
-
# @author.books # selects all books by using the Authorship join model
-
#
-
# You can also go through a +has_many+ association on the join model:
-
#
-
# class Firm < ActiveRecord::Base
-
# has_many :clients
-
# has_many :invoices, through: :clients
-
# end
-
#
-
# class Client < ActiveRecord::Base
-
# belongs_to :firm
-
# has_many :invoices
-
# end
-
#
-
# class Invoice < ActiveRecord::Base
-
# belongs_to :client
-
# end
-
#
-
# @firm = Firm.first
-
# @firm.clients.collect { |c| c.invoices }.flatten # select all invoices for all clients of the firm
-
# @firm.invoices # selects all invoices by going through the Client join model
-
#
-
# Similarly you can go through a +has_one+ association on the join model:
-
#
-
# class Group < ActiveRecord::Base
-
# has_many :users
-
# has_many :avatars, through: :users
-
# end
-
#
-
# class User < ActiveRecord::Base
-
# belongs_to :group
-
# has_one :avatar
-
# end
-
#
-
# class Avatar < ActiveRecord::Base
-
# belongs_to :user
-
# end
-
#
-
# @group = Group.first
-
# @group.users.collect { |u| u.avatar }.compact # select all avatars for all users in the group
-
# @group.avatars # selects all avatars by going through the User join model.
-
#
-
# An important caveat with going through +has_one+ or +has_many+ associations on the
-
# join model is that these associations are *read-only*. For example, the following
-
# would not work following the previous example:
-
#
-
# @group.avatars << Avatar.new # this would work if User belonged_to Avatar rather than the other way around
-
# @group.avatars.delete(@group.avatars.last) # so would this
-
#
-
# == Setting Inverses
-
#
-
# If you are using a +belongs_to+ on the join model, it is a good idea to set the
-
# <tt>:inverse_of</tt> option on the +belongs_to+, which will mean that the following example
-
# works correctly (where <tt>tags</tt> is a +has_many+ <tt>:through</tt> association):
-
#
-
# @post = Post.first
-
# @tag = @post.tags.build name: "ruby"
-
# @tag.save
-
#
-
# The last line ought to save the through record (a <tt>Taggable</tt>). This will only work if the
-
# <tt>:inverse_of</tt> is set:
-
#
-
# class Taggable < ActiveRecord::Base
-
# belongs_to :post
-
# belongs_to :tag, inverse_of: :taggings
-
# end
-
#
-
# If you do not set the <tt>:inverse_of</tt> record, the association will
-
# do its best to match itself up with the correct inverse. Automatic
-
# inverse detection only works on <tt>has_many</tt>, <tt>has_one</tt>, and
-
# <tt>belongs_to</tt> associations.
-
#
-
# Extra options on the associations, as defined in the
-
# <tt>AssociationReflection::INVALID_AUTOMATIC_INVERSE_OPTIONS</tt> constant, will
-
# also prevent the association's inverse from being found automatically.
-
#
-
# The automatic guessing of the inverse association uses a heuristic based
-
# on the name of the class, so it may not work for all associations,
-
# especially the ones with non-standard names.
-
#
-
# You can turn off the automatic detection of inverse associations by setting
-
# the <tt>:inverse_of</tt> option to <tt>false</tt> like so:
-
#
-
# class Taggable < ActiveRecord::Base
-
# belongs_to :tag, inverse_of: false
-
# end
-
#
-
# == Nested \Associations
-
#
-
# You can actually specify *any* association with the <tt>:through</tt> option, including an
-
# association which has a <tt>:through</tt> option itself. For example:
-
#
-
# class Author < ActiveRecord::Base
-
# has_many :posts
-
# has_many :comments, through: :posts
-
# has_many :commenters, through: :comments
-
# end
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :comments
-
# end
-
#
-
# class Comment < ActiveRecord::Base
-
# belongs_to :commenter
-
# end
-
#
-
# @author = Author.first
-
# @author.commenters # => People who commented on posts written by the author
-
#
-
# An equivalent way of setting up this association this would be:
-
#
-
# class Author < ActiveRecord::Base
-
# has_many :posts
-
# has_many :commenters, through: :posts
-
# end
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :comments
-
# has_many :commenters, through: :comments
-
# end
-
#
-
# class Comment < ActiveRecord::Base
-
# belongs_to :commenter
-
# end
-
#
-
# When using nested association, you will not be able to modify the association because there
-
# is not enough information to know what modification to make. For example, if you tried to
-
# add a <tt>Commenter</tt> in the example above, there would be no way to tell how to set up the
-
# intermediate <tt>Post</tt> and <tt>Comment</tt> objects.
-
#
-
# == Polymorphic \Associations
-
#
-
# Polymorphic associations on models are not restricted on what types of models they
-
# can be associated with. Rather, they specify an interface that a +has_many+ association
-
# must adhere to.
-
#
-
# class Asset < ActiveRecord::Base
-
# belongs_to :attachable, polymorphic: true
-
# end
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :assets, as: :attachable # The :as option specifies the polymorphic interface to use.
-
# end
-
#
-
# @asset.attachable = @post
-
#
-
# This works by using a type column in addition to a foreign key to specify the associated
-
# record. In the Asset example, you'd need an +attachable_id+ integer column and an
-
# +attachable_type+ string column.
-
#
-
# Using polymorphic associations in combination with single table inheritance (STI) is
-
# a little tricky. In order for the associations to work as expected, ensure that you
-
# store the base model for the STI models in the type column of the polymorphic
-
# association. To continue with the asset example above, suppose there are guest posts
-
# and member posts that use the posts table for STI. In this case, there must be a +type+
-
# column in the posts table.
-
#
-
# Note: The <tt>attachable_type=</tt> method is being called when assigning an +attachable+.
-
# The +class_name+ of the +attachable+ is passed as a String.
-
#
-
# class Asset < ActiveRecord::Base
-
# belongs_to :attachable, polymorphic: true
-
#
-
# def attachable_type=(class_name)
-
# super(class_name.constantize.base_class.to_s)
-
# end
-
# end
-
#
-
# class Post < ActiveRecord::Base
-
# # because we store "Post" in attachable_type now dependent: :destroy will work
-
# has_many :assets, as: :attachable, dependent: :destroy
-
# end
-
#
-
# class GuestPost < Post
-
# end
-
#
-
# class MemberPost < Post
-
# end
-
#
-
# == Caching
-
#
-
# All of the methods are built on a simple caching principle that will keep the result
-
# of the last query around unless specifically instructed not to. The cache is even
-
# shared across methods to make it even cheaper to use the macro-added methods without
-
# worrying too much about performance at the first go.
-
#
-
# project.milestones # fetches milestones from the database
-
# project.milestones.size # uses the milestone cache
-
# project.milestones.empty? # uses the milestone cache
-
# project.milestones(true).size # fetches milestones from the database
-
# project.milestones # uses the milestone cache
-
#
-
# == Eager loading of associations
-
#
-
# Eager loading is a way to find objects of a certain class and a number of named associations.
-
# This is one of the easiest ways of to prevent the dreaded 1+N problem in which fetching 100
-
# posts that each need to display their author triggers 101 database queries. Through the
-
# use of eager loading, the 101 queries can be reduced to 2.
-
#
-
# class Post < ActiveRecord::Base
-
# belongs_to :author
-
# has_many :comments
-
# end
-
#
-
# Consider the following loop using the class above:
-
#
-
# Post.all.each do |post|
-
# puts "Post: " + post.title
-
# puts "Written by: " + post.author.name
-
# puts "Last comment on: " + post.comments.first.created_on
-
# end
-
#
-
# To iterate over these one hundred posts, we'll generate 201 database queries. Let's
-
# first just optimize it for retrieving the author:
-
#
-
# Post.includes(:author).each do |post|
-
#
-
# This references the name of the +belongs_to+ association that also used the <tt>:author</tt>
-
# symbol. After loading the posts, find will collect the +author_id+ from each one and load
-
# all the referenced authors with one query. Doing so will cut down the number of queries
-
# from 201 to 102.
-
#
-
# We can improve upon the situation further by referencing both associations in the finder with:
-
#
-
# Post.includes(:author, :comments).each do |post|
-
#
-
# This will load all comments with a single query. This reduces the total number of queries
-
# to 3. More generally the number of queries will be 1 plus the number of associations
-
# named (except if some of the associations are polymorphic +belongs_to+ - see below).
-
#
-
# To include a deep hierarchy of associations, use a hash:
-
#
-
# Post.includes(:author, {comments: {author: :gravatar}}).each do |post|
-
#
-
# That'll grab not only all the comments but all their authors and gravatar pictures.
-
# You can mix and match symbols, arrays and hashes in any combination to describe the
-
# associations you want to load.
-
#
-
# All of this power shouldn't fool you into thinking that you can pull out huge amounts
-
# of data with no performance penalty just because you've reduced the number of queries.
-
# The database still needs to send all the data to Active Record and it still needs to
-
# be processed. So it's no catch-all for performance problems, but it's a great way to
-
# cut down on the number of queries in a situation as the one described above.
-
#
-
# Since only one table is loaded at a time, conditions or orders cannot reference tables
-
# other than the main one. If this is the case Active Record falls back to the previously
-
# used LEFT OUTER JOIN based strategy. For example
-
#
-
# Post.includes([:author, :comments]).where(['comments.approved = ?', true])
-
#
-
# This will result in a single SQL query with joins along the lines of:
-
# <tt>LEFT OUTER JOIN comments ON comments.post_id = posts.id</tt> and
-
# <tt>LEFT OUTER JOIN authors ON authors.id = posts.author_id</tt>. Note that using conditions
-
# like this can have unintended consequences.
-
# In the above example posts with no approved comments are not returned at all, because
-
# the conditions apply to the SQL statement as a whole and not just to the association.
-
# You must disambiguate column references for this fallback to happen, for example
-
# <tt>order: "author.name DESC"</tt> will work but <tt>order: "name DESC"</tt> will not.
-
#
-
# If you do want eager load only some members of an association it is usually more natural
-
# to include an association which has conditions defined on it:
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :approved_comments, -> { where approved: true }, class_name: 'Comment'
-
# end
-
#
-
# Post.includes(:approved_comments)
-
#
-
# This will load posts and eager load the +approved_comments+ association, which contains
-
# only those comments that have been approved.
-
#
-
# If you eager load an association with a specified <tt>:limit</tt> option, it will be ignored,
-
# returning all the associated objects:
-
#
-
# class Picture < ActiveRecord::Base
-
# has_many :most_recent_comments, -> { order('id DESC').limit(10) }, class_name: 'Comment'
-
# end
-
#
-
# Picture.includes(:most_recent_comments).first.most_recent_comments # => returns all associated comments.
-
#
-
# Eager loading is supported with polymorphic associations.
-
#
-
# class Address < ActiveRecord::Base
-
# belongs_to :addressable, polymorphic: true
-
# end
-
#
-
# A call that tries to eager load the addressable model
-
#
-
# Address.includes(:addressable)
-
#
-
# This will execute one query to load the addresses and load the addressables with one
-
# query per addressable type.
-
# For example if all the addressables are either of class Person or Company then a total
-
# of 3 queries will be executed. The list of addressable types to load is determined on
-
# the back of the addresses loaded. This is not supported if Active Record has to fallback
-
# to the previous implementation of eager loading and will raise <tt>ActiveRecord::EagerLoadPolymorphicError</tt>.
-
# The reason is that the parent model's type is a column value so its corresponding table
-
# name cannot be put in the +FROM+/+JOIN+ clauses of that query.
-
#
-
# == Table Aliasing
-
#
-
# Active Record uses table aliasing in the case that a table is referenced multiple times
-
# in a join. If a table is referenced only once, the standard table name is used. The
-
# second time, the table is aliased as <tt>#{reflection_name}_#{parent_table_name}</tt>.
-
# Indexes are appended for any more successive uses of the table name.
-
#
-
# Post.joins(:comments)
-
# # => SELECT ... FROM posts INNER JOIN comments ON ...
-
# Post.joins(:special_comments) # STI
-
# # => SELECT ... FROM posts INNER JOIN comments ON ... AND comments.type = 'SpecialComment'
-
# Post.joins(:comments, :special_comments) # special_comments is the reflection name, posts is the parent table name
-
# # => SELECT ... FROM posts INNER JOIN comments ON ... INNER JOIN comments special_comments_posts
-
#
-
# Acts as tree example:
-
#
-
# TreeMixin.joins(:children)
-
# # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
-
# TreeMixin.joins(children: :parent)
-
# # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
-
# INNER JOIN parents_mixins ...
-
# TreeMixin.joins(children: {parent: :children})
-
# # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
-
# INNER JOIN parents_mixins ...
-
# INNER JOIN mixins childrens_mixins_2
-
#
-
# Has and Belongs to Many join tables use the same idea, but add a <tt>_join</tt> suffix:
-
#
-
# Post.joins(:categories)
-
# # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
-
# Post.joins(categories: :posts)
-
# # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
-
# INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories
-
# Post.joins(categories: {posts: :categories})
-
# # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
-
# INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories
-
# INNER JOIN categories_posts categories_posts_join INNER JOIN categories categories_posts_2
-
#
-
# If you wish to specify your own custom joins using <tt>joins</tt> method, those table
-
# names will take precedence over the eager associations:
-
#
-
# Post.joins(:comments).joins("inner join comments ...")
-
# # => SELECT ... FROM posts INNER JOIN comments_posts ON ... INNER JOIN comments ...
-
# Post.joins(:comments, :special_comments).joins("inner join comments ...")
-
# # => SELECT ... FROM posts INNER JOIN comments comments_posts ON ...
-
# INNER JOIN comments special_comments_posts ...
-
# INNER JOIN comments ...
-
#
-
# Table aliases are automatically truncated according to the maximum length of table identifiers
-
# according to the specific database.
-
#
-
# == Modules
-
#
-
# By default, associations will look for objects within the current module scope. Consider:
-
#
-
# module MyApplication
-
# module Business
-
# class Firm < ActiveRecord::Base
-
# has_many :clients
-
# end
-
#
-
# class Client < ActiveRecord::Base; end
-
# end
-
# end
-
#
-
# When <tt>Firm#clients</tt> is called, it will in turn call
-
# <tt>MyApplication::Business::Client.find_all_by_firm_id(firm.id)</tt>.
-
# If you want to associate with a class in another module scope, this can be done by
-
# specifying the complete class name.
-
#
-
# module MyApplication
-
# module Business
-
# class Firm < ActiveRecord::Base; end
-
# end
-
#
-
# module Billing
-
# class Account < ActiveRecord::Base
-
# belongs_to :firm, class_name: "MyApplication::Business::Firm"
-
# end
-
# end
-
# end
-
#
-
# == Bi-directional associations
-
#
-
# When you specify an association there is usually an association on the associated model
-
# that specifies the same relationship in reverse. For example, with the following models:
-
#
-
# class Dungeon < ActiveRecord::Base
-
# has_many :traps
-
# has_one :evil_wizard
-
# end
-
#
-
# class Trap < ActiveRecord::Base
-
# belongs_to :dungeon
-
# end
-
#
-
# class EvilWizard < ActiveRecord::Base
-
# belongs_to :dungeon
-
# end
-
#
-
# The +traps+ association on +Dungeon+ and the +dungeon+ association on +Trap+ are
-
# the inverse of each other and the inverse of the +dungeon+ association on +EvilWizard+
-
# is the +evil_wizard+ association on +Dungeon+ (and vice-versa). By default,
-
# Active Record doesn't know anything about these inverse relationships and so no object
-
# loading optimization is possible. For example:
-
#
-
# d = Dungeon.first
-
# t = d.traps.first
-
# d.level == t.dungeon.level # => true
-
# d.level = 10
-
# d.level == t.dungeon.level # => false
-
#
-
# The +Dungeon+ instances +d+ and <tt>t.dungeon</tt> in the above example refer to
-
# the same object data from the database, but are actually different in-memory copies
-
# of that data. Specifying the <tt>:inverse_of</tt> option on associations lets you tell
-
# Active Record about inverse relationships and it will optimise object loading. For
-
# example, if we changed our model definitions to:
-
#
-
# class Dungeon < ActiveRecord::Base
-
# has_many :traps, inverse_of: :dungeon
-
# has_one :evil_wizard, inverse_of: :dungeon
-
# end
-
#
-
# class Trap < ActiveRecord::Base
-
# belongs_to :dungeon, inverse_of: :traps
-
# end
-
#
-
# class EvilWizard < ActiveRecord::Base
-
# belongs_to :dungeon, inverse_of: :evil_wizard
-
# end
-
#
-
# Then, from our code snippet above, +d+ and <tt>t.dungeon</tt> are actually the same
-
# in-memory instance and our final <tt>d.level == t.dungeon.level</tt> will return +true+.
-
#
-
# There are limitations to <tt>:inverse_of</tt> support:
-
#
-
# * does not work with <tt>:through</tt> associations.
-
# * does not work with <tt>:polymorphic</tt> associations.
-
# * for +belongs_to+ associations +has_many+ inverse associations are ignored.
-
#
-
# == Deleting from associations
-
#
-
# === Dependent associations
-
#
-
# +has_many+, +has_one+ and +belongs_to+ associations support the <tt>:dependent</tt> option.
-
# This allows you to specify that associated records should be deleted when the owner is
-
# deleted.
-
#
-
# For example:
-
#
-
# class Author
-
# has_many :posts, dependent: :destroy
-
# end
-
# Author.find(1).destroy # => Will destroy all of the author's posts, too
-
#
-
# The <tt>:dependent</tt> option can have different values which specify how the deletion
-
# is done. For more information, see the documentation for this option on the different
-
# specific association types. When no option is given, the behavior is to do nothing
-
# with the associated records when destroying a record.
-
#
-
# Note that <tt>:dependent</tt> is implemented using Rails' callback
-
# system, which works by processing callbacks in order. Therefore, other
-
# callbacks declared either before or after the <tt>:dependent</tt> option
-
# can affect what it does.
-
#
-
# === Delete or destroy?
-
#
-
# +has_many+ and +has_and_belongs_to_many+ associations have the methods <tt>destroy</tt>,
-
# <tt>delete</tt>, <tt>destroy_all</tt> and <tt>delete_all</tt>.
-
#
-
# For +has_and_belongs_to_many+, <tt>delete</tt> and <tt>destroy</tt> are the same: they
-
# cause the records in the join table to be removed.
-
#
-
# For +has_many+, <tt>destroy</tt> and <tt>destroy_all</tt> will always call the <tt>destroy</tt> method of the
-
# record(s) being removed so that callbacks are run. However <tt>delete</tt> and <tt>delete_all</tt> will either
-
# do the deletion according to the strategy specified by the <tt>:dependent</tt> option, or
-
# if no <tt>:dependent</tt> option is given, then it will follow the default strategy.
-
# The default strategy is <tt>:nullify</tt> (set the foreign keys to <tt>nil</tt>), except for
-
# +has_many+ <tt>:through</tt>, where the default strategy is <tt>delete_all</tt> (delete
-
# the join records, without running their callbacks).
-
#
-
# There is also a <tt>clear</tt> method which is the same as <tt>delete_all</tt>, except that
-
# it returns the association rather than the records which have been deleted.
-
#
-
# === What gets deleted?
-
#
-
# There is a potential pitfall here: +has_and_belongs_to_many+ and +has_many+ <tt>:through</tt>
-
# associations have records in join tables, as well as the associated records. So when we
-
# call one of these deletion methods, what exactly should be deleted?
-
#
-
# The answer is that it is assumed that deletion on an association is about removing the
-
# <i>link</i> between the owner and the associated object(s), rather than necessarily the
-
# associated objects themselves. So with +has_and_belongs_to_many+ and +has_many+
-
# <tt>:through</tt>, the join records will be deleted, but the associated records won't.
-
#
-
# This makes sense if you think about it: if you were to call <tt>post.tags.delete(Tag.find_by(name: 'food'))</tt>
-
# you would want the 'food' tag to be unlinked from the post, rather than for the tag itself
-
# to be removed from the database.
-
#
-
# However, there are examples where this strategy doesn't make sense. For example, suppose
-
# a person has many projects, and each project has many tasks. If we deleted one of a person's
-
# tasks, we would probably not want the project to be deleted. In this scenario, the delete method
-
# won't actually work: it can only be used if the association on the join model is a
-
# +belongs_to+. In other situations you are expected to perform operations directly on
-
# either the associated records or the <tt>:through</tt> association.
-
#
-
# With a regular +has_many+ there is no distinction between the "associated records"
-
# and the "link", so there is only one choice for what gets deleted.
-
#
-
# With +has_and_belongs_to_many+ and +has_many+ <tt>:through</tt>, if you want to delete the
-
# associated records themselves, you can always do something along the lines of
-
# <tt>person.tasks.each(&:destroy)</tt>.
-
#
-
# == Type safety with <tt>ActiveRecord::AssociationTypeMismatch</tt>
-
#
-
# If you attempt to assign an object to an association that doesn't match the inferred
-
# or specified <tt>:class_name</tt>, you'll get an <tt>ActiveRecord::AssociationTypeMismatch</tt>.
-
#
-
# == Options
-
#
-
# All of the association macros can be specialized through options. This makes cases
-
# more complex than the simple and guessable ones possible.
-
1
module ClassMethods
-
# Specifies a one-to-many association. The following methods for retrieval and query of
-
# collections of associated objects will be added:
-
#
-
# [collection(force_reload = false)]
-
# Returns an array of all the associated objects.
-
# An empty array is returned if none are found.
-
# [collection<<(object, ...)]
-
# Adds one or more objects to the collection by setting their foreign keys to the collection's primary key.
-
# Note that this operation instantly fires update SQL without waiting for the save or update call on the
-
# parent object, unless the parent object is a new record.
-
# [collection.delete(object, ...)]
-
# Removes one or more objects from the collection by setting their foreign keys to +NULL+.
-
# Objects will be in addition destroyed if they're associated with <tt>dependent: :destroy</tt>,
-
# and deleted if they're associated with <tt>dependent: :delete_all</tt>.
-
#
-
# If the <tt>:through</tt> option is used, then the join records are deleted (rather than
-
# nullified) by default, but you can specify <tt>dependent: :destroy</tt> or
-
# <tt>dependent: :nullify</tt> to override this.
-
# [collection.destroy(object, ...)]
-
# Removes one or more objects from the collection by running <tt>destroy</tt> on
-
# each record, regardless of any dependent option, ensuring callbacks are run.
-
#
-
# If the <tt>:through</tt> option is used, then the join records are destroyed
-
# instead, not the objects themselves.
-
# [collection=objects]
-
# Replaces the collections content by deleting and adding objects as appropriate. If the <tt>:through</tt>
-
# option is true callbacks in the join models are triggered except destroy callbacks, since deletion is
-
# direct.
-
# [collection_singular_ids]
-
# Returns an array of the associated objects' ids
-
# [collection_singular_ids=ids]
-
# Replace the collection with the objects identified by the primary keys in +ids+. This
-
# method loads the models and calls <tt>collection=</tt>. See above.
-
# [collection.clear]
-
# Removes every object from the collection. This destroys the associated objects if they
-
# are associated with <tt>dependent: :destroy</tt>, deletes them directly from the
-
# database if <tt>dependent: :delete_all</tt>, otherwise sets their foreign keys to +NULL+.
-
# If the <tt>:through</tt> option is true no destroy callbacks are invoked on the join models.
-
# Join models are directly deleted.
-
# [collection.empty?]
-
# Returns +true+ if there are no associated objects.
-
# [collection.size]
-
# Returns the number of associated objects.
-
# [collection.find(...)]
-
# Finds an associated object according to the same rules as <tt>ActiveRecord::Base.find</tt>.
-
# [collection.exists?(...)]
-
# Checks whether an associated object with the given conditions exists.
-
# Uses the same rules as <tt>ActiveRecord::Base.exists?</tt>.
-
# [collection.build(attributes = {}, ...)]
-
# Returns one or more new objects of the collection type that have been instantiated
-
# with +attributes+ and linked to this object through a foreign key, but have not yet
-
# been saved.
-
# [collection.create(attributes = {})]
-
# Returns a new object of the collection type that has been instantiated
-
# with +attributes+, linked to this object through a foreign key, and that has already
-
# been saved (if it passed the validation). *Note*: This only works if the base model
-
# already exists in the DB, not if it is a new (unsaved) record!
-
# [collection.create!(attributes = {})]
-
# Does the same as <tt>collection.create</tt>, but raises <tt>ActiveRecord::RecordInvalid</tt>
-
# if the record is invalid.
-
#
-
# (*Note*: +collection+ is replaced with the symbol passed as the first argument, so
-
# <tt>has_many :clients</tt> would add among others <tt>clients.empty?</tt>.)
-
#
-
# === Example
-
#
-
# A <tt>Firm</tt> class declares <tt>has_many :clients</tt>, which will add:
-
# * <tt>Firm#clients</tt> (similar to <tt>Client.where(firm_id: id)</tt>)
-
# * <tt>Firm#clients<<</tt>
-
# * <tt>Firm#clients.delete</tt>
-
# * <tt>Firm#clients.destroy</tt>
-
# * <tt>Firm#clients=</tt>
-
# * <tt>Firm#client_ids</tt>
-
# * <tt>Firm#client_ids=</tt>
-
# * <tt>Firm#clients.clear</tt>
-
# * <tt>Firm#clients.empty?</tt> (similar to <tt>firm.clients.size == 0</tt>)
-
# * <tt>Firm#clients.size</tt> (similar to <tt>Client.count "firm_id = #{id}"</tt>)
-
# * <tt>Firm#clients.find</tt> (similar to <tt>Client.where(firm_id: id).find(id)</tt>)
-
# * <tt>Firm#clients.exists?(name: 'ACME')</tt> (similar to <tt>Client.exists?(name: 'ACME', firm_id: firm.id)</tt>)
-
# * <tt>Firm#clients.build</tt> (similar to <tt>Client.new("firm_id" => id)</tt>)
-
# * <tt>Firm#clients.create</tt> (similar to <tt>c = Client.new("firm_id" => id); c.save; c</tt>)
-
# * <tt>Firm#clients.create!</tt> (similar to <tt>c = Client.new("firm_id" => id); c.save!</tt>)
-
# The declaration can also include an options hash to specialize the behavior of the association.
-
#
-
# === Options
-
# [:class_name]
-
# Specify the class name of the association. Use it only if that name can't be inferred
-
# from the association name. So <tt>has_many :products</tt> will by default be linked
-
# to the Product class, but if the real class name is SpecialProduct, you'll have to
-
# specify it with this option.
-
# [:foreign_key]
-
# Specify the foreign key used for the association. By default this is guessed to be the name
-
# of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_many+
-
# association will use "person_id" as the default <tt>:foreign_key</tt>.
-
# [:primary_key]
-
# Specify the method that returns the primary key used for the association. By default this is +id+.
-
# [:dependent]
-
# Controls what happens to the associated objects when
-
# their owner is destroyed. Note that these are implemented as
-
# callbacks, and Rails executes callbacks in order. Therefore, other
-
# similar callbacks may affect the <tt>:dependent</tt> behavior, and the
-
# <tt>:dependent</tt> behavior may affect other callbacks.
-
#
-
# * <tt>:destroy</tt> causes all the associated objects to also be destroyed.
-
# * <tt>:delete_all</tt> causes all the associated objects to be deleted directly from the database (so callbacks will not be executed).
-
# * <tt>:nullify</tt> causes the foreign keys to be set to +NULL+. Callbacks are not executed.
-
# * <tt>:restrict_with_exception</tt> causes an exception to be raised if there are any associated records.
-
# * <tt>:restrict_with_error</tt> causes an error to be added to the owner if there are any associated objects.
-
#
-
# If using with the <tt>:through</tt> option, the association on the join model must be
-
# a +belongs_to+, and the records which get deleted are the join records, rather than
-
# the associated records.
-
# [:counter_cache]
-
# This option can be used to configure a custom named <tt>:counter_cache.</tt> You only need this option,
-
# when you customized the name of your <tt>:counter_cache</tt> on the <tt>belongs_to</tt> association.
-
# [:as]
-
# Specifies a polymorphic interface (See <tt>belongs_to</tt>).
-
# [:through]
-
# Specifies an association through which to perform the query. This can be any other type
-
# of association, including other <tt>:through</tt> associations. Options for <tt>:class_name</tt>,
-
# <tt>:primary_key</tt> and <tt>:foreign_key</tt> are ignored, as the association uses the
-
# source reflection.
-
#
-
# If the association on the join model is a +belongs_to+, the collection can be modified
-
# and the records on the <tt>:through</tt> model will be automatically created and removed
-
# as appropriate. Otherwise, the collection is read-only, so you should manipulate the
-
# <tt>:through</tt> association directly.
-
#
-
# If you are going to modify the association (rather than just read from it), then it is
-
# a good idea to set the <tt>:inverse_of</tt> option on the source association on the
-
# join model. This allows associated records to be built which will automatically create
-
# the appropriate join model records when they are saved. (See the 'Association Join Models'
-
# section above.)
-
# [:source]
-
# Specifies the source association name used by <tt>has_many :through</tt> queries.
-
# Only use it if the name cannot be inferred from the association.
-
# <tt>has_many :subscribers, through: :subscriptions</tt> will look for either <tt>:subscribers</tt> or
-
# <tt>:subscriber</tt> on Subscription, unless a <tt>:source</tt> is given.
-
# [:source_type]
-
# Specifies type of the source association used by <tt>has_many :through</tt> queries where the source
-
# association is a polymorphic +belongs_to+.
-
# [:validate]
-
# If +false+, don't validate the associated objects when saving the parent object. true by default.
-
# [:autosave]
-
# If true, always save the associated objects or destroy them if marked for destruction,
-
# when saving the parent object. If false, never save or destroy the associated objects.
-
# By default, only save associated objects that are new records. This option is implemented as a
-
# +before_save+ callback. Because callbacks are run in the order they are defined, associated objects
-
# may need to be explicitly saved in any user-defined +before_save+ callbacks.
-
#
-
# Note that <tt>accepts_nested_attributes_for</tt> sets <tt>:autosave</tt> to <tt>true</tt>.
-
# [:inverse_of]
-
# Specifies the name of the <tt>belongs_to</tt> association on the associated object
-
# that is the inverse of this <tt>has_many</tt> association. Does not work in combination
-
# with <tt>:through</tt> or <tt>:as</tt> options.
-
# See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
-
#
-
# Option examples:
-
# has_many :comments, -> { order "posted_on" }
-
# has_many :comments, -> { includes :author }
-
# has_many :people, -> { where("deleted = 0").order("name") }, class_name: "Person"
-
# has_many :tracks, -> { order "position" }, dependent: :destroy
-
# has_many :comments, dependent: :nullify
-
# has_many :tags, as: :taggable
-
# has_many :reports, -> { readonly }
-
# has_many :subscribers, through: :subscriptions, source: :user
-
1
def has_many(name, scope = nil, options = {}, &extension)
-
8
reflection = Builder::HasMany.build(self, name, scope, options, &extension)
-
8
Reflection.add_reflection self, name, reflection
-
end
-
-
# Specifies a one-to-one association with another class. This method should only be used
-
# if the other class contains the foreign key. If the current class contains the foreign key,
-
# then you should use +belongs_to+ instead. See also ActiveRecord::Associations::ClassMethods's overview
-
# on when to use +has_one+ and when to use +belongs_to+.
-
#
-
# The following methods for retrieval and query of a single associated object will be added:
-
#
-
# [association(force_reload = false)]
-
# Returns the associated object. +nil+ is returned if none is found.
-
# [association=(associate)]
-
# Assigns the associate object, extracts the primary key, sets it as the foreign key,
-
# and saves the associate object. To avoid database inconsistencies, permanently deletes an existing
-
# associated object when assigning a new one, even if the new one isn't saved to database.
-
# [build_association(attributes = {})]
-
# Returns a new object of the associated type that has been instantiated
-
# with +attributes+ and linked to this object through a foreign key, but has not
-
# yet been saved.
-
# [create_association(attributes = {})]
-
# Returns a new object of the associated type that has been instantiated
-
# with +attributes+, linked to this object through a foreign key, and that
-
# has already been saved (if it passed the validation).
-
# [create_association!(attributes = {})]
-
# Does the same as <tt>create_association</tt>, but raises <tt>ActiveRecord::RecordInvalid</tt>
-
# if the record is invalid.
-
#
-
# (+association+ is replaced with the symbol passed as the first argument, so
-
# <tt>has_one :manager</tt> would add among others <tt>manager.nil?</tt>.)
-
#
-
# === Example
-
#
-
# An Account class declares <tt>has_one :beneficiary</tt>, which will add:
-
# * <tt>Account#beneficiary</tt> (similar to <tt>Beneficiary.where(account_id: id).first</tt>)
-
# * <tt>Account#beneficiary=(beneficiary)</tt> (similar to <tt>beneficiary.account_id = account.id; beneficiary.save</tt>)
-
# * <tt>Account#build_beneficiary</tt> (similar to <tt>Beneficiary.new("account_id" => id)</tt>)
-
# * <tt>Account#create_beneficiary</tt> (similar to <tt>b = Beneficiary.new("account_id" => id); b.save; b</tt>)
-
# * <tt>Account#create_beneficiary!</tt> (similar to <tt>b = Beneficiary.new("account_id" => id); b.save!; b</tt>)
-
#
-
# === Options
-
#
-
# The declaration can also include an options hash to specialize the behavior of the association.
-
#
-
# Options are:
-
# [:class_name]
-
# Specify the class name of the association. Use it only if that name can't be inferred
-
# from the association name. So <tt>has_one :manager</tt> will by default be linked to the Manager class, but
-
# if the real class name is Person, you'll have to specify it with this option.
-
# [:dependent]
-
# Controls what happens to the associated object when
-
# its owner is destroyed:
-
#
-
# * <tt>:destroy</tt> causes the associated object to also be destroyed
-
# * <tt>:delete</tt> causes the associated object to be deleted directly from the database (so callbacks will not execute)
-
# * <tt>:nullify</tt> causes the foreign key to be set to +NULL+. Callbacks are not executed.
-
# * <tt>:restrict_with_exception</tt> causes an exception to be raised if there is an associated record
-
# * <tt>:restrict_with_error</tt> causes an error to be added to the owner if there is an associated object
-
# [:foreign_key]
-
# Specify the foreign key used for the association. By default this is guessed to be the name
-
# of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_one+ association
-
# will use "person_id" as the default <tt>:foreign_key</tt>.
-
# [:primary_key]
-
# Specify the method that returns the primary key used for the association. By default this is +id+.
-
# [:as]
-
# Specifies a polymorphic interface (See <tt>belongs_to</tt>).
-
# [:through]
-
# Specifies a Join Model through which to perform the query. Options for <tt>:class_name</tt>,
-
# <tt>:primary_key</tt>, and <tt>:foreign_key</tt> are ignored, as the association uses the
-
# source reflection. You can only use a <tt>:through</tt> query through a <tt>has_one</tt>
-
# or <tt>belongs_to</tt> association on the join model.
-
# [:source]
-
# Specifies the source association name used by <tt>has_one :through</tt> queries.
-
# Only use it if the name cannot be inferred from the association.
-
# <tt>has_one :favorite, through: :favorites</tt> will look for a
-
# <tt>:favorite</tt> on Favorite, unless a <tt>:source</tt> is given.
-
# [:source_type]
-
# Specifies type of the source association used by <tt>has_one :through</tt> queries where the source
-
# association is a polymorphic +belongs_to+.
-
# [:validate]
-
# If +false+, don't validate the associated object when saving the parent object. +false+ by default.
-
# [:autosave]
-
# If true, always save the associated object or destroy it if marked for destruction,
-
# when saving the parent object. If false, never save or destroy the associated object.
-
# By default, only save the associated object if it's a new record.
-
#
-
# Note that <tt>accepts_nested_attributes_for</tt> sets <tt>:autosave</tt> to <tt>true</tt>.
-
# [:inverse_of]
-
# Specifies the name of the <tt>belongs_to</tt> association on the associated object
-
# that is the inverse of this <tt>has_one</tt> association. Does not work in combination
-
# with <tt>:through</tt> or <tt>:as</tt> options.
-
# See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
-
#
-
# Option examples:
-
# has_one :credit_card, dependent: :destroy # destroys the associated credit card
-
# has_one :credit_card, dependent: :nullify # updates the associated records foreign
-
# # key value to NULL rather than destroying it
-
# has_one :last_comment, -> { order 'posted_on' }, class_name: "Comment"
-
# has_one :project_manager, -> { where role: 'project_manager' }, class_name: "Person"
-
# has_one :attachment, as: :attachable
-
# has_one :boss, readonly: :true
-
# has_one :club, through: :membership
-
# has_one :primary_address, -> { where primary: true }, through: :addressables, source: :addressable
-
1
def has_one(name, scope = nil, options = {})
-
reflection = Builder::HasOne.build(self, name, scope, options)
-
Reflection.add_reflection self, name, reflection
-
end
-
-
# Specifies a one-to-one association with another class. This method should only be used
-
# if this class contains the foreign key. If the other class contains the foreign key,
-
# then you should use +has_one+ instead. See also ActiveRecord::Associations::ClassMethods's overview
-
# on when to use +has_one+ and when to use +belongs_to+.
-
#
-
# Methods will be added for retrieval and query for a single associated object, for which
-
# this object holds an id:
-
#
-
# [association(force_reload = false)]
-
# Returns the associated object. +nil+ is returned if none is found.
-
# [association=(associate)]
-
# Assigns the associate object, extracts the primary key, and sets it as the foreign key.
-
# [build_association(attributes = {})]
-
# Returns a new object of the associated type that has been instantiated
-
# with +attributes+ and linked to this object through a foreign key, but has not yet been saved.
-
# [create_association(attributes = {})]
-
# Returns a new object of the associated type that has been instantiated
-
# with +attributes+, linked to this object through a foreign key, and that
-
# has already been saved (if it passed the validation).
-
# [create_association!(attributes = {})]
-
# Does the same as <tt>create_association</tt>, but raises <tt>ActiveRecord::RecordInvalid</tt>
-
# if the record is invalid.
-
#
-
# (+association+ is replaced with the symbol passed as the first argument, so
-
# <tt>belongs_to :author</tt> would add among others <tt>author.nil?</tt>.)
-
#
-
# === Example
-
#
-
# A Post class declares <tt>belongs_to :author</tt>, which will add:
-
# * <tt>Post#author</tt> (similar to <tt>Author.find(author_id)</tt>)
-
# * <tt>Post#author=(author)</tt> (similar to <tt>post.author_id = author.id</tt>)
-
# * <tt>Post#build_author</tt> (similar to <tt>post.author = Author.new</tt>)
-
# * <tt>Post#create_author</tt> (similar to <tt>post.author = Author.new; post.author.save; post.author</tt>)
-
# * <tt>Post#create_author!</tt> (similar to <tt>post.author = Author.new; post.author.save!; post.author</tt>)
-
# The declaration can also include an options hash to specialize the behavior of the association.
-
#
-
# === Options
-
#
-
# [:class_name]
-
# Specify the class name of the association. Use it only if that name can't be inferred
-
# from the association name. So <tt>belongs_to :author</tt> will by default be linked to the Author class, but
-
# if the real class name is Person, you'll have to specify it with this option.
-
# [:foreign_key]
-
# Specify the foreign key used for the association. By default this is guessed to be the name
-
# of the association with an "_id" suffix. So a class that defines a <tt>belongs_to :person</tt>
-
# association will use "person_id" as the default <tt>:foreign_key</tt>. Similarly,
-
# <tt>belongs_to :favorite_person, class_name: "Person"</tt> will use a foreign key
-
# of "favorite_person_id".
-
# [:foreign_type]
-
# Specify the column used to store the associated object's type, if this is a polymorphic
-
# association. By default this is guessed to be the name of the association with a "_type"
-
# suffix. So a class that defines a <tt>belongs_to :taggable, polymorphic: true</tt>
-
# association will use "taggable_type" as the default <tt>:foreign_type</tt>.
-
# [:primary_key]
-
# Specify the method that returns the primary key of associated object used for the association.
-
# By default this is id.
-
# [:dependent]
-
# If set to <tt>:destroy</tt>, the associated object is destroyed when this object is. If set to
-
# <tt>:delete</tt>, the associated object is deleted *without* calling its destroy method.
-
# This option should not be specified when <tt>belongs_to</tt> is used in conjunction with
-
# a <tt>has_many</tt> relationship on another class because of the potential to leave
-
# orphaned records behind.
-
# [:counter_cache]
-
# Caches the number of belonging objects on the associate class through the use of +increment_counter+
-
# and +decrement_counter+. The counter cache is incremented when an object of this
-
# class is created and decremented when it's destroyed. This requires that a column
-
# named <tt>#{table_name}_count</tt> (such as +comments_count+ for a belonging Comment class)
-
# is used on the associate class (such as a Post class) - that is the migration for
-
# <tt>#{table_name}_count</tt> is created on the associate class (such that <tt>Post.comments_count</tt> will
-
# return the count cached, see note below). You can also specify a custom counter
-
# cache column by providing a column name instead of a +true+/+false+ value to this
-
# option (e.g., <tt>counter_cache: :my_custom_counter</tt>.)
-
# Note: Specifying a counter cache will add it to that model's list of readonly attributes
-
# using +attr_readonly+.
-
# [:polymorphic]
-
# Specify this association is a polymorphic association by passing +true+.
-
# Note: If you've enabled the counter cache, then you may want to add the counter cache attribute
-
# to the +attr_readonly+ list in the associated classes (e.g. <tt>class Post; attr_readonly :comments_count; end</tt>).
-
# [:validate]
-
# If +false+, don't validate the associated objects when saving the parent object. +false+ by default.
-
# [:autosave]
-
# If true, always save the associated object or destroy it if marked for destruction, when
-
# saving the parent object.
-
# If false, never save or destroy the associated object.
-
# By default, only save the associated object if it's a new record.
-
#
-
# Note that <tt>accepts_nested_attributes_for</tt> sets <tt>:autosave</tt> to <tt>true</tt>.
-
# [:touch]
-
# If true, the associated object will be touched (the updated_at/on attributes set to now)
-
# when this record is either saved or destroyed. If you specify a symbol, that attribute
-
# will be updated with the current time in addition to the updated_at/on attribute.
-
# [:inverse_of]
-
# Specifies the name of the <tt>has_one</tt> or <tt>has_many</tt> association on the associated
-
# object that is the inverse of this <tt>belongs_to</tt> association. Does not work in
-
# combination with the <tt>:polymorphic</tt> options.
-
# See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
-
#
-
# Option examples:
-
# belongs_to :firm, foreign_key: "client_of"
-
# belongs_to :person, primary_key: "name", foreign_key: "person_name"
-
# belongs_to :author, class_name: "Person", foreign_key: "author_id"
-
# belongs_to :valid_coupon, ->(o) { where "discounts > #{o.payments_count}" },
-
# class_name: "Coupon", foreign_key: "coupon_id"
-
# belongs_to :attachable, polymorphic: true
-
# belongs_to :project, readonly: true
-
# belongs_to :post, counter_cache: true
-
# belongs_to :company, touch: true
-
# belongs_to :company, touch: :employees_last_updated_at
-
1
def belongs_to(name, scope = nil, options = {})
-
reflection = Builder::BelongsTo.build(self, name, scope, options)
-
Reflection.add_reflection self, name, reflection
-
end
-
-
# Specifies a many-to-many relationship with another class. This associates two classes via an
-
# intermediate join table. Unless the join table is explicitly specified as an option, it is
-
# guessed using the lexical order of the class names. So a join between Developer and Project
-
# will give the default join table name of "developers_projects" because "D" precedes "P" alphabetically.
-
# Note that this precedence is calculated using the <tt><</tt> operator for String. This
-
# means that if the strings are of different lengths, and the strings are equal when compared
-
# up to the shortest length, then the longer string is considered of higher
-
# lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers"
-
# to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes",
-
# but it in fact generates a join table name of "paper_boxes_papers". Be aware of this caveat, and use the
-
# custom <tt>:join_table</tt> option if you need to.
-
# If your tables share a common prefix, it will only appear once at the beginning. For example,
-
# the tables "catalog_categories" and "catalog_products" generate a join table name of "catalog_categories_products".
-
#
-
# The join table should not have a primary key or a model associated with it. You must manually generate the
-
# join table with a migration such as this:
-
#
-
# class CreateDevelopersProjectsJoinTable < ActiveRecord::Migration
-
# def change
-
# create_table :developers_projects, id: false do |t|
-
# t.integer :developer_id
-
# t.integer :project_id
-
# end
-
# end
-
# end
-
#
-
# It's also a good idea to add indexes to each of those columns to speed up the joins process.
-
# However, in MySQL it is advised to add a compound index for both of the columns as MySQL only
-
# uses one index per table during the lookup.
-
#
-
# Adds the following methods for retrieval and query:
-
#
-
# [collection(force_reload = false)]
-
# Returns an array of all the associated objects.
-
# An empty array is returned if none are found.
-
# [collection<<(object, ...)]
-
# Adds one or more objects to the collection by creating associations in the join table
-
# (<tt>collection.push</tt> and <tt>collection.concat</tt> are aliases to this method).
-
# Note that this operation instantly fires update SQL without waiting for the save or update call on the
-
# parent object, unless the parent object is a new record.
-
# [collection.delete(object, ...)]
-
# Removes one or more objects from the collection by removing their associations from the join table.
-
# This does not destroy the objects.
-
# [collection.destroy(object, ...)]
-
# Removes one or more objects from the collection by running destroy on each association in the join table, overriding any dependent option.
-
# This does not destroy the objects.
-
# [collection=objects]
-
# Replaces the collection's content by deleting and adding objects as appropriate.
-
# [collection_singular_ids]
-
# Returns an array of the associated objects' ids.
-
# [collection_singular_ids=ids]
-
# Replace the collection by the objects identified by the primary keys in +ids+.
-
# [collection.clear]
-
# Removes every object from the collection. This does not destroy the objects.
-
# [collection.empty?]
-
# Returns +true+ if there are no associated objects.
-
# [collection.size]
-
# Returns the number of associated objects.
-
# [collection.find(id)]
-
# Finds an associated object responding to the +id+ and that
-
# meets the condition that it has to be associated with this object.
-
# Uses the same rules as <tt>ActiveRecord::Base.find</tt>.
-
# [collection.exists?(...)]
-
# Checks whether an associated object with the given conditions exists.
-
# Uses the same rules as <tt>ActiveRecord::Base.exists?</tt>.
-
# [collection.build(attributes = {})]
-
# Returns a new object of the collection type that has been instantiated
-
# with +attributes+ and linked to this object through the join table, but has not yet been saved.
-
# [collection.create(attributes = {})]
-
# Returns a new object of the collection type that has been instantiated
-
# with +attributes+, linked to this object through the join table, and that has already been
-
# saved (if it passed the validation).
-
#
-
# (+collection+ is replaced with the symbol passed as the first argument, so
-
# <tt>has_and_belongs_to_many :categories</tt> would add among others <tt>categories.empty?</tt>.)
-
#
-
# === Example
-
#
-
# A Developer class declares <tt>has_and_belongs_to_many :projects</tt>, which will add:
-
# * <tt>Developer#projects</tt>
-
# * <tt>Developer#projects<<</tt>
-
# * <tt>Developer#projects.delete</tt>
-
# * <tt>Developer#projects.destroy</tt>
-
# * <tt>Developer#projects=</tt>
-
# * <tt>Developer#project_ids</tt>
-
# * <tt>Developer#project_ids=</tt>
-
# * <tt>Developer#projects.clear</tt>
-
# * <tt>Developer#projects.empty?</tt>
-
# * <tt>Developer#projects.size</tt>
-
# * <tt>Developer#projects.find(id)</tt>
-
# * <tt>Developer#projects.exists?(...)</tt>
-
# * <tt>Developer#projects.build</tt> (similar to <tt>Project.new("developer_id" => id)</tt>)
-
# * <tt>Developer#projects.create</tt> (similar to <tt>c = Project.new("developer_id" => id); c.save; c</tt>)
-
# The declaration may include an options hash to specialize the behavior of the association.
-
#
-
# === Options
-
#
-
# [:class_name]
-
# Specify the class name of the association. Use it only if that name can't be inferred
-
# from the association name. So <tt>has_and_belongs_to_many :projects</tt> will by default be linked to the
-
# Project class, but if the real class name is SuperProject, you'll have to specify it with this option.
-
# [:join_table]
-
# Specify the name of the join table if the default based on lexical order isn't what you want.
-
# <b>WARNING:</b> If you're overwriting the table name of either class, the +table_name+ method
-
# MUST be declared underneath any +has_and_belongs_to_many+ declaration in order to work.
-
# [:foreign_key]
-
# Specify the foreign key used for the association. By default this is guessed to be the name
-
# of this class in lower-case and "_id" suffixed. So a Person class that makes
-
# a +has_and_belongs_to_many+ association to Project will use "person_id" as the
-
# default <tt>:foreign_key</tt>.
-
# [:association_foreign_key]
-
# Specify the foreign key used for the association on the receiving side of the association.
-
# By default this is guessed to be the name of the associated class in lower-case and "_id" suffixed.
-
# So if a Person class makes a +has_and_belongs_to_many+ association to Project,
-
# the association will use "project_id" as the default <tt>:association_foreign_key</tt>.
-
# [:readonly]
-
# If true, all the associated objects are readonly through the association.
-
# [:validate]
-
# If +false+, don't validate the associated objects when saving the parent object. +true+ by default.
-
# [:autosave]
-
# If true, always save the associated objects or destroy them if marked for destruction, when
-
# saving the parent object.
-
# If false, never save or destroy the associated objects.
-
# By default, only save associated objects that are new records.
-
#
-
# Note that <tt>accepts_nested_attributes_for</tt> sets <tt>:autosave</tt> to <tt>true</tt>.
-
#
-
# Option examples:
-
# has_and_belongs_to_many :projects
-
# has_and_belongs_to_many :projects, -> { includes :milestones, :manager }
-
# has_and_belongs_to_many :nations, class_name: "Country"
-
# has_and_belongs_to_many :categories, join_table: "prods_cats"
-
# has_and_belongs_to_many :categories, -> { readonly }
-
1
def has_and_belongs_to_many(name, scope = nil, options = {}, &extension)
-
if scope.is_a?(Hash)
-
options = scope
-
scope = nil
-
end
-
-
builder = Builder::HasAndBelongsToMany.new name, self, options
-
-
join_model = builder.through_model
-
-
middle_reflection = builder.middle_reflection join_model
-
-
Builder::HasMany.define_callbacks self, middle_reflection
-
Reflection.add_reflection self, middle_reflection.name, middle_reflection
-
-
include Module.new {
-
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def destroy_associations
-
association(:#{middle_reflection.name}).delete_all(:delete_all)
-
association(:#{name}).reset
-
super
-
end
-
RUBY
-
}
-
-
hm_options = {}
-
hm_options[:through] = middle_reflection.name
-
hm_options[:source] = join_model.right_reflection.name
-
-
[:before_add, :after_add, :before_remove, :after_remove, :autosave, :validate].each do |k|
-
hm_options[k] = options[k] if options.key? k
-
end
-
-
has_many name, scope, hm_options, &extension
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
-
# This is the parent Association class which defines the variables
-
# used by all associations.
-
#
-
# The hierarchy is defined as follows:
-
# Association
-
# - SingularAssociation
-
# - BelongsToAssociation
-
# - HasOneAssociation
-
# - CollectionAssociation
-
# - HasManyAssociation
-
-
1
module ActiveRecord::Associations::Builder
-
1
class Association #:nodoc:
-
1
class << self
-
1
attr_accessor :extensions
-
# TODO: This class accessor is needed to make activerecord-deprecated_finders work.
-
# We can move it to a constant in 5.0.
-
1
attr_accessor :valid_options
-
end
-
1
self.extensions = []
-
-
1
self.valid_options = [:class_name, :class, :foreign_key, :validate]
-
-
1
attr_reader :name, :scope, :options
-
-
1
def self.build(model, name, scope, options, &block)
-
8
if model.dangerous_attribute_method?(name)
-
raise ArgumentError, "You tried to define an association named #{name} on the model #{model.name}, but " \
-
"this will conflict with a method #{name} already defined by Active Record. " \
-
"Please choose a different association name."
-
end
-
-
8
builder = create_builder model, name, scope, options, &block
-
8
reflection = builder.build(model)
-
8
define_accessors model, reflection
-
8
define_callbacks model, reflection
-
8
builder.define_extensions model
-
8
reflection
-
end
-
-
1
def self.create_builder(model, name, scope, options, &block)
-
8
raise ArgumentError, "association names must be a Symbol" unless name.kind_of?(Symbol)
-
-
8
new(model, name, scope, options, &block)
-
end
-
-
1
def initialize(model, name, scope, options)
-
# TODO: Move this to create_builder as soon we drop support to activerecord-deprecated_finders.
-
8
if scope.is_a?(Hash)
-
1
options = scope
-
1
scope = nil
-
end
-
-
# TODO: Remove this model argument as soon we drop support to activerecord-deprecated_finders.
-
8
@name = name
-
8
@scope = scope
-
8
@options = options
-
-
8
validate_options
-
-
8
if scope && scope.arity == 0
-
@scope = proc { instance_exec(&scope) }
-
end
-
end
-
-
1
def build(model)
-
8
ActiveRecord::Reflection.create(macro, name, scope, options, model)
-
end
-
-
1
def macro
-
raise NotImplementedError
-
end
-
-
1
def valid_options
-
8
Association.valid_options + Association.extensions.flat_map(&:valid_options)
-
end
-
-
1
def validate_options
-
8
options.assert_valid_keys(valid_options)
-
end
-
-
1
def define_extensions(model)
-
end
-
-
1
def self.define_callbacks(model, reflection)
-
8
add_before_destroy_callbacks(model, reflection) if reflection.options[:dependent]
-
8
Association.extensions.each do |extension|
-
8
extension.build model, reflection
-
end
-
end
-
-
# Defines the setter and getter methods for the association
-
# class Post < ActiveRecord::Base
-
# has_many :comments
-
# end
-
#
-
# Post.first.comments and Post.first.comments= methods are defined by this method...
-
1
def self.define_accessors(model, reflection)
-
8
mixin = model.generated_association_methods
-
8
name = reflection.name
-
8
define_readers(mixin, name)
-
8
define_writers(mixin, name)
-
end
-
-
1
def self.define_readers(mixin, name)
-
8
mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{name}(*args)
-
association(:#{name}).reader(*args)
-
end
-
CODE
-
end
-
-
1
def self.define_writers(mixin, name)
-
8
mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{name}=(value)
-
association(:#{name}).writer(value)
-
end
-
CODE
-
end
-
-
1
def self.valid_dependent_options
-
raise NotImplementedError
-
end
-
-
1
private
-
-
1
def self.add_before_destroy_callbacks(model, reflection)
-
unless valid_dependent_options.include? reflection.options[:dependent]
-
raise ArgumentError, "The :dependent option must be one of #{valid_dependent_options}, but is :#{reflection.options[:dependent]}"
-
end
-
-
name = reflection.name
-
model.before_destroy lambda { |o| o.association(name).handle_dependency }
-
end
-
end
-
end
-
# This class is inherited by the has_many and has_many_and_belongs_to_many association classes
-
-
1
require 'active_record/associations'
-
-
1
module ActiveRecord::Associations::Builder
-
1
class CollectionAssociation < Association #:nodoc:
-
-
1
CALLBACKS = [:before_add, :after_add, :before_remove, :after_remove]
-
-
1
def valid_options
-
super + [:table_name, :before_add,
-
8
:after_add, :before_remove, :after_remove, :extend]
-
end
-
-
1
attr_reader :block_extension
-
-
1
def initialize(model, name, scope, options)
-
8
super
-
8
@mod = nil
-
8
if block_given?
-
@mod = Module.new(&Proc.new)
-
@scope = wrap_scope @scope, @mod
-
end
-
end
-
-
1
def self.define_callbacks(model, reflection)
-
8
super
-
8
name = reflection.name
-
8
options = reflection.options
-
8
CALLBACKS.each { |callback_name|
-
32
define_callback(model, callback_name, name, options)
-
}
-
end
-
-
1
def define_extensions(model)
-
8
if @mod
-
extension_module_name = "#{model.name.demodulize}#{name.to_s.camelize}AssociationExtension"
-
model.parent.const_set(extension_module_name, @mod)
-
end
-
end
-
-
1
def self.define_callback(model, callback_name, name, options)
-
32
full_callback_name = "#{callback_name}_for_#{name}"
-
-
# TODO : why do i need method_defined? I think its because of the inheritance chain
-
32
model.class_attribute full_callback_name unless model.method_defined?(full_callback_name)
-
32
callbacks = Array(options[callback_name.to_sym]).map do |callback|
-
case callback
-
when Symbol
-
->(method, owner, record) { owner.send(callback, record) }
-
when Proc
-
->(method, owner, record) { callback.call(owner, record) }
-
else
-
->(method, owner, record) { callback.send(method, owner, record) }
-
end
-
end
-
32
model.send "#{full_callback_name}=", callbacks
-
end
-
-
# Defines the setter and getter methods for the collection_singular_ids.
-
1
def self.define_readers(mixin, name)
-
8
super
-
-
8
mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{name.to_s.singularize}_ids
-
association(:#{name}).ids_reader
-
end
-
CODE
-
end
-
-
1
def self.define_writers(mixin, name)
-
8
super
-
-
8
mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{name.to_s.singularize}_ids=(ids)
-
association(:#{name}).ids_writer(ids)
-
end
-
CODE
-
end
-
-
1
private
-
-
1
def wrap_scope(scope, mod)
-
if scope
-
proc { |owner| instance_exec(owner, &scope).extending(mod) }
-
else
-
proc { extending(mod) }
-
end
-
end
-
end
-
end
-
1
module ActiveRecord::Associations::Builder
-
1
class HasMany < CollectionAssociation #:nodoc:
-
1
def macro
-
8
:has_many
-
end
-
-
1
def valid_options
-
8
super + [:primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of, :counter_cache]
-
end
-
-
1
def self.valid_dependent_options
-
[:destroy, :delete_all, :nullify, :restrict_with_error, :restrict_with_exception]
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Associations
-
# Association proxies in Active Record are middlemen between the object that
-
# holds the association, known as the <tt>@owner</tt>, and the actual associated
-
# object, known as the <tt>@target</tt>. The kind of association any proxy is
-
# about is available in <tt>@reflection</tt>. That's an instance of the class
-
# ActiveRecord::Reflection::AssociationReflection.
-
#
-
# For example, given
-
#
-
# class Blog < ActiveRecord::Base
-
# has_many :posts
-
# end
-
#
-
# blog = Blog.first
-
#
-
# the association proxy in <tt>blog.posts</tt> has the object in +blog+ as
-
# <tt>@owner</tt>, the collection of its posts as <tt>@target</tt>, and
-
# the <tt>@reflection</tt> object represents a <tt>:has_many</tt> macro.
-
#
-
# This class delegates unknown methods to <tt>@target</tt> via
-
# <tt>method_missing</tt>.
-
#
-
# The <tt>@target</tt> object is not \loaded until needed. For example,
-
#
-
# blog.posts.count
-
#
-
# is computed directly through SQL and does not trigger by itself the
-
# instantiation of the actual post records.
-
1
class CollectionProxy < Relation
-
1
delegate(*(ActiveRecord::Calculations.public_instance_methods - [:count]), to: :scope)
-
-
1
def initialize(klass, association) #:nodoc:
-
@association = association
-
super klass, klass.arel_table
-
merge! association.scope(nullify: false)
-
end
-
-
1
def target
-
@association.target
-
end
-
-
1
def load_target
-
@association.load_target
-
end
-
-
# Returns +true+ if the association has been loaded, otherwise +false+.
-
#
-
# person.pets.loaded? # => false
-
# person.pets
-
# person.pets.loaded? # => true
-
1
def loaded?
-
@association.loaded?
-
end
-
-
# Works in two ways.
-
#
-
# *First:* Specify a subset of fields to be selected from the result set.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.select(:name)
-
# # => [
-
# # #<Pet id: nil, name: "Fancy-Fancy">,
-
# # #<Pet id: nil, name: "Spook">,
-
# # #<Pet id: nil, name: "Choo-Choo">
-
# # ]
-
#
-
# person.pets.select(:id, :name )
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy">,
-
# # #<Pet id: 2, name: "Spook">,
-
# # #<Pet id: 3, name: "Choo-Choo">
-
# # ]
-
#
-
# Be careful because this also means you're initializing a model
-
# object with only the fields that you've selected. If you attempt
-
# to access a field except +id+ that is not in the initialized record you'll
-
# receive:
-
#
-
# person.pets.select(:name).first.person_id
-
# # => ActiveModel::MissingAttributeError: missing attribute: person_id
-
#
-
# *Second:* You can pass a block so it can be used just like Array#select.
-
# This builds an array of objects from the database for the scope,
-
# converting them into an array and iterating through them using
-
# Array#select.
-
#
-
# person.pets.select { |pet| pet.name =~ /oo/ }
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.select(:name) { |pet| pet.name =~ /oo/ }
-
# # => [
-
# # #<Pet id: 2, name: "Spook">,
-
# # #<Pet id: 3, name: "Choo-Choo">
-
# # ]
-
1
def select(*fields, &block)
-
@association.select(*fields, &block)
-
end
-
-
# Finds an object in the collection responding to the +id+. Uses the same
-
# rules as <tt>ActiveRecord::Base.find</tt>. Returns <tt>ActiveRecord::RecordNotFound</tt>
-
# error if the object cannot be found.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.find(1) # => #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>
-
# person.pets.find(4) # => ActiveRecord::RecordNotFound: Couldn't find Pet with id=4
-
#
-
# person.pets.find(2) { |pet| pet.name.downcase! }
-
# # => #<Pet id: 2, name: "fancy-fancy", person_id: 1>
-
#
-
# person.pets.find(2, 3)
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
1
def find(*args, &block)
-
@association.find(*args, &block)
-
end
-
-
# Returns the first record, or the first +n+ records, from the collection.
-
# If the collection is empty, the first form returns +nil+, and the second
-
# form returns an empty array.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.first # => #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>
-
#
-
# person.pets.first(2)
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>
-
# # ]
-
#
-
# another_person_without.pets # => []
-
# another_person_without.pets.first # => nil
-
# another_person_without.pets.first(3) # => []
-
1
def first(*args)
-
@association.first(*args)
-
end
-
-
# Same as +first+ except returns only the second record.
-
1
def second(*args)
-
@association.second(*args)
-
end
-
-
# Same as +first+ except returns only the third record.
-
1
def third(*args)
-
@association.third(*args)
-
end
-
-
# Same as +first+ except returns only the fourth record.
-
1
def fourth(*args)
-
@association.fourth(*args)
-
end
-
-
# Same as +first+ except returns only the fifth record.
-
1
def fifth(*args)
-
@association.fifth(*args)
-
end
-
-
# Same as +first+ except returns only the forty second record.
-
# Also known as accessing "the reddit".
-
1
def forty_two(*args)
-
@association.forty_two(*args)
-
end
-
-
# Returns the last record, or the last +n+ records, from the collection.
-
# If the collection is empty, the first form returns +nil+, and the second
-
# form returns an empty array.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.last # => #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
#
-
# person.pets.last(2)
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# another_person_without.pets # => []
-
# another_person_without.pets.last # => nil
-
# another_person_without.pets.last(3) # => []
-
1
def last(*args)
-
@association.last(*args)
-
end
-
-
# Returns a new object of the collection type that has been instantiated
-
# with +attributes+ and linked to this object, but have not yet been saved.
-
# You can pass an array of attributes hashes, this will return an array
-
# with the new objects.
-
#
-
# class Person
-
# has_many :pets
-
# end
-
#
-
# person.pets.build
-
# # => #<Pet id: nil, name: nil, person_id: 1>
-
#
-
# person.pets.build(name: 'Fancy-Fancy')
-
# # => #<Pet id: nil, name: "Fancy-Fancy", person_id: 1>
-
#
-
# person.pets.build([{name: 'Spook'}, {name: 'Choo-Choo'}, {name: 'Brain'}])
-
# # => [
-
# # #<Pet id: nil, name: "Spook", person_id: 1>,
-
# # #<Pet id: nil, name: "Choo-Choo", person_id: 1>,
-
# # #<Pet id: nil, name: "Brain", person_id: 1>
-
# # ]
-
#
-
# person.pets.size # => 5 # size of the collection
-
# person.pets.count # => 0 # count from database
-
1
def build(attributes = {}, &block)
-
@association.build(attributes, &block)
-
end
-
1
alias_method :new, :build
-
-
# Returns a new object of the collection type that has been instantiated with
-
# attributes, linked to this object and that has already been saved (if it
-
# passes the validations).
-
#
-
# class Person
-
# has_many :pets
-
# end
-
#
-
# person.pets.create(name: 'Fancy-Fancy')
-
# # => #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>
-
#
-
# person.pets.create([{name: 'Spook'}, {name: 'Choo-Choo'}])
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.size # => 3
-
# person.pets.count # => 3
-
#
-
# person.pets.find(1, 2, 3)
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
1
def create(attributes = {}, &block)
-
@association.create(attributes, &block)
-
end
-
-
# Like +create+, except that if the record is invalid, raises an exception.
-
#
-
# class Person
-
# has_many :pets
-
# end
-
#
-
# class Pet
-
# validates :name, presence: true
-
# end
-
#
-
# person.pets.create!(name: nil)
-
# # => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
-
1
def create!(attributes = {}, &block)
-
@association.create!(attributes, &block)
-
end
-
-
# Add one or more records to the collection by setting their foreign keys
-
# to the association's primary key. Since << flattens its argument list and
-
# inserts each record, +push+ and +concat+ behave identically. Returns +self+
-
# so method calls may be chained.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.size # => 0
-
# person.pets.concat(Pet.new(name: 'Fancy-Fancy'))
-
# person.pets.concat(Pet.new(name: 'Spook'), Pet.new(name: 'Choo-Choo'))
-
# person.pets.size # => 3
-
#
-
# person.id # => 1
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.concat([Pet.new(name: 'Brain'), Pet.new(name: 'Benny')])
-
# person.pets.size # => 5
-
1
def concat(*records)
-
@association.concat(*records)
-
end
-
-
# Replaces this collection with +other_array+. This will perform a diff
-
# and delete/add only records that have changed.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets
-
# # => [#<Pet id: 1, name: "Gorby", group: "cats", person_id: 1>]
-
#
-
# other_pets = [Pet.new(name: 'Puff', group: 'celebrities']
-
#
-
# person.pets.replace(other_pets)
-
#
-
# person.pets
-
# # => [#<Pet id: 2, name: "Puff", group: "celebrities", person_id: 1>]
-
#
-
# If the supplied array has an incorrect association type, it raises
-
# an <tt>ActiveRecord::AssociationTypeMismatch</tt> error:
-
#
-
# person.pets.replace(["doo", "ggie", "gaga"])
-
# # => ActiveRecord::AssociationTypeMismatch: Pet expected, got String
-
1
def replace(other_array)
-
@association.replace(other_array)
-
end
-
-
# Deletes all the records from the collection. For +has_many+ associations,
-
# the deletion is done according to the strategy specified by the <tt>:dependent</tt>
-
# option. Returns an array with the deleted records.
-
#
-
# If no <tt>:dependent</tt> option is given, then it will follow the
-
# default strategy. The default strategy is <tt>:nullify</tt>. This
-
# sets the foreign keys to <tt>NULL</tt>. For, +has_many+ <tt>:through</tt>,
-
# the default strategy is +delete_all+.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets # dependent: :nullify option by default
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.delete_all
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.size # => 0
-
# person.pets # => []
-
#
-
# Pet.find(1, 2, 3)
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: nil>,
-
# # #<Pet id: 2, name: "Spook", person_id: nil>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: nil>
-
# # ]
-
#
-
# If it is set to <tt>:destroy</tt> all the objects from the collection
-
# are removed by calling their +destroy+ method. See +destroy+ for more
-
# information.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets, dependent: :destroy
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.delete_all
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# Pet.find(1, 2, 3)
-
# # => ActiveRecord::RecordNotFound
-
#
-
# If it is set to <tt>:delete_all</tt>, all the objects are deleted
-
# *without* calling their +destroy+ method.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets, dependent: :delete_all
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.delete_all
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# Pet.find(1, 2, 3)
-
# # => ActiveRecord::RecordNotFound
-
1
def delete_all(dependent = nil)
-
@association.delete_all(dependent)
-
end
-
-
# Deletes the records of the collection directly from the database
-
# ignoring the +:dependent+ option. It invokes +before_remove+,
-
# +after_remove+ , +before_destroy+ and +after_destroy+ callbacks.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.destroy_all
-
#
-
# person.pets.size # => 0
-
# person.pets # => []
-
#
-
# Pet.find(1) # => Couldn't find Pet with id=1
-
1
def destroy_all
-
@association.destroy_all
-
end
-
-
# Deletes the +records+ supplied and removes them from the collection. For
-
# +has_many+ associations, the deletion is done according to the strategy
-
# specified by the <tt>:dependent</tt> option. Returns an array with the
-
# deleted records.
-
#
-
# If no <tt>:dependent</tt> option is given, then it will follow the default
-
# strategy. The default strategy is <tt>:nullify</tt>. This sets the foreign
-
# keys to <tt>NULL</tt>. For, +has_many+ <tt>:through</tt>, the default
-
# strategy is +delete_all+.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets # dependent: :nullify option by default
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.delete(Pet.find(1))
-
# # => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]
-
#
-
# person.pets.size # => 2
-
# person.pets
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# Pet.find(1)
-
# # => #<Pet id: 1, name: "Fancy-Fancy", person_id: nil>
-
#
-
# If it is set to <tt>:destroy</tt> all the +records+ are removed by calling
-
# their +destroy+ method. See +destroy+ for more information.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets, dependent: :destroy
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.delete(Pet.find(1), Pet.find(3))
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.size # => 1
-
# person.pets
-
# # => [#<Pet id: 2, name: "Spook", person_id: 1>]
-
#
-
# Pet.find(1, 3)
-
# # => ActiveRecord::RecordNotFound: Couldn't find all Pets with IDs (1, 3)
-
#
-
# If it is set to <tt>:delete_all</tt>, all the +records+ are deleted
-
# *without* calling their +destroy+ method.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets, dependent: :delete_all
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.delete(Pet.find(1))
-
# # => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]
-
#
-
# person.pets.size # => 2
-
# person.pets
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# Pet.find(1)
-
# # => ActiveRecord::RecordNotFound: Couldn't find Pet with id=1
-
#
-
# You can pass +Fixnum+ or +String+ values, it finds the records
-
# responding to the +id+ and executes delete on them.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.delete("1")
-
# # => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]
-
#
-
# person.pets.delete(2, 3)
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
1
def delete(*records)
-
@association.delete(*records)
-
end
-
-
# Destroys the +records+ supplied and removes them from the collection.
-
# This method will _always_ remove record from the database ignoring
-
# the +:dependent+ option. Returns an array with the removed records.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.destroy(Pet.find(1))
-
# # => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]
-
#
-
# person.pets.size # => 2
-
# person.pets
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.destroy(Pet.find(2), Pet.find(3))
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.size # => 0
-
# person.pets # => []
-
#
-
# Pet.find(1, 2, 3) # => ActiveRecord::RecordNotFound: Couldn't find all Pets with IDs (1, 2, 3)
-
#
-
# You can pass +Fixnum+ or +String+ values, it finds the records
-
# responding to the +id+ and then deletes them from the database.
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 4, name: "Benny", person_id: 1>,
-
# # #<Pet id: 5, name: "Brain", person_id: 1>,
-
# # #<Pet id: 6, name: "Boss", person_id: 1>
-
# # ]
-
#
-
# person.pets.destroy("4")
-
# # => #<Pet id: 4, name: "Benny", person_id: 1>
-
#
-
# person.pets.size # => 2
-
# person.pets
-
# # => [
-
# # #<Pet id: 5, name: "Brain", person_id: 1>,
-
# # #<Pet id: 6, name: "Boss", person_id: 1>
-
# # ]
-
#
-
# person.pets.destroy(5, 6)
-
# # => [
-
# # #<Pet id: 5, name: "Brain", person_id: 1>,
-
# # #<Pet id: 6, name: "Boss", person_id: 1>
-
# # ]
-
#
-
# person.pets.size # => 0
-
# person.pets # => []
-
#
-
# Pet.find(4, 5, 6) # => ActiveRecord::RecordNotFound: Couldn't find all Pets with IDs (4, 5, 6)
-
1
def destroy(*records)
-
@association.destroy(*records)
-
end
-
-
# Specifies whether the records should be unique or not.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.select(:name)
-
# # => [
-
# # #<Pet name: "Fancy-Fancy">,
-
# # #<Pet name: "Fancy-Fancy">
-
# # ]
-
#
-
# person.pets.select(:name).distinct
-
# # => [#<Pet name: "Fancy-Fancy">]
-
1
def distinct
-
@association.distinct
-
end
-
1
alias uniq distinct
-
-
# Count all records using SQL.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.count # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
1
def count(column_name = nil, options = {})
-
# TODO: Remove options argument as soon we remove support to
-
# activerecord-deprecated_finders.
-
@association.count(column_name, options)
-
end
-
-
# Returns the size of the collection. If the collection hasn't been loaded,
-
# it executes a <tt>SELECT COUNT(*)</tt> query. Else it calls <tt>collection.size</tt>.
-
#
-
# If the collection has been already loaded +size+ and +length+ are
-
# equivalent. If not and you are going to need the records anyway
-
# +length+ will take one less query. Otherwise +size+ is more efficient.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.size # => 3
-
# # executes something like SELECT COUNT(*) FROM "pets" WHERE "pets"."person_id" = 1
-
#
-
# person.pets # This will execute a SELECT * FROM query
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.size # => 3
-
# # Because the collection is already loaded, this will behave like
-
# # collection.size and no SQL count query is executed.
-
1
def size
-
@association.size
-
end
-
-
# Returns the size of the collection calling +size+ on the target.
-
# If the collection has been already loaded, +length+ and +size+ are
-
# equivalent. If not and you are going to need the records anyway this
-
# method will take one less query. Otherwise +size+ is more efficient.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.length # => 3
-
# # executes something like SELECT "pets".* FROM "pets" WHERE "pets"."person_id" = 1
-
#
-
# # Because the collection is loaded, you can
-
# # call the collection with no additional queries:
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
1
def length
-
@association.length
-
end
-
-
# Returns +true+ if the collection is empty. If the collection has been
-
# loaded it is equivalent
-
# to <tt>collection.size.zero?</tt>. If the collection has not been loaded,
-
# it is equivalent to <tt>collection.exists?</tt>. If the collection has
-
# not already been loaded and you are going to fetch the records anyway it
-
# is better to check <tt>collection.length.zero?</tt>.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.count # => 1
-
# person.pets.empty? # => false
-
#
-
# person.pets.delete_all
-
#
-
# person.pets.count # => 0
-
# person.pets.empty? # => true
-
1
def empty?
-
@association.empty?
-
end
-
-
# Returns +true+ if the collection is not empty.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.count # => 0
-
# person.pets.any? # => false
-
#
-
# person.pets << Pet.new(name: 'Snoop')
-
# person.pets.count # => 0
-
# person.pets.any? # => true
-
#
-
# You can also pass a block to define criteria. The behavior
-
# is the same, it returns true if the collection based on the
-
# criteria is not empty.
-
#
-
# person.pets
-
# # => [#<Pet name: "Snoop", group: "dogs">]
-
#
-
# person.pets.any? do |pet|
-
# pet.group == 'cats'
-
# end
-
# # => false
-
#
-
# person.pets.any? do |pet|
-
# pet.group == 'dogs'
-
# end
-
# # => true
-
1
def any?(&block)
-
@association.any?(&block)
-
end
-
-
# Returns true if the collection has more than one record.
-
# Equivalent to <tt>collection.size > 1</tt>.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.count # => 1
-
# person.pets.many? # => false
-
#
-
# person.pets << Pet.new(name: 'Snoopy')
-
# person.pets.count # => 2
-
# person.pets.many? # => true
-
#
-
# You can also pass a block to define criteria. The
-
# behavior is the same, it returns true if the collection
-
# based on the criteria has more than one record.
-
#
-
# person.pets
-
# # => [
-
# # #<Pet name: "Gorby", group: "cats">,
-
# # #<Pet name: "Puff", group: "cats">,
-
# # #<Pet name: "Snoop", group: "dogs">
-
# # ]
-
#
-
# person.pets.many? do |pet|
-
# pet.group == 'dogs'
-
# end
-
# # => false
-
#
-
# person.pets.many? do |pet|
-
# pet.group == 'cats'
-
# end
-
# # => true
-
1
def many?(&block)
-
@association.many?(&block)
-
end
-
-
# Returns +true+ if the given object is present in the collection.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets # => [#<Pet id: 20, name: "Snoop">]
-
#
-
# person.pets.include?(Pet.find(20)) # => true
-
# person.pets.include?(Pet.find(21)) # => false
-
1
def include?(record)
-
!!@association.include?(record)
-
end
-
-
1
def proxy_association
-
@association
-
end
-
-
# We don't want this object to be put on the scoping stack, because
-
# that could create an infinite loop where we call an @association
-
# method, which gets the current scope, which is this object, which
-
# delegates to @association, and so on.
-
1
def scoping
-
@association.scope.scoping { yield }
-
end
-
-
# Returns a <tt>Relation</tt> object for the records in this association
-
1
def scope
-
@association.scope
-
end
-
1
alias spawn scope
-
-
# Equivalent to <tt>Array#==</tt>. Returns +true+ if the two arrays
-
# contain the same number of elements and if each element is equal
-
# to the corresponding element in the other array, otherwise returns
-
# +false+.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>
-
# # ]
-
#
-
# other = person.pets.to_ary
-
#
-
# person.pets == other
-
# # => true
-
#
-
# other = [Pet.new(id: 1), Pet.new(id: 2)]
-
#
-
# person.pets == other
-
# # => false
-
1
def ==(other)
-
load_target == other
-
end
-
-
# Returns a new array of objects from the collection. If the collection
-
# hasn't been loaded, it fetches the records from the database.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets
-
# # => [
-
# # #<Pet id: 4, name: "Benny", person_id: 1>,
-
# # #<Pet id: 5, name: "Brain", person_id: 1>,
-
# # #<Pet id: 6, name: "Boss", person_id: 1>
-
# # ]
-
#
-
# other_pets = person.pets.to_ary
-
# # => [
-
# # #<Pet id: 4, name: "Benny", person_id: 1>,
-
# # #<Pet id: 5, name: "Brain", person_id: 1>,
-
# # #<Pet id: 6, name: "Boss", person_id: 1>
-
# # ]
-
#
-
# other_pets.replace([Pet.new(name: 'BooGoo')])
-
#
-
# other_pets
-
# # => [#<Pet id: nil, name: "BooGoo", person_id: 1>]
-
#
-
# person.pets
-
# # This is not affected by replace
-
# # => [
-
# # #<Pet id: 4, name: "Benny", person_id: 1>,
-
# # #<Pet id: 5, name: "Brain", person_id: 1>,
-
# # #<Pet id: 6, name: "Boss", person_id: 1>
-
# # ]
-
1
def to_ary
-
load_target.dup
-
end
-
1
alias_method :to_a, :to_ary
-
-
# Adds one or more +records+ to the collection by setting their foreign keys
-
# to the association's primary key. Returns +self+, so several appends may be
-
# chained together.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.size # => 0
-
# person.pets << Pet.new(name: 'Fancy-Fancy')
-
# person.pets << [Pet.new(name: 'Spook'), Pet.new(name: 'Choo-Choo')]
-
# person.pets.size # => 3
-
#
-
# person.id # => 1
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
1
def <<(*records)
-
proxy_association.concat(records) && self
-
end
-
1
alias_method :push, :<<
-
1
alias_method :append, :<<
-
-
1
def prepend(*args)
-
raise NoMethodError, "prepend on association is not defined. Please use << or append"
-
end
-
-
# Equivalent to +delete_all+. The difference is that returns +self+, instead
-
# of an array with the deleted objects, so methods can be chained. See
-
# +delete_all+ for more information.
-
1
def clear
-
delete_all
-
self
-
end
-
-
# Reloads the collection from the database. Returns +self+.
-
# Equivalent to <tt>collection(true)</tt>.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets # fetches pets from the database
-
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
-
#
-
# person.pets # uses the pets cache
-
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
-
#
-
# person.pets.reload # fetches pets from the database
-
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
-
#
-
# person.pets(true) # fetches pets from the database
-
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
-
1
def reload
-
proxy_association.reload
-
self
-
end
-
-
# Unloads the association. Returns +self+.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets # fetches pets from the database
-
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
-
#
-
# person.pets # uses the pets cache
-
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
-
#
-
# person.pets.reset # clears the pets cache
-
#
-
# person.pets # fetches pets from the database
-
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
-
1
def reset
-
proxy_association.reset
-
proxy_association.reset_scope
-
self
-
end
-
end
-
end
-
end
-
1
require 'active_model/forbidden_attributes_protection'
-
-
1
module ActiveRecord
-
1
module AttributeAssignment
-
1
extend ActiveSupport::Concern
-
1
include ActiveModel::ForbiddenAttributesProtection
-
-
# Allows you to set all the attributes by passing in a hash of attributes with
-
# keys matching the attribute names (which again matches the column names).
-
#
-
# If the passed hash responds to <tt>permitted?</tt> method and the return value
-
# of this method is +false+ an <tt>ActiveModel::ForbiddenAttributesError</tt>
-
# exception is raised.
-
1
def assign_attributes(new_attributes)
-
if !new_attributes.respond_to?(:stringify_keys)
-
raise ArgumentError, "When assigning attributes, you must pass a hash as an argument."
-
end
-
return if new_attributes.blank?
-
-
attributes = new_attributes.stringify_keys
-
multi_parameter_attributes = []
-
nested_parameter_attributes = []
-
-
attributes = sanitize_for_mass_assignment(attributes)
-
-
attributes.each do |k, v|
-
if k.include?("(")
-
multi_parameter_attributes << [ k, v ]
-
elsif v.is_a?(Hash)
-
nested_parameter_attributes << [ k, v ]
-
else
-
_assign_attribute(k, v)
-
end
-
end
-
-
assign_nested_parameter_attributes(nested_parameter_attributes) unless nested_parameter_attributes.empty?
-
assign_multiparameter_attributes(multi_parameter_attributes) unless multi_parameter_attributes.empty?
-
end
-
-
1
alias attributes= assign_attributes
-
-
1
private
-
-
1
def _assign_attribute(k, v)
-
public_send("#{k}=", v)
-
rescue NoMethodError
-
if respond_to?("#{k}=")
-
raise
-
else
-
raise UnknownAttributeError.new(self, k)
-
end
-
end
-
-
# Assign any deferred nested attributes after the base attributes have been set.
-
1
def assign_nested_parameter_attributes(pairs)
-
pairs.each { |k, v| _assign_attribute(k, v) }
-
end
-
-
# Instantiates objects for all attribute classes that needs more than one constructor parameter. This is done
-
# by calling new on the column type or aggregation type (through composed_of) object with these parameters.
-
# So having the pairs written_on(1) = "2004", written_on(2) = "6", written_on(3) = "24", will instantiate
-
# written_on (a date type) with Date.new("2004", "6", "24"). You can also specify a typecast character in the
-
# parentheses to have the parameters typecasted before they're used in the constructor. Use i for Fixnum and
-
# f for Float. If all the values for a given attribute are empty, the attribute will be set to +nil+.
-
1
def assign_multiparameter_attributes(pairs)
-
execute_callstack_for_multiparameter_attributes(
-
extract_callstack_for_multiparameter_attributes(pairs)
-
)
-
end
-
-
1
def execute_callstack_for_multiparameter_attributes(callstack)
-
errors = []
-
callstack.each do |name, values_with_empty_parameters|
-
begin
-
send("#{name}=", MultiparameterAttribute.new(self, name, values_with_empty_parameters).read_value)
-
rescue => ex
-
errors << AttributeAssignmentError.new("error on assignment #{values_with_empty_parameters.values.inspect} to #{name} (#{ex.message})", ex, name)
-
end
-
end
-
unless errors.empty?
-
error_descriptions = errors.map { |ex| ex.message }.join(",")
-
raise MultiparameterAssignmentErrors.new(errors), "#{errors.size} error(s) on assignment of multiparameter attributes [#{error_descriptions}]"
-
end
-
end
-
-
1
def extract_callstack_for_multiparameter_attributes(pairs)
-
attributes = {}
-
-
pairs.each do |(multiparameter_name, value)|
-
attribute_name = multiparameter_name.split("(").first
-
attributes[attribute_name] ||= {}
-
-
parameter_value = value.empty? ? nil : type_cast_attribute_value(multiparameter_name, value)
-
attributes[attribute_name][find_parameter_position(multiparameter_name)] ||= parameter_value
-
end
-
-
attributes
-
end
-
-
1
def type_cast_attribute_value(multiparameter_name, value)
-
multiparameter_name =~ /\([0-9]*([if])\)/ ? value.send("to_" + $1) : value
-
end
-
-
1
def find_parameter_position(multiparameter_name)
-
multiparameter_name.scan(/\(([0-9]*).*\)/).first.first.to_i
-
end
-
-
1
class MultiparameterAttribute #:nodoc:
-
1
attr_reader :object, :name, :values, :column
-
-
1
def initialize(object, name, values)
-
@object = object
-
@name = name
-
@values = values
-
end
-
-
1
def read_value
-
return if values.values.compact.empty?
-
-
@column = object.class.reflect_on_aggregation(name.to_sym) || object.column_for_attribute(name)
-
klass = column.klass
-
-
if klass == Time
-
read_time
-
elsif klass == Date
-
read_date
-
else
-
read_other(klass)
-
end
-
end
-
-
1
private
-
-
1
def instantiate_time_object(set_values)
-
if object.class.send(:create_time_zone_conversion_attribute?, name, column)
-
Time.zone.local(*set_values)
-
else
-
Time.send(object.class.default_timezone, *set_values)
-
end
-
end
-
-
1
def read_time
-
# If column is a :time (and not :date or :timestamp) there is no need to validate if
-
# there are year/month/day fields
-
if column.type == :time
-
# if the column is a time set the values to their defaults as January 1, 1970, but only if they're nil
-
{ 1 => 1970, 2 => 1, 3 => 1 }.each do |key,value|
-
values[key] ||= value
-
end
-
else
-
# else column is a timestamp, so if Date bits were not provided, error
-
validate_required_parameters!([1,2,3])
-
-
# If Date bits were provided but blank, then return nil
-
return if blank_date_parameter?
-
end
-
-
max_position = extract_max_param(6)
-
set_values = values.values_at(*(1..max_position))
-
# If Time bits are not there, then default to 0
-
(3..5).each { |i| set_values[i] = set_values[i].presence || 0 }
-
instantiate_time_object(set_values)
-
end
-
-
1
def read_date
-
return if blank_date_parameter?
-
set_values = values.values_at(1,2,3)
-
begin
-
Date.new(*set_values)
-
rescue ArgumentError # if Date.new raises an exception on an invalid date
-
instantiate_time_object(set_values).to_date # we instantiate Time object and convert it back to a date thus using Time's logic in handling invalid dates
-
end
-
end
-
-
1
def read_other(klass)
-
max_position = extract_max_param
-
positions = (1..max_position)
-
validate_required_parameters!(positions)
-
-
set_values = values.values_at(*positions)
-
klass.new(*set_values)
-
end
-
-
# Checks whether some blank date parameter exists. Note that this is different
-
# than the validate_required_parameters! method, since it just checks for blank
-
# positions instead of missing ones, and does not raise in case one blank position
-
# exists. The caller is responsible to handle the case of this returning true.
-
1
def blank_date_parameter?
-
(1..3).any? { |position| values[position].blank? }
-
end
-
-
# If some position is not provided, it errors out a missing parameter exception.
-
1
def validate_required_parameters!(positions)
-
if missing_parameter = positions.detect { |position| !values.key?(position) }
-
raise ArgumentError.new("Missing Parameter - #{name}(#{missing_parameter})")
-
end
-
end
-
-
1
def extract_max_param(upper_cap = 100)
-
[values.keys.max, upper_cap].min
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/enumerable'
-
1
require 'mutex_m'
-
1
require 'thread_safe'
-
-
1
module ActiveRecord
-
# = Active Record Attribute Methods
-
1
module AttributeMethods
-
1
extend ActiveSupport::Concern
-
1
include ActiveModel::AttributeMethods
-
-
1
included do
-
1
initialize_generated_modules
-
1
include Read
-
1
include Write
-
1
include BeforeTypeCast
-
1
include Query
-
1
include PrimaryKey
-
1
include TimeZoneConversion
-
1
include Dirty
-
1
include Serialization
-
end
-
-
1
AttrNames = Module.new {
-
1
def self.set_name_cache(name, value)
-
const_name = "ATTR_#{name}"
-
unless const_defined? const_name
-
const_set const_name, value.dup.freeze
-
end
-
end
-
}
-
-
1
BLACKLISTED_CLASS_METHODS = %w(private public protected)
-
-
1
class AttributeMethodCache
-
1
def initialize
-
2
@module = Module.new
-
2
@method_cache = ThreadSafe::Cache.new
-
end
-
-
1
def [](name)
-
@method_cache.compute_if_absent(name) do
-
safe_name = name.unpack('h*').first
-
temp_method = "__temp__#{safe_name}"
-
ActiveRecord::AttributeMethods::AttrNames.set_name_cache safe_name, name
-
@module.module_eval method_body(temp_method, safe_name), __FILE__, __LINE__
-
@module.instance_method temp_method
-
end
-
end
-
-
1
private
-
1
def method_body; raise NotImplementedError; end
-
end
-
-
1
module ClassMethods
-
1
def inherited(child_class) #:nodoc:
-
2
child_class.initialize_generated_modules
-
2
super
-
end
-
-
1
def initialize_generated_modules # :nodoc:
-
6
@generated_attribute_methods = Module.new { extend Mutex_m }
-
3
@attribute_methods_generated = false
-
3
include @generated_attribute_methods
-
end
-
-
# Generates all the attribute related methods for columns in the database
-
# accessors, mutators and query methods.
-
1
def define_attribute_methods # :nodoc:
-
# Use a mutex; we don't want two thread simultaneously trying to define
-
# attribute methods.
-
generated_attribute_methods.synchronize do
-
return false if @attribute_methods_generated
-
superclass.define_attribute_methods unless self == base_class
-
super(column_names)
-
@attribute_methods_generated = true
-
end
-
true
-
end
-
-
1
def undefine_attribute_methods # :nodoc:
-
5
generated_attribute_methods.synchronize do
-
5
super if @attribute_methods_generated
-
5
@attribute_methods_generated = false
-
end
-
end
-
-
# Raises a <tt>ActiveRecord::DangerousAttributeError</tt> exception when an
-
# \Active \Record method is defined in the model, otherwise +false+.
-
#
-
# class Person < ActiveRecord::Base
-
# def save
-
# 'already defined by Active Record'
-
# end
-
# end
-
#
-
# Person.instance_method_already_implemented?(:save)
-
# # => ActiveRecord::DangerousAttributeError: save is defined by ActiveRecord
-
#
-
# Person.instance_method_already_implemented?(:name)
-
# # => false
-
1
def instance_method_already_implemented?(method_name)
-
if dangerous_attribute_method?(method_name)
-
raise DangerousAttributeError, "#{method_name} is defined by Active Record"
-
end
-
-
if superclass == Base
-
super
-
else
-
# If B < A and A defines its own attribute method, then we don't want to overwrite that.
-
defined = method_defined_within?(method_name, superclass, superclass.generated_attribute_methods)
-
base_defined = Base.method_defined?(method_name) || Base.private_method_defined?(method_name)
-
defined && !base_defined || super
-
end
-
end
-
-
# A method name is 'dangerous' if it is already (re)defined by Active Record, but
-
# not by any ancestors. (So 'puts' is not dangerous but 'save' is.)
-
1
def dangerous_attribute_method?(name) # :nodoc:
-
8
method_defined_within?(name, Base)
-
end
-
-
1
def method_defined_within?(name, klass, superklass = klass.superclass) # :nodoc:
-
8
if klass.method_defined?(name) || klass.private_method_defined?(name)
-
if superklass.method_defined?(name) || superklass.private_method_defined?(name)
-
klass.instance_method(name).owner != superklass.instance_method(name).owner
-
else
-
true
-
end
-
else
-
8
false
-
end
-
end
-
-
# A class method is 'dangerous' if it is already (re)defined by Active Record, but
-
# not by any ancestors. (So 'puts' is not dangerous but 'new' is.)
-
1
def dangerous_class_method?(method_name)
-
BLACKLISTED_CLASS_METHODS.include?(method_name.to_s) || class_method_defined_within?(method_name, Base)
-
end
-
-
1
def class_method_defined_within?(name, klass, superklass = klass.superclass) # :nodoc
-
if klass.respond_to?(name, true)
-
if superklass.respond_to?(name, true)
-
klass.method(name).owner != superklass.method(name).owner
-
else
-
true
-
end
-
else
-
false
-
end
-
end
-
-
1
def find_generated_attribute_method(method_name) # :nodoc:
-
klass = self
-
until klass == Base
-
gen_methods = klass.generated_attribute_methods
-
return gen_methods.instance_method(method_name) if method_defined_within?(method_name, gen_methods, Object)
-
klass = klass.superclass
-
end
-
nil
-
end
-
-
# Returns +true+ if +attribute+ is an attribute method and table exists,
-
# +false+ otherwise.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# Person.attribute_method?('name') # => true
-
# Person.attribute_method?(:age=) # => true
-
# Person.attribute_method?(:nothing) # => false
-
1
def attribute_method?(attribute)
-
super || (table_exists? && column_names.include?(attribute.to_s.sub(/=$/, '')))
-
end
-
-
# Returns an array of column names as strings if it's not an abstract class and
-
# table exists. Otherwise it returns an empty array.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# Person.attribute_names
-
# # => ["id", "created_at", "updated_at", "name", "age"]
-
1
def attribute_names
-
@attribute_names ||= if !abstract_class? && table_exists?
-
column_names
-
else
-
[]
-
end
-
end
-
end
-
-
# If we haven't generated any methods yet, generate them, then
-
# see if we've created the method we're looking for.
-
1
def method_missing(method, *args, &block) # :nodoc:
-
self.class.define_attribute_methods
-
if respond_to_without_attributes?(method)
-
# make sure to invoke the correct attribute method, as we might have gotten here via a `super`
-
# call in a overwritten attribute method
-
if attribute_method = self.class.find_generated_attribute_method(method)
-
# this is probably horribly slow, but should only happen at most once for a given AR class
-
attribute_method.bind(self).call(*args, &block)
-
else
-
send(method, *args, &block)
-
end
-
else
-
super
-
end
-
end
-
-
# A Person object with a name attribute can ask <tt>person.respond_to?(:name)</tt>,
-
# <tt>person.respond_to?(:name=)</tt>, and <tt>person.respond_to?(:name?)</tt>
-
# which will all return +true+. It also define the attribute methods if they have
-
# not been generated.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# person = Person.new
-
# person.respond_to(:name) # => true
-
# person.respond_to(:name=) # => true
-
# person.respond_to(:name?) # => true
-
# person.respond_to('age') # => true
-
# person.respond_to('age=') # => true
-
# person.respond_to('age?') # => true
-
# person.respond_to(:nothing) # => false
-
1
def respond_to?(name, include_private = false)
-
name = name.to_s
-
self.class.define_attribute_methods
-
result = super
-
-
# If the result is false the answer is false.
-
return false unless result
-
-
# If the result is true then check for the select case.
-
# For queries selecting a subset of columns, return false for unselected columns.
-
# We check defined?(@attributes) not to issue warnings if called on objects that
-
# have been allocated but not yet initialized.
-
if defined?(@attributes) && @attributes.any? && self.class.column_names.include?(name)
-
return has_attribute?(name)
-
end
-
-
return true
-
end
-
-
# Returns +true+ if the given attribute is in the attributes hash, otherwise +false+.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# person = Person.new
-
# person.has_attribute?(:name) # => true
-
# person.has_attribute?('age') # => true
-
# person.has_attribute?(:nothing) # => false
-
1
def has_attribute?(attr_name)
-
@attributes.has_key?(attr_name.to_s)
-
end
-
-
# Returns an array of names for the attributes available on this object.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# person = Person.new
-
# person.attribute_names
-
# # => ["id", "created_at", "updated_at", "name", "age"]
-
1
def attribute_names
-
@attributes.keys
-
end
-
-
# Returns a hash of all the attributes with their names as keys and the values of the attributes as values.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# person = Person.create(name: 'Francesco', age: 22)
-
# person.attributes
-
# # => {"id"=>3, "created_at"=>Sun, 21 Oct 2012 04:53:04, "updated_at"=>Sun, 21 Oct 2012 04:53:04, "name"=>"Francesco", "age"=>22}
-
1
def attributes
-
attribute_names.each_with_object({}) { |name, attrs|
-
attrs[name] = read_attribute(name)
-
}
-
end
-
-
# Placeholder so it can be overriden when needed by serialization
-
1
def attributes_for_coder # :nodoc:
-
attributes
-
end
-
-
# Returns an <tt>#inspect</tt>-like string for the value of the
-
# attribute +attr_name+. String attributes are truncated upto 50
-
# characters, Date and Time attributes are returned in the
-
# <tt>:db</tt> format, Array attributes are truncated upto 10 values.
-
# Other attributes return the value of <tt>#inspect</tt> without
-
# modification.
-
#
-
# person = Person.create!(name: 'David Heinemeier Hansson ' * 3)
-
#
-
# person.attribute_for_inspect(:name)
-
# # => "\"David Heinemeier Hansson David Heinemeier Hansson ...\""
-
#
-
# person.attribute_for_inspect(:created_at)
-
# # => "\"2012-10-22 00:15:07\""
-
#
-
# person.attribute_for_inspect(:tag_ids)
-
# # => "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...]"
-
1
def attribute_for_inspect(attr_name)
-
value = read_attribute(attr_name)
-
-
if value.is_a?(String) && value.length > 50
-
"#{value[0, 50]}...".inspect
-
elsif value.is_a?(Date) || value.is_a?(Time)
-
%("#{value.to_s(:db)}")
-
elsif value.is_a?(Array) && value.size > 10
-
inspected = value.first(10).inspect
-
%(#{inspected[0...-1]}, ...])
-
else
-
value.inspect
-
end
-
end
-
-
# Returns +true+ if the specified +attribute+ has been set by the user or by a
-
# database load and is neither +nil+ nor <tt>empty?</tt> (the latter only applies
-
# to objects that respond to <tt>empty?</tt>, most notably Strings). Otherwise, +false+.
-
# Note that it always returns +true+ with boolean attributes.
-
#
-
# class Task < ActiveRecord::Base
-
# end
-
#
-
# person = Task.new(title: '', is_done: false)
-
# person.attribute_present?(:title) # => false
-
# person.attribute_present?(:is_done) # => true
-
# person.name = 'Francesco'
-
# person.is_done = true
-
# person.attribute_present?(:title) # => true
-
# person.attribute_present?(:is_done) # => true
-
1
def attribute_present?(attribute)
-
value = read_attribute(attribute)
-
!value.nil? && !(value.respond_to?(:empty?) && value.empty?)
-
end
-
-
# Returns the column object for the named attribute. Returns +nil+ if the
-
# named attribute not exists.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# person = Person.new
-
# person.column_for_attribute(:name) # the result depends on the ConnectionAdapter
-
# # => #<ActiveRecord::ConnectionAdapters::SQLite3Column:0x007ff4ab083980 @name="name", @sql_type="varchar(255)", @null=true, ...>
-
#
-
# person.column_for_attribute(:nothing)
-
# # => nil
-
1
def column_for_attribute(name)
-
# FIXME: should this return a null object for columns that don't exist?
-
self.class.columns_hash[name.to_s]
-
end
-
-
# Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example,
-
# "2004-12-12" in a date column is cast to a date object, like Date.new(2004, 12, 12)). It raises
-
# <tt>ActiveModel::MissingAttributeError</tt> if the identified attribute is missing.
-
#
-
# Alias for the <tt>read_attribute</tt> method.
-
#
-
# class Person < ActiveRecord::Base
-
# belongs_to :organization
-
# end
-
#
-
# person = Person.new(name: 'Francesco', age: '22')
-
# person[:name] # => "Francesco"
-
# person[:age] # => 22
-
#
-
# person = Person.select('id').first
-
# person[:name] # => ActiveModel::MissingAttributeError: missing attribute: name
-
# person[:organization_id] # => ActiveModel::MissingAttributeError: missing attribute: organization_id
-
1
def [](attr_name)
-
read_attribute(attr_name) { |n| missing_attribute(n, caller) }
-
end
-
-
# Updates the attribute identified by <tt>attr_name</tt> with the specified +value+.
-
# (Alias for the protected <tt>write_attribute</tt> method).
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# person = Person.new
-
# person[:age] = '22'
-
# person[:age] # => 22
-
# person[:age] # => Fixnum
-
1
def []=(attr_name, value)
-
write_attribute(attr_name, value)
-
end
-
-
1
protected
-
-
1
def clone_attributes(reader_method = :read_attribute, attributes = {}) # :nodoc:
-
attribute_names.each do |name|
-
attributes[name] = clone_attribute_value(reader_method, name)
-
end
-
attributes
-
end
-
-
1
def clone_attribute_value(reader_method, attribute_name) # :nodoc:
-
value = send(reader_method, attribute_name)
-
value.duplicable? ? value.clone : value
-
rescue TypeError, NoMethodError
-
value
-
end
-
-
1
def arel_attributes_with_values_for_create(attribute_names) # :nodoc:
-
arel_attributes_with_values(attributes_for_create(attribute_names))
-
end
-
-
1
def arel_attributes_with_values_for_update(attribute_names) # :nodoc:
-
arel_attributes_with_values(attributes_for_update(attribute_names))
-
end
-
-
1
def attribute_method?(attr_name) # :nodoc:
-
# We check defined? because Syck calls respond_to? before actually calling initialize.
-
defined?(@attributes) && @attributes.include?(attr_name)
-
end
-
-
1
private
-
-
# Returns a Hash of the Arel::Attributes and attribute values that have been
-
# typecasted for use in an Arel insert/update method.
-
1
def arel_attributes_with_values(attribute_names)
-
attrs = {}
-
arel_table = self.class.arel_table
-
-
attribute_names.each do |name|
-
attrs[arel_table[name]] = typecasted_attribute_value(name)
-
end
-
attrs
-
end
-
-
# Filters the primary keys and readonly attributes from the attribute names.
-
1
def attributes_for_update(attribute_names)
-
attribute_names.select do |name|
-
column_for_attribute(name) && !readonly_attribute?(name)
-
end
-
end
-
-
# Filters out the primary keys, from the attribute names, when the primary
-
# key is to be generated (e.g. the id attribute has no value).
-
1
def attributes_for_create(attribute_names)
-
attribute_names.select do |name|
-
column_for_attribute(name) && !(pk_attribute?(name) && id.nil?)
-
end
-
end
-
-
1
def readonly_attribute?(name)
-
self.class.readonly_attributes.include?(name)
-
end
-
-
1
def pk_attribute?(name)
-
column_for_attribute(name).primary
-
end
-
-
1
def typecasted_attribute_value(name)
-
# FIXME: we need @attributes to be used consistently.
-
# If the values stored in @attributes were already typecasted, this code
-
# could be simplified
-
read_attribute(name)
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module AttributeMethods
-
# = Active Record Attribute Methods Before Type Cast
-
#
-
# <tt>ActiveRecord::AttributeMethods::BeforeTypeCast</tt> provides a way to
-
# read the value of the attributes before typecasting and deserialization.
-
#
-
# class Task < ActiveRecord::Base
-
# end
-
#
-
# task = Task.new(id: '1', completed_on: '2012-10-21')
-
# task.id # => 1
-
# task.completed_on # => Sun, 21 Oct 2012
-
#
-
# task.attributes_before_type_cast
-
# # => {"id"=>"1", "completed_on"=>"2012-10-21", ... }
-
# task.read_attribute_before_type_cast('id') # => "1"
-
# task.read_attribute_before_type_cast('completed_on') # => "2012-10-21"
-
#
-
# In addition to #read_attribute_before_type_cast and #attributes_before_type_cast,
-
# it declares a method for all attributes with the <tt>*_before_type_cast</tt>
-
# suffix.
-
#
-
# task.id_before_type_cast # => "1"
-
# task.completed_on_before_type_cast # => "2012-10-21"
-
1
module BeforeTypeCast
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
attribute_method_suffix "_before_type_cast"
-
end
-
-
# Returns the value of the attribute identified by +attr_name+ before
-
# typecasting and deserialization.
-
#
-
# class Task < ActiveRecord::Base
-
# end
-
#
-
# task = Task.new(id: '1', completed_on: '2012-10-21')
-
# task.read_attribute('id') # => 1
-
# task.read_attribute_before_type_cast('id') # => '1'
-
# task.read_attribute('completed_on') # => Sun, 21 Oct 2012
-
# task.read_attribute_before_type_cast('completed_on') # => "2012-10-21"
-
# task.read_attribute_before_type_cast(:completed_on) # => "2012-10-21"
-
1
def read_attribute_before_type_cast(attr_name)
-
@attributes[attr_name.to_s]
-
end
-
-
# Returns a hash of attributes before typecasting and deserialization.
-
#
-
# class Task < ActiveRecord::Base
-
# end
-
#
-
# task = Task.new(title: nil, is_done: true, completed_on: '2012-10-21')
-
# task.attributes
-
# # => {"id"=>nil, "title"=>nil, "is_done"=>true, "completed_on"=>Sun, 21 Oct 2012, "created_at"=>nil, "updated_at"=>nil}
-
# task.attributes_before_type_cast
-
# # => {"id"=>nil, "title"=>nil, "is_done"=>true, "completed_on"=>"2012-10-21", "created_at"=>nil, "updated_at"=>nil}
-
1
def attributes_before_type_cast
-
@attributes
-
end
-
-
1
private
-
-
# Handle *_before_type_cast for method_missing.
-
1
def attribute_before_type_cast(attribute_name)
-
read_attribute_before_type_cast(attribute_name)
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
-
1
module ActiveRecord
-
1
module AttributeMethods
-
1
module Dirty # :nodoc:
-
1
extend ActiveSupport::Concern
-
-
1
include ActiveModel::Dirty
-
-
1
included do
-
1
if self < ::ActiveRecord::Timestamp
-
raise "You cannot include Dirty after Timestamp"
-
end
-
-
1
class_attribute :partial_writes, instance_writer: false
-
1
self.partial_writes = true
-
end
-
-
# Attempts to +save+ the record and clears changed attributes if successful.
-
1
def save(*)
-
if status = super
-
changes_applied
-
end
-
status
-
end
-
-
# Attempts to <tt>save!</tt> the record and clears changed attributes if successful.
-
1
def save!(*)
-
super.tap do
-
changes_applied
-
end
-
end
-
-
# <tt>reload</tt> the record and clears changed attributes.
-
1
def reload(*)
-
super.tap do
-
reset_changes
-
end
-
end
-
-
1
def initialize_dup(other) # :nodoc:
-
super
-
init_changed_attributes
-
end
-
-
1
private
-
1
def initialize_internals_callback
-
super
-
init_changed_attributes
-
end
-
-
1
def init_changed_attributes
-
@changed_attributes = nil
-
# Intentionally avoid using #column_defaults since overridden defaults (as is done in
-
# optimistic locking) won't get written unless they get marked as changed
-
self.class.columns.each do |c|
-
attr, orig_value = c.name, c.default
-
changed_attributes[attr] = orig_value if _field_changed?(attr, orig_value, @attributes[attr])
-
end
-
end
-
-
# Wrap write_attribute to remember original attribute value.
-
1
def write_attribute(attr, value)
-
attr = attr.to_s
-
-
save_changed_attribute(attr, value)
-
-
super(attr, value)
-
end
-
-
1
def save_changed_attribute(attr, value)
-
# The attribute already has an unsaved change.
-
if attribute_changed?(attr)
-
old = changed_attributes[attr]
-
changed_attributes.delete(attr) unless _field_changed?(attr, old, value)
-
else
-
old = clone_attribute_value(:read_attribute, attr)
-
changed_attributes[attr] = old if _field_changed?(attr, old, value)
-
end
-
end
-
-
1
def update_record(*)
-
partial_writes? ? super(keys_for_partial_write) : super
-
end
-
-
1
def create_record(*)
-
partial_writes? ? super(keys_for_partial_write) : super
-
end
-
-
# Serialized attributes should always be written in case they've been
-
# changed in place.
-
1
def keys_for_partial_write
-
changed
-
end
-
-
1
def _field_changed?(attr, old, value)
-
if column = column_for_attribute(attr)
-
if column.number? && (changes_from_nil_to_empty_string?(column, old, value) ||
-
changes_from_zero_to_string?(old, value))
-
value = nil
-
else
-
value = column.type_cast(value)
-
end
-
end
-
-
old != value
-
end
-
-
1
def changes_from_nil_to_empty_string?(column, old, value)
-
# For nullable numeric columns, NULL gets stored in database for blank (i.e. '') values.
-
# Hence we don't record it as a change if the value changes from nil to ''.
-
# If an old value of 0 is set to '' we want this to get changed to nil as otherwise it'll
-
# be typecast back to 0 (''.to_i => 0)
-
column.null && (old.nil? || old == 0) && value.blank?
-
end
-
-
1
def changes_from_zero_to_string?(old, value)
-
# For columns with old 0 and value non-empty string
-
old == 0 && value.is_a?(String) && value.present? && non_zero?(value)
-
end
-
-
1
def non_zero?(value)
-
value !~ /\A0+(\.0+)?\z/
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module AttributeMethods
-
1
module Query
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
attribute_method_suffix "?"
-
end
-
-
1
def query_attribute(attr_name)
-
value = read_attribute(attr_name) { |n| missing_attribute(n, caller) }
-
-
case value
-
when true then true
-
when false, nil then false
-
else
-
column = self.class.columns_hash[attr_name]
-
if column.nil?
-
if Numeric === value || value !~ /[^0-9]/
-
!value.to_i.zero?
-
else
-
return false if ActiveRecord::ConnectionAdapters::Column::FALSE_VALUES.include?(value)
-
!value.blank?
-
end
-
elsif column.number?
-
!value.zero?
-
else
-
!value.blank?
-
end
-
end
-
end
-
-
1
private
-
# Handle *? for method_missing.
-
1
def attribute?(attribute_name)
-
query_attribute(attribute_name)
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/method_transplanting'
-
-
1
module ActiveRecord
-
1
module AttributeMethods
-
1
module Read
-
1
ReaderMethodCache = Class.new(AttributeMethodCache) {
-
1
private
-
# We want to generate the methods via module_eval rather than
-
# define_method, because define_method is slower on dispatch.
-
# Evaluating many similar methods may use more memory as the instruction
-
# sequences are duplicated and cached (in MRI). define_method may
-
# be slower on dispatch, but if you're careful about the closure
-
# created, then define_method will consume much less memory.
-
#
-
# But sometimes the database might return columns with
-
# characters that are not allowed in normal method names (like
-
# 'my_column(omg)'. So to work around this we first define with
-
# the __temp__ identifier, and then use alias method to rename
-
# it to what we want.
-
#
-
# We are also defining a constant to hold the frozen string of
-
# the attribute name. Using a constant means that we do not have
-
# to allocate an object on each call to the attribute method.
-
# Making it frozen means that it doesn't get duped when used to
-
# key the @attributes_cache in read_attribute.
-
1
def method_body(method_name, const_name)
-
<<-EOMETHOD
-
def #{method_name}
-
name = ::ActiveRecord::AttributeMethods::AttrNames::ATTR_#{const_name}
-
read_attribute(name) { |n| missing_attribute(n, caller) }
-
end
-
EOMETHOD
-
end
-
}.new
-
-
1
extend ActiveSupport::Concern
-
-
1
ATTRIBUTE_TYPES_CACHED_BY_DEFAULT = [:datetime, :timestamp, :time, :date]
-
-
1
included do
-
1
class_attribute :attribute_types_cached_by_default, instance_writer: false
-
1
self.attribute_types_cached_by_default = ATTRIBUTE_TYPES_CACHED_BY_DEFAULT
-
end
-
-
1
module ClassMethods
-
# +cache_attributes+ allows you to declare which converted attribute
-
# values should be cached. Usually caching only pays off for attributes
-
# with expensive conversion methods, like time related columns (e.g.
-
# +created_at+, +updated_at+).
-
1
def cache_attributes(*attribute_names)
-
cached_attributes.merge attribute_names.map { |attr| attr.to_s }
-
end
-
-
# Returns the attributes which are cached. By default time related columns
-
# with datatype <tt>:datetime, :timestamp, :time, :date</tt> are cached.
-
1
def cached_attributes
-
@cached_attributes ||= columns.select { |c| cacheable_column?(c) }.map { |col| col.name }.to_set
-
end
-
-
# Returns +true+ if the provided attribute is being cached.
-
1
def cache_attribute?(attr_name)
-
cached_attributes.include?(attr_name)
-
end
-
-
1
protected
-
-
1
if Module.methods_transplantable?
-
1
def define_method_attribute(name)
-
method = ReaderMethodCache[name]
-
generated_attribute_methods.module_eval { define_method name, method }
-
end
-
else
-
def define_method_attribute(name)
-
safe_name = name.unpack('h*').first
-
temp_method = "__temp__#{safe_name}"
-
-
ActiveRecord::AttributeMethods::AttrNames.set_name_cache safe_name, name
-
-
generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1
-
def #{temp_method}
-
name = ::ActiveRecord::AttributeMethods::AttrNames::ATTR_#{safe_name}
-
read_attribute(name) { |n| missing_attribute(n, caller) }
-
end
-
STR
-
-
generated_attribute_methods.module_eval do
-
alias_method name, temp_method
-
undef_method temp_method
-
end
-
end
-
end
-
-
1
private
-
-
1
def cacheable_column?(column)
-
if attribute_types_cached_by_default == ATTRIBUTE_TYPES_CACHED_BY_DEFAULT
-
! serialized_attributes.include? column.name
-
else
-
attribute_types_cached_by_default.include?(column.type)
-
end
-
end
-
end
-
-
# Returns the value of the attribute identified by <tt>attr_name</tt> after
-
# it has been typecast (for example, "2004-12-12" in a date column is cast
-
# to a date object, like Date.new(2004, 12, 12)).
-
1
def read_attribute(attr_name)
-
# If it's cached, just return it
-
# We use #[] first as a perf optimization for non-nil values. See https://gist.github.com/jonleighton/3552829.
-
name = attr_name.to_s
-
@attributes_cache[name] || @attributes_cache.fetch(name) {
-
column = @column_types_override[name] if @column_types_override
-
column ||= @column_types[name]
-
-
return @attributes.fetch(name) {
-
if name == 'id' && self.class.primary_key != name
-
read_attribute(self.class.primary_key)
-
end
-
} unless column
-
-
value = @attributes.fetch(name) {
-
return block_given? ? yield(name) : nil
-
}
-
-
if self.class.cache_attribute?(name)
-
@attributes_cache[name] = column.type_cast(value)
-
else
-
column.type_cast value
-
end
-
}
-
end
-
-
1
private
-
-
1
def attribute(attribute_name)
-
read_attribute(attribute_name)
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module AttributeMethods
-
1
module Serialization
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
# Returns a hash of all the attributes that have been specified for
-
# serialization as keys and their class restriction as values.
-
1
class_attribute :serialized_attributes, instance_accessor: false
-
1
self.serialized_attributes = {}
-
end
-
-
1
module ClassMethods
-
##
-
# :method: serialized_attributes
-
#
-
# Returns a hash of all the attributes that have been specified for
-
# serialization as keys and their class restriction as values.
-
-
# If you have an attribute that needs to be saved to the database as an
-
# object, and retrieved as the same object, then specify the name of that
-
# attribute using this method and it will be handled automatically. The
-
# serialization is done through YAML. If +class_name+ is specified, the
-
# serialized object must be of that class on retrieval or
-
# <tt>SerializationTypeMismatch</tt> will be raised.
-
#
-
# A notable side effect of serialized attributes is that the model will
-
# be updated on every save, even if it is not dirty.
-
#
-
# ==== Parameters
-
#
-
# * +attr_name+ - The field name that should be serialized.
-
# * +class_name+ - Optional, class name that the object type should be equal to.
-
#
-
# ==== Example
-
#
-
# # Serialize a preferences attribute.
-
# class User < ActiveRecord::Base
-
# serialize :preferences
-
# end
-
1
def serialize(attr_name, class_name = Object)
-
include Behavior
-
-
coder = if [:load, :dump].all? { |x| class_name.respond_to?(x) }
-
class_name
-
else
-
Coders::YAMLColumn.new(class_name)
-
end
-
-
# merge new serialized attribute and create new hash to ensure that each class in inheritance hierarchy
-
# has its own hash of own serialized attributes
-
self.serialized_attributes = serialized_attributes.merge(attr_name.to_s => coder)
-
end
-
end
-
-
1
class Type # :nodoc:
-
1
def initialize(column)
-
@column = column
-
end
-
-
1
def type_cast(value)
-
if value.state == :serialized
-
value.unserialized_value @column.type_cast value.value
-
else
-
value.unserialized_value
-
end
-
end
-
-
1
def type
-
@column.type
-
end
-
-
1
def accessor
-
ActiveRecord::Store::IndifferentHashAccessor
-
end
-
end
-
-
1
class Attribute < Struct.new(:coder, :value, :state) # :nodoc:
-
1
def unserialized_value(v = value)
-
state == :serialized ? unserialize(v) : value
-
end
-
-
1
def serialized_value
-
state == :unserialized ? serialize : value
-
end
-
-
1
def unserialize(v)
-
self.state = :unserialized
-
self.value = coder.load(v)
-
end
-
-
1
def serialize
-
self.state = :serialized
-
self.value = coder.dump(value)
-
end
-
end
-
-
# This is only added to the model when serialize is called, which
-
# ensures we do not make things slower when serialization is not used.
-
1
module Behavior # :nodoc:
-
1
extend ActiveSupport::Concern
-
-
1
module ClassMethods # :nodoc:
-
1
def initialize_attributes(attributes, options = {})
-
serialized = (options.delete(:serialized) { true }) ? :serialized : :unserialized
-
super(attributes, options)
-
-
serialized_attributes.each do |key, coder|
-
if attributes.key?(key)
-
attributes[key] = Attribute.new(coder, attributes[key], serialized)
-
end
-
end
-
-
attributes
-
end
-
end
-
-
1
def should_record_timestamps?
-
super || (self.record_timestamps && (attributes.keys & self.class.serialized_attributes.keys).present?)
-
end
-
-
1
def keys_for_partial_write
-
super | (attributes.keys & self.class.serialized_attributes.keys)
-
end
-
-
1
def type_cast_attribute_for_write(column, value)
-
if column && coder = self.class.serialized_attributes[column.name]
-
Attribute.new(coder, value, :unserialized)
-
else
-
super
-
end
-
end
-
-
1
def _field_changed?(attr, old, value)
-
if self.class.serialized_attributes.include?(attr)
-
old != value
-
else
-
super
-
end
-
end
-
-
1
def read_attribute_before_type_cast(attr_name)
-
if self.class.serialized_attributes.include?(attr_name)
-
super.unserialized_value
-
else
-
super
-
end
-
end
-
-
1
def attributes_before_type_cast
-
super.dup.tap do |attributes|
-
self.class.serialized_attributes.each_key do |key|
-
if attributes.key?(key)
-
attributes[key] = attributes[key].unserialized_value
-
end
-
end
-
end
-
end
-
-
1
def typecasted_attribute_value(name)
-
if self.class.serialized_attributes.include?(name)
-
@attributes[name].serialized_value
-
else
-
super
-
end
-
end
-
-
1
def attributes_for_coder
-
attribute_names.each_with_object({}) do |name, attrs|
-
attrs[name] = if self.class.serialized_attributes.include?(name)
-
@attributes[name].serialized_value
-
else
-
read_attribute(name)
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module AttributeMethods
-
1
module TimeZoneConversion
-
1
class Type # :nodoc:
-
1
def initialize(column)
-
@column = column
-
end
-
-
1
def type_cast(value)
-
value = @column.type_cast(value)
-
value.acts_like?(:time) ? value.in_time_zone : value
-
end
-
-
1
def type
-
@column.type
-
end
-
end
-
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
mattr_accessor :time_zone_aware_attributes, instance_writer: false
-
1
self.time_zone_aware_attributes = false
-
-
1
class_attribute :skip_time_zone_conversion_for_attributes, instance_writer: false
-
1
self.skip_time_zone_conversion_for_attributes = []
-
end
-
-
1
module ClassMethods
-
1
protected
-
# Defined for all +datetime+ and +timestamp+ attributes when +time_zone_aware_attributes+ are enabled.
-
# This enhanced write method will automatically convert the time passed to it to the zone stored in Time.zone.
-
1
def define_method_attribute=(attr_name)
-
if create_time_zone_conversion_attribute?(attr_name, columns_hash[attr_name])
-
method_body, line = <<-EOV, __LINE__ + 1
-
def #{attr_name}=(time)
-
time_with_zone = time.respond_to?(:in_time_zone) ? time.in_time_zone : nil
-
previous_time = attribute_changed?("#{attr_name}") ? changed_attributes["#{attr_name}"] : read_attribute(:#{attr_name})
-
write_attribute(:#{attr_name}, time)
-
#{attr_name}_will_change! if previous_time != time_with_zone
-
@attributes_cache["#{attr_name}"] = time_with_zone
-
end
-
EOV
-
generated_attribute_methods.module_eval(method_body, __FILE__, line)
-
else
-
super
-
end
-
end
-
-
1
private
-
1
def create_time_zone_conversion_attribute?(name, column)
-
time_zone_aware_attributes &&
-
!self.skip_time_zone_conversion_for_attributes.include?(name.to_sym) &&
-
(:datetime == column.type || :timestamp == column.type)
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/method_transplanting'
-
-
1
module ActiveRecord
-
1
module AttributeMethods
-
1
module Write
-
1
WriterMethodCache = Class.new(AttributeMethodCache) {
-
1
private
-
-
1
def method_body(method_name, const_name)
-
<<-EOMETHOD
-
def #{method_name}(value)
-
name = ::ActiveRecord::AttributeMethods::AttrNames::ATTR_#{const_name}
-
write_attribute(name, value)
-
end
-
EOMETHOD
-
end
-
}.new
-
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
attribute_method_suffix "="
-
end
-
-
1
module ClassMethods
-
1
protected
-
-
1
if Module.methods_transplantable?
-
# See define_method_attribute in read.rb for an explanation of
-
# this code.
-
1
def define_method_attribute=(name)
-
method = WriterMethodCache[name]
-
generated_attribute_methods.module_eval {
-
define_method "#{name}=", method
-
}
-
end
-
else
-
def define_method_attribute=(name)
-
safe_name = name.unpack('h*').first
-
ActiveRecord::AttributeMethods::AttrNames.set_name_cache safe_name, name
-
-
generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1
-
def __temp__#{safe_name}=(value)
-
name = ::ActiveRecord::AttributeMethods::AttrNames::ATTR_#{safe_name}
-
write_attribute(name, value)
-
end
-
alias_method #{(name + '=').inspect}, :__temp__#{safe_name}=
-
undef_method :__temp__#{safe_name}=
-
STR
-
end
-
end
-
end
-
-
# Updates the attribute identified by <tt>attr_name</tt> with the
-
# specified +value+. Empty strings for fixnum and float columns are
-
# turned into +nil+.
-
1
def write_attribute(attr_name, value)
-
attr_name = attr_name.to_s
-
attr_name = self.class.primary_key if attr_name == 'id' && self.class.primary_key
-
@attributes_cache.delete(attr_name)
-
column = column_for_attribute(attr_name)
-
-
# If we're dealing with a binary column, write the data to the cache
-
# so we don't attempt to typecast multiple times.
-
if column && column.binary?
-
@attributes_cache[attr_name] = value
-
end
-
-
if column || @attributes.has_key?(attr_name)
-
@attributes[attr_name] = type_cast_attribute_for_write(column, value)
-
else
-
raise ActiveModel::MissingAttributeError, "can't write unknown attribute `#{attr_name}'"
-
end
-
end
-
1
alias_method :raw_write_attribute, :write_attribute
-
-
1
private
-
# Handle *= for method_missing.
-
1
def attribute=(attribute_name, value)
-
write_attribute(attribute_name, value)
-
end
-
-
1
def type_cast_attribute_for_write(column, value)
-
return value unless column
-
-
column.type_cast_for_write value
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
# = Active Record Autosave Association
-
#
-
# +AutosaveAssociation+ is a module that takes care of automatically saving
-
# associated records when their parent is saved. In addition to saving, it
-
# also destroys any associated records that were marked for destruction.
-
# (See +mark_for_destruction+ and <tt>marked_for_destruction?</tt>).
-
#
-
# Saving of the parent, its associations, and the destruction of marked
-
# associations, all happen inside a transaction. This should never leave the
-
# database in an inconsistent state.
-
#
-
# If validations for any of the associations fail, their error messages will
-
# be applied to the parent.
-
#
-
# Note that it also means that associations marked for destruction won't
-
# be destroyed directly. They will however still be marked for destruction.
-
#
-
# Note that <tt>autosave: false</tt> is not same as not declaring <tt>:autosave</tt>.
-
# When the <tt>:autosave</tt> option is not present then new association records are
-
# saved but the updated association records are not saved.
-
#
-
# == Validation
-
#
-
# Children records are validated unless <tt>:validate</tt> is +false+.
-
#
-
# == Callbacks
-
#
-
# Association with autosave option defines several callbacks on your
-
# model (before_save, after_create, after_update). Please note that
-
# callbacks are executed in the order they were defined in
-
# model. You should avoid modifying the association content, before
-
# autosave callbacks are executed. Placing your callbacks after
-
# associations is usually a good practice.
-
#
-
# === One-to-one Example
-
#
-
# class Post
-
# has_one :author, autosave: true
-
# end
-
#
-
# Saving changes to the parent and its associated model can now be performed
-
# automatically _and_ atomically:
-
#
-
# post = Post.find(1)
-
# post.title # => "The current global position of migrating ducks"
-
# post.author.name # => "alloy"
-
#
-
# post.title = "On the migration of ducks"
-
# post.author.name = "Eloy Duran"
-
#
-
# post.save
-
# post.reload
-
# post.title # => "On the migration of ducks"
-
# post.author.name # => "Eloy Duran"
-
#
-
# Destroying an associated model, as part of the parent's save action, is as
-
# simple as marking it for destruction:
-
#
-
# post.author.mark_for_destruction
-
# post.author.marked_for_destruction? # => true
-
#
-
# Note that the model is _not_ yet removed from the database:
-
#
-
# id = post.author.id
-
# Author.find_by(id: id).nil? # => false
-
#
-
# post.save
-
# post.reload.author # => nil
-
#
-
# Now it _is_ removed from the database:
-
#
-
# Author.find_by(id: id).nil? # => true
-
#
-
# === One-to-many Example
-
#
-
# When <tt>:autosave</tt> is not declared new children are saved when their parent is saved:
-
#
-
# class Post
-
# has_many :comments # :autosave option is not declared
-
# end
-
#
-
# post = Post.new(title: 'ruby rocks')
-
# post.comments.build(body: 'hello world')
-
# post.save # => saves both post and comment
-
#
-
# post = Post.create(title: 'ruby rocks')
-
# post.comments.build(body: 'hello world')
-
# post.save # => saves both post and comment
-
#
-
# post = Post.create(title: 'ruby rocks')
-
# post.comments.create(body: 'hello world')
-
# post.save # => saves both post and comment
-
#
-
# When <tt>:autosave</tt> is true all children are saved, no matter whether they
-
# are new records or not:
-
#
-
# class Post
-
# has_many :comments, autosave: true
-
# end
-
#
-
# post = Post.create(title: 'ruby rocks')
-
# post.comments.create(body: 'hello world')
-
# post.comments[0].body = 'hi everyone'
-
# post.save # => saves both post and comment, with 'hi everyone' as body
-
#
-
# Destroying one of the associated models as part of the parent's save action
-
# is as simple as marking it for destruction:
-
#
-
# post.comments.last.mark_for_destruction
-
# post.comments.last.marked_for_destruction? # => true
-
# post.comments.length # => 2
-
#
-
# Note that the model is _not_ yet removed from the database:
-
#
-
# id = post.comments.last.id
-
# Comment.find_by(id: id).nil? # => false
-
#
-
# post.save
-
# post.reload.comments.length # => 1
-
#
-
# Now it _is_ removed from the database:
-
#
-
# Comment.find_by(id: id).nil? # => true
-
-
1
module AutosaveAssociation
-
1
extend ActiveSupport::Concern
-
-
1
module AssociationBuilderExtension #:nodoc:
-
1
def self.build(model, reflection)
-
8
model.send(:add_autosave_association_callbacks, reflection)
-
end
-
-
1
def self.valid_options
-
8
[ :autosave ]
-
end
-
end
-
-
1
included do
-
1
Associations::Builder::Association.extensions << AssociationBuilderExtension
-
end
-
-
1
module ClassMethods
-
1
private
-
-
1
def define_non_cyclic_method(name, &block)
-
16
define_method(name) do |*args|
-
result = true; @_already_called ||= {}
-
# Loop prevention for validation of associations
-
unless @_already_called[name]
-
begin
-
@_already_called[name]=true
-
result = instance_eval(&block)
-
ensure
-
@_already_called[name]=false
-
end
-
end
-
-
result
-
end
-
end
-
-
# Adds validation and save callbacks for the association as specified by
-
# the +reflection+.
-
#
-
# For performance reasons, we don't check whether to validate at runtime.
-
# However the validation and callback methods are lazy and those methods
-
# get created when they are invoked for the very first time. However,
-
# this can change, for instance, when using nested attributes, which is
-
# called _after_ the association has been defined. Since we don't want
-
# the callbacks to get defined multiple times, there are guards that
-
# check if the save or validation methods have already been defined
-
# before actually defining them.
-
1
def add_autosave_association_callbacks(reflection)
-
13
save_method = :"autosave_associated_records_for_#{reflection.name}"
-
13
validation_method = :"validate_associated_records_for_#{reflection.name}"
-
13
collection = reflection.collection?
-
-
13
unless method_defined?(save_method)
-
8
if collection
-
8
before_save :before_save_collection_association
-
-
8
define_non_cyclic_method(save_method) { save_collection_association(reflection) }
-
# Doesn't use after_save as that would save associations added in after_create/after_update twice
-
8
after_create save_method
-
8
after_update save_method
-
elsif reflection.macro == :has_one
-
define_method(save_method) { save_has_one_association(reflection) }
-
# Configures two callbacks instead of a single after_save so that
-
# the model may rely on their execution order relative to its
-
# own callbacks.
-
#
-
# For example, given that after_creates run before after_saves, if
-
# we configured instead an after_save there would be no way to fire
-
# a custom after_create callback after the child association gets
-
# created.
-
after_create save_method
-
after_update save_method
-
else
-
define_non_cyclic_method(save_method) { save_belongs_to_association(reflection) }
-
before_save save_method
-
end
-
end
-
-
13
if reflection.validate? && !method_defined?(validation_method)
-
8
method = (collection ? :validate_collection_association : :validate_single_association)
-
8
define_non_cyclic_method(validation_method) { send(method, reflection) }
-
8
validate validation_method
-
end
-
end
-
end
-
-
# Reloads the attributes of the object as usual and clears <tt>marked_for_destruction</tt> flag.
-
1
def reload(options = nil)
-
@marked_for_destruction = false
-
@destroyed_by_association = nil
-
super
-
end
-
-
# Marks this record to be destroyed as part of the parents save transaction.
-
# This does _not_ actually destroy the record instantly, rather child record will be destroyed
-
# when <tt>parent.save</tt> is called.
-
#
-
# Only useful if the <tt>:autosave</tt> option on the parent is enabled for this associated model.
-
1
def mark_for_destruction
-
@marked_for_destruction = true
-
end
-
-
# Returns whether or not this record will be destroyed as part of the parents save transaction.
-
#
-
# Only useful if the <tt>:autosave</tt> option on the parent is enabled for this associated model.
-
1
def marked_for_destruction?
-
@marked_for_destruction
-
end
-
-
# Records the association that is being destroyed and destroying this
-
# record in the process.
-
1
def destroyed_by_association=(reflection)
-
@destroyed_by_association = reflection
-
end
-
-
# Returns the association for the parent being destroyed.
-
#
-
# Used to avoid updating the counter cache unnecessarily.
-
1
def destroyed_by_association
-
@destroyed_by_association
-
end
-
-
# Returns whether or not this record has been changed in any way (including whether
-
# any of its nested autosave associations are likewise changed)
-
1
def changed_for_autosave?
-
new_record? || changed? || marked_for_destruction? || nested_records_changed_for_autosave?
-
end
-
-
1
private
-
-
# Returns the record for an association collection that should be validated
-
# or saved. If +autosave+ is +false+ only new records will be returned,
-
# unless the parent is/was a new record itself.
-
1
def associated_records_to_validate_or_save(association, new_record, autosave)
-
if new_record
-
association && association.target
-
elsif autosave
-
association.target.find_all { |record| record.changed_for_autosave? }
-
else
-
association.target.find_all { |record| record.new_record? }
-
end
-
end
-
-
# go through nested autosave associations that are loaded in memory (without loading
-
# any new ones), and return true if is changed for autosave
-
1
def nested_records_changed_for_autosave?
-
self.class.reflect_on_all_autosave_associations.any? do |reflection|
-
association = association_instance_get(reflection.name)
-
association && Array.wrap(association.target).any? { |a| a.changed_for_autosave? }
-
end
-
end
-
-
# Validate the association if <tt>:validate</tt> or <tt>:autosave</tt> is
-
# turned on for the association.
-
1
def validate_single_association(reflection)
-
association = association_instance_get(reflection.name)
-
record = association && association.reader
-
association_valid?(reflection, record) if record
-
end
-
-
# Validate the associated records if <tt>:validate</tt> or
-
# <tt>:autosave</tt> is turned on for the association specified by
-
# +reflection+.
-
1
def validate_collection_association(reflection)
-
if association = association_instance_get(reflection.name)
-
if records = associated_records_to_validate_or_save(association, new_record?, reflection.options[:autosave])
-
records.each { |record| association_valid?(reflection, record) }
-
end
-
end
-
end
-
-
# Returns whether or not the association is valid and applies any errors to
-
# the parent, <tt>self</tt>, if it wasn't. Skips any <tt>:autosave</tt>
-
# enabled records if they're marked_for_destruction? or destroyed.
-
1
def association_valid?(reflection, record)
-
return true if record.destroyed? || record.marked_for_destruction?
-
-
unless valid = record.valid?
-
if reflection.options[:autosave]
-
record.errors.each do |attribute, message|
-
attribute = "#{reflection.name}.#{attribute}"
-
errors[attribute] << message
-
errors[attribute].uniq!
-
end
-
else
-
errors.add(reflection.name)
-
end
-
end
-
valid
-
end
-
-
# Is used as a before_save callback to check while saving a collection
-
# association whether or not the parent was a new record before saving.
-
1
def before_save_collection_association
-
@new_record_before_save = new_record?
-
true
-
end
-
-
# Saves any new associated records, or all loaded autosave associations if
-
# <tt>:autosave</tt> is enabled on the association.
-
#
-
# In addition, it destroys all children that were marked for destruction
-
# with mark_for_destruction.
-
#
-
# This all happens inside a transaction, _if_ the Transactions module is included into
-
# ActiveRecord::Base after the AutosaveAssociation module, which it does by default.
-
1
def save_collection_association(reflection)
-
if association = association_instance_get(reflection.name)
-
autosave = reflection.options[:autosave]
-
-
if records = associated_records_to_validate_or_save(association, @new_record_before_save, autosave)
-
-
if autosave
-
records_to_destroy = records.select(&:marked_for_destruction?)
-
records_to_destroy.each { |record| association.destroy(record) }
-
records -= records_to_destroy
-
end
-
-
records.each do |record|
-
next if record.destroyed?
-
-
saved = true
-
-
if autosave != false && (@new_record_before_save || record.new_record?)
-
if autosave
-
saved = association.insert_record(record, false)
-
else
-
association.insert_record(record) unless reflection.nested?
-
end
-
elsif autosave
-
saved = record.save(:validate => false)
-
end
-
-
raise ActiveRecord::Rollback unless saved
-
end
-
end
-
-
# reconstruct the scope now that we know the owner's id
-
association.reset_scope if association.respond_to?(:reset_scope)
-
end
-
end
-
-
# Saves the associated record if it's new or <tt>:autosave</tt> is enabled
-
# on the association.
-
#
-
# In addition, it will destroy the association if it was marked for
-
# destruction with mark_for_destruction.
-
#
-
# This all happens inside a transaction, _if_ the Transactions module is included into
-
# ActiveRecord::Base after the AutosaveAssociation module, which it does by default.
-
1
def save_has_one_association(reflection)
-
association = association_instance_get(reflection.name)
-
record = association && association.load_target
-
if record && !record.destroyed?
-
autosave = reflection.options[:autosave]
-
-
if autosave && record.marked_for_destruction?
-
record.destroy
-
else
-
key = reflection.options[:primary_key] ? send(reflection.options[:primary_key]) : id
-
if autosave != false && (autosave || new_record? || record_changed?(reflection, record, key))
-
-
unless reflection.through_reflection
-
record[reflection.foreign_key] = key
-
end
-
-
saved = record.save(:validate => !autosave)
-
raise ActiveRecord::Rollback if !saved && autosave
-
saved
-
end
-
end
-
end
-
end
-
-
# If the record is new or it has changed, returns true.
-
1
def record_changed?(reflection, record, key)
-
record.new_record? || record[reflection.foreign_key] != key || record.attribute_changed?(reflection.foreign_key)
-
end
-
-
# Saves the associated record if it's new or <tt>:autosave</tt> is enabled.
-
#
-
# In addition, it will destroy the association if it was marked for destruction.
-
1
def save_belongs_to_association(reflection)
-
association = association_instance_get(reflection.name)
-
record = association && association.load_target
-
if record && !record.destroyed?
-
autosave = reflection.options[:autosave]
-
-
if autosave && record.marked_for_destruction?
-
self[reflection.foreign_key] = nil
-
record.destroy
-
elsif autosave != false
-
saved = record.save(:validate => !autosave) if record.new_record? || (autosave && record.changed_for_autosave?)
-
-
if association.updated?
-
association_id = record.send(reflection.options[:primary_key] || :id)
-
self[reflection.foreign_key] = association_id
-
association.loaded!
-
end
-
-
saved if autosave
-
end
-
end
-
end
-
end
-
end
-
1
require 'yaml'
-
1
require 'set'
-
1
require 'active_support/benchmarkable'
-
1
require 'active_support/dependencies'
-
1
require 'active_support/descendants_tracker'
-
1
require 'active_support/time'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/class/delegating_attributes'
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'active_support/core_ext/hash/deep_merge'
-
1
require 'active_support/core_ext/hash/slice'
-
1
require 'active_support/core_ext/string/behavior'
-
1
require 'active_support/core_ext/kernel/singleton_class'
-
1
require 'active_support/core_ext/module/introspection'
-
1
require 'active_support/core_ext/object/duplicable'
-
1
require 'active_support/core_ext/class/subclasses'
-
1
require 'arel'
-
1
require 'active_record/errors'
-
1
require 'active_record/log_subscriber'
-
1
require 'active_record/explain_subscriber'
-
1
require 'active_record/relation/delegation'
-
-
1
module ActiveRecord #:nodoc:
-
# = Active Record
-
#
-
# Active Record objects don't specify their attributes directly, but rather infer them from
-
# the table definition with which they're linked. Adding, removing, and changing attributes
-
# and their type is done directly in the database. Any change is instantly reflected in the
-
# Active Record objects. The mapping that binds a given Active Record class to a certain
-
# database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.
-
#
-
# See the mapping rules in table_name and the full example in link:files/activerecord/README_rdoc.html for more insight.
-
#
-
# == Creation
-
#
-
# Active Records accept constructor parameters either in a hash or as a block. The hash
-
# method is especially useful when you're receiving the data from somewhere else, like an
-
# HTTP request. It works like this:
-
#
-
# user = User.new(name: "David", occupation: "Code Artist")
-
# user.name # => "David"
-
#
-
# You can also use block initialization:
-
#
-
# user = User.new do |u|
-
# u.name = "David"
-
# u.occupation = "Code Artist"
-
# end
-
#
-
# And of course you can just create a bare object and specify the attributes after the fact:
-
#
-
# user = User.new
-
# user.name = "David"
-
# user.occupation = "Code Artist"
-
#
-
# == Conditions
-
#
-
# Conditions can either be specified as a string, array, or hash representing the WHERE-part of an SQL statement.
-
# The array form is to be used when the condition input is tainted and requires sanitization. The string form can
-
# be used for statements that don't involve tainted data. The hash form works much like the array form, except
-
# only equality and range is possible. Examples:
-
#
-
# class User < ActiveRecord::Base
-
# def self.authenticate_unsafely(user_name, password)
-
# where("user_name = '#{user_name}' AND password = '#{password}'").first
-
# end
-
#
-
# def self.authenticate_safely(user_name, password)
-
# where("user_name = ? AND password = ?", user_name, password).first
-
# end
-
#
-
# def self.authenticate_safely_simply(user_name, password)
-
# where(user_name: user_name, password: password).first
-
# end
-
# end
-
#
-
# The <tt>authenticate_unsafely</tt> method inserts the parameters directly into the query
-
# and is thus susceptible to SQL-injection attacks if the <tt>user_name</tt> and +password+
-
# parameters come directly from an HTTP request. The <tt>authenticate_safely</tt> and
-
# <tt>authenticate_safely_simply</tt> both will sanitize the <tt>user_name</tt> and +password+
-
# before inserting them in the query, which will ensure that an attacker can't escape the
-
# query and fake the login (or worse).
-
#
-
# When using multiple parameters in the conditions, it can easily become hard to read exactly
-
# what the fourth or fifth question mark is supposed to represent. In those cases, you can
-
# resort to named bind variables instead. That's done by replacing the question marks with
-
# symbols and supplying a hash with values for the matching symbol keys:
-
#
-
# Company.where(
-
# "id = :id AND name = :name AND division = :division AND created_at > :accounting_date",
-
# { id: 3, name: "37signals", division: "First", accounting_date: '2005-01-01' }
-
# ).first
-
#
-
# Similarly, a simple hash without a statement will generate conditions based on equality with the SQL AND
-
# operator. For instance:
-
#
-
# Student.where(first_name: "Harvey", status: 1)
-
# Student.where(params[:student])
-
#
-
# A range may be used in the hash to use the SQL BETWEEN operator:
-
#
-
# Student.where(grade: 9..12)
-
#
-
# An array may be used in the hash to use the SQL IN operator:
-
#
-
# Student.where(grade: [9,11,12])
-
#
-
# When joining tables, nested hashes or keys written in the form 'table_name.column_name'
-
# can be used to qualify the table name of a particular condition. For instance:
-
#
-
# Student.joins(:schools).where(schools: { category: 'public' })
-
# Student.joins(:schools).where('schools.category' => 'public' )
-
#
-
# == Overwriting default accessors
-
#
-
# All column values are automatically available through basic accessors on the Active Record
-
# object, but sometimes you want to specialize this behavior. This can be done by overwriting
-
# the default accessors (using the same name as the attribute) and calling
-
# <tt>read_attribute(attr_name)</tt> and <tt>write_attribute(attr_name, value)</tt> to actually
-
# change things.
-
#
-
# class Song < ActiveRecord::Base
-
# # Uses an integer of seconds to hold the length of the song
-
#
-
# def length=(minutes)
-
# write_attribute(:length, minutes.to_i * 60)
-
# end
-
#
-
# def length
-
# read_attribute(:length) / 60
-
# end
-
# end
-
#
-
# You can alternatively use <tt>self[:attribute]=(value)</tt> and <tt>self[:attribute]</tt>
-
# instead of <tt>write_attribute(:attribute, value)</tt> and <tt>read_attribute(:attribute)</tt>.
-
#
-
# == Attribute query methods
-
#
-
# In addition to the basic accessors, query methods are also automatically available on the Active Record object.
-
# Query methods allow you to test whether an attribute value is present.
-
#
-
# For example, an Active Record User with the <tt>name</tt> attribute has a <tt>name?</tt> method that you can call
-
# to determine whether the user has a name:
-
#
-
# user = User.new(name: "David")
-
# user.name? # => true
-
#
-
# anonymous = User.new(name: "")
-
# anonymous.name? # => false
-
#
-
# == Accessing attributes before they have been typecasted
-
#
-
# Sometimes you want to be able to read the raw attribute data without having the column-determined
-
# typecast run its course first. That can be done by using the <tt><attribute>_before_type_cast</tt>
-
# accessors that all attributes have. For example, if your Account model has a <tt>balance</tt> attribute,
-
# you can call <tt>account.balance_before_type_cast</tt> or <tt>account.id_before_type_cast</tt>.
-
#
-
# This is especially useful in validation situations where the user might supply a string for an
-
# integer field and you want to display the original string back in an error message. Accessing the
-
# attribute normally would typecast the string to 0, which isn't what you want.
-
#
-
# == Dynamic attribute-based finders
-
#
-
# Dynamic attribute-based finders are a mildly deprecated way of getting (and/or creating) objects
-
# by simple queries without turning to SQL. They work by appending the name of an attribute
-
# to <tt>find_by_</tt> like <tt>Person.find_by_user_name</tt>.
-
# Instead of writing <tt>Person.find_by(user_name: user_name)</tt>, you can use
-
# <tt>Person.find_by_user_name(user_name)</tt>.
-
#
-
# It's possible to add an exclamation point (!) on the end of the dynamic finders to get them to raise an
-
# <tt>ActiveRecord::RecordNotFound</tt> error if they do not return any records,
-
# like <tt>Person.find_by_last_name!</tt>.
-
#
-
# It's also possible to use multiple attributes in the same find by separating them with "_and_".
-
#
-
# Person.find_by(user_name: user_name, password: password)
-
# Person.find_by_user_name_and_password(user_name, password) # with dynamic finder
-
#
-
# It's even possible to call these dynamic finder methods on relations and named scopes.
-
#
-
# Payment.order("created_on").find_by_amount(50)
-
#
-
# == Saving arrays, hashes, and other non-mappable objects in text columns
-
#
-
# Active Record can serialize any object in text columns using YAML. To do so, you must
-
# specify this with a call to the class method +serialize+.
-
# This makes it possible to store arrays, hashes, and other non-mappable objects without doing
-
# any additional work.
-
#
-
# class User < ActiveRecord::Base
-
# serialize :preferences
-
# end
-
#
-
# user = User.create(preferences: { "background" => "black", "display" => large })
-
# User.find(user.id).preferences # => { "background" => "black", "display" => large }
-
#
-
# You can also specify a class option as the second parameter that'll raise an exception
-
# if a serialized object is retrieved as a descendant of a class not in the hierarchy.
-
#
-
# class User < ActiveRecord::Base
-
# serialize :preferences, Hash
-
# end
-
#
-
# user = User.create(preferences: %w( one two three ))
-
# User.find(user.id).preferences # raises SerializationTypeMismatch
-
#
-
# When you specify a class option, the default value for that attribute will be a new
-
# instance of that class.
-
#
-
# class User < ActiveRecord::Base
-
# serialize :preferences, OpenStruct
-
# end
-
#
-
# user = User.new
-
# user.preferences.theme_color = "red"
-
#
-
#
-
# == Single table inheritance
-
#
-
# Active Record allows inheritance by storing the name of the class in a column that by
-
# default is named "type" (can be changed by overwriting <tt>Base.inheritance_column</tt>).
-
# This means that an inheritance looking like this:
-
#
-
# class Company < ActiveRecord::Base; end
-
# class Firm < Company; end
-
# class Client < Company; end
-
# class PriorityClient < Client; end
-
#
-
# When you do <tt>Firm.create(name: "37signals")</tt>, this record will be saved in
-
# the companies table with type = "Firm". You can then fetch this row again using
-
# <tt>Company.where(name: '37signals').first</tt> and it will return a Firm object.
-
#
-
# If you don't have a type column defined in your table, single-table inheritance won't
-
# be triggered. In that case, it'll work just like normal subclasses with no special magic
-
# for differentiating between them or reloading the right type with find.
-
#
-
# Note, all the attributes for all the cases are kept in the same table. Read more:
-
# http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html
-
#
-
# == Connection to multiple databases in different models
-
#
-
# Connections are usually created through ActiveRecord::Base.establish_connection and retrieved
-
# by ActiveRecord::Base.connection. All classes inheriting from ActiveRecord::Base will use this
-
# connection. But you can also set a class-specific connection. For example, if Course is an
-
# ActiveRecord::Base, but resides in a different database, you can just say <tt>Course.establish_connection</tt>
-
# and Course and all of its subclasses will use this connection instead.
-
#
-
# This feature is implemented by keeping a connection pool in ActiveRecord::Base that is
-
# a Hash indexed by the class. If a connection is requested, the retrieve_connection method
-
# will go up the class-hierarchy until a connection is found in the connection pool.
-
#
-
# == Exceptions
-
#
-
# * ActiveRecordError - Generic error class and superclass of all other errors raised by Active Record.
-
# * AdapterNotSpecified - The configuration hash used in <tt>establish_connection</tt> didn't include an
-
# <tt>:adapter</tt> key.
-
# * AdapterNotFound - The <tt>:adapter</tt> key used in <tt>establish_connection</tt> specified a
-
# non-existent adapter
-
# (or a bad spelling of an existing one).
-
# * AssociationTypeMismatch - The object assigned to the association wasn't of the type
-
# specified in the association definition.
-
# * AttributeAssignmentError - An error occurred while doing a mass assignment through the
-
# <tt>attributes=</tt> method.
-
# You can inspect the +attribute+ property of the exception object to determine which attribute
-
# triggered the error.
-
# * ConnectionNotEstablished - No connection has been established. Use <tt>establish_connection</tt>
-
# before querying.
-
# * MultiparameterAssignmentErrors - Collection of errors that occurred during a mass assignment using the
-
# <tt>attributes=</tt> method. The +errors+ property of this exception contains an array of
-
# AttributeAssignmentError
-
# objects that should be inspected to determine which attributes triggered the errors.
-
# * RecordInvalid - raised by save! and create! when the record is invalid.
-
# * RecordNotFound - No record responded to the +find+ method. Either the row with the given ID doesn't exist
-
# or the row didn't meet the additional restrictions. Some +find+ calls do not raise this exception to signal
-
# nothing was found, please check its documentation for further details.
-
# * SerializationTypeMismatch - The serialized object wasn't of the class specified as the second parameter.
-
# * StatementInvalid - The database server rejected the SQL statement. The precise error is added in the message.
-
#
-
# *Note*: The attributes listed are class-level attributes (accessible from both the class and instance level).
-
# So it's possible to assign a logger to the class through <tt>Base.logger=</tt> which will then be used by all
-
# instances in the current object space.
-
1
class Base
-
1
extend ActiveModel::Naming
-
-
1
extend ActiveSupport::Benchmarkable
-
1
extend ActiveSupport::DescendantsTracker
-
-
1
extend ConnectionHandling
-
1
extend QueryCache::ClassMethods
-
1
extend Querying
-
1
extend Translation
-
1
extend DynamicMatchers
-
1
extend Explain
-
1
extend Enum
-
1
extend Delegation::DelegateCache
-
-
1
include Core
-
1
include Persistence
-
1
include NoTouching
-
1
include ReadonlyAttributes
-
1
include ModelSchema
-
1
include Inheritance
-
1
include Scoping
-
1
include Sanitization
-
1
include AttributeAssignment
-
1
include ActiveModel::Conversion
-
1
include Integration
-
1
include Validations
-
1
include CounterCache
-
1
include Locking::Optimistic
-
1
include Locking::Pessimistic
-
1
include AttributeMethods
-
1
include Callbacks
-
1
include Timestamp
-
1
include Associations
-
1
include ActiveModel::SecurePassword
-
1
include AutosaveAssociation
-
1
include NestedAttributes
-
1
include Aggregations
-
1
include Transactions
-
1
include Reflection
-
1
include Serialization
-
1
include Store
-
end
-
-
1
ActiveSupport.run_load_hooks(:active_record, Base)
-
end
-
1
module ActiveRecord
-
# = Active Record Callbacks
-
#
-
# Callbacks are hooks into the life cycle of an Active Record object that allow you to trigger logic
-
# before or after an alteration of the object state. This can be used to make sure that associated and
-
# dependent objects are deleted when +destroy+ is called (by overwriting +before_destroy+) or to massage attributes
-
# before they're validated (by overwriting +before_validation+). As an example of the callbacks initiated, consider
-
# the <tt>Base#save</tt> call for a new record:
-
#
-
# * (-) <tt>save</tt>
-
# * (-) <tt>valid</tt>
-
# * (1) <tt>before_validation</tt>
-
# * (-) <tt>validate</tt>
-
# * (2) <tt>after_validation</tt>
-
# * (3) <tt>before_save</tt>
-
# * (4) <tt>before_create</tt>
-
# * (-) <tt>create</tt>
-
# * (5) <tt>after_create</tt>
-
# * (6) <tt>after_save</tt>
-
# * (7) <tt>after_commit</tt>
-
#
-
# Also, an <tt>after_rollback</tt> callback can be configured to be triggered whenever a rollback is issued.
-
# Check out <tt>ActiveRecord::Transactions</tt> for more details about <tt>after_commit</tt> and
-
# <tt>after_rollback</tt>.
-
#
-
# Additionally, an <tt>after_touch</tt> callback is triggered whenever an
-
# object is touched.
-
#
-
# Lastly an <tt>after_find</tt> and <tt>after_initialize</tt> callback is triggered for each object that
-
# is found and instantiated by a finder, with <tt>after_initialize</tt> being triggered after new objects
-
# are instantiated as well.
-
#
-
# There are nineteen callbacks in total, which give you immense power to react and prepare for each state in the
-
# Active Record life cycle. The sequence for calling <tt>Base#save</tt> for an existing record is similar,
-
# except that each <tt>_create</tt> callback is replaced by the corresponding <tt>_update</tt> callback.
-
#
-
# Examples:
-
# class CreditCard < ActiveRecord::Base
-
# # Strip everything but digits, so the user can specify "555 234 34" or
-
# # "5552-3434" and both will mean "55523434"
-
# before_validation(on: :create) do
-
# self.number = number.gsub(/[^0-9]/, "") if attribute_present?("number")
-
# end
-
# end
-
#
-
# class Subscription < ActiveRecord::Base
-
# before_create :record_signup
-
#
-
# private
-
# def record_signup
-
# self.signed_up_on = Date.today
-
# end
-
# end
-
#
-
# class Firm < ActiveRecord::Base
-
# # Destroys the associated clients and people when the firm is destroyed
-
# before_destroy { |record| Person.destroy_all "firm_id = #{record.id}" }
-
# before_destroy { |record| Client.destroy_all "client_of = #{record.id}" }
-
# end
-
#
-
# == Inheritable callback queues
-
#
-
# Besides the overwritable callback methods, it's also possible to register callbacks through the
-
# use of the callback macros. Their main advantage is that the macros add behavior into a callback
-
# queue that is kept intact down through an inheritance hierarchy.
-
#
-
# class Topic < ActiveRecord::Base
-
# before_destroy :destroy_author
-
# end
-
#
-
# class Reply < Topic
-
# before_destroy :destroy_readers
-
# end
-
#
-
# Now, when <tt>Topic#destroy</tt> is run only +destroy_author+ is called. When <tt>Reply#destroy</tt> is
-
# run, both +destroy_author+ and +destroy_readers+ are called. Contrast this to the following situation
-
# where the +before_destroy+ method is overridden:
-
#
-
# class Topic < ActiveRecord::Base
-
# def before_destroy() destroy_author end
-
# end
-
#
-
# class Reply < Topic
-
# def before_destroy() destroy_readers end
-
# end
-
#
-
# In that case, <tt>Reply#destroy</tt> would only run +destroy_readers+ and _not_ +destroy_author+.
-
# So, use the callback macros when you want to ensure that a certain callback is called for the entire
-
# hierarchy, and use the regular overwritable methods when you want to leave it up to each descendant
-
# to decide whether they want to call +super+ and trigger the inherited callbacks.
-
#
-
# *IMPORTANT:* In order for inheritance to work for the callback queues, you must specify the
-
# callbacks before specifying the associations. Otherwise, you might trigger the loading of a
-
# child before the parent has registered the callbacks and they won't be inherited.
-
#
-
# == Types of callbacks
-
#
-
# There are four types of callbacks accepted by the callback macros: Method references (symbol), callback objects,
-
# inline methods (using a proc), and inline eval methods (using a string). Method references and callback objects
-
# are the recommended approaches, inline methods using a proc are sometimes appropriate (such as for
-
# creating mix-ins), and inline eval methods are deprecated.
-
#
-
# The method reference callbacks work by specifying a protected or private method available in the object, like this:
-
#
-
# class Topic < ActiveRecord::Base
-
# before_destroy :delete_parents
-
#
-
# private
-
# def delete_parents
-
# self.class.delete_all "parent_id = #{id}"
-
# end
-
# end
-
#
-
# The callback objects have methods named after the callback called with the record as the only parameter, such as:
-
#
-
# class BankAccount < ActiveRecord::Base
-
# before_save EncryptionWrapper.new
-
# after_save EncryptionWrapper.new
-
# after_initialize EncryptionWrapper.new
-
# end
-
#
-
# class EncryptionWrapper
-
# def before_save(record)
-
# record.credit_card_number = encrypt(record.credit_card_number)
-
# end
-
#
-
# def after_save(record)
-
# record.credit_card_number = decrypt(record.credit_card_number)
-
# end
-
#
-
# alias_method :after_initialize, :after_save
-
#
-
# private
-
# def encrypt(value)
-
# # Secrecy is committed
-
# end
-
#
-
# def decrypt(value)
-
# # Secrecy is unveiled
-
# end
-
# end
-
#
-
# So you specify the object you want messaged on a given callback. When that callback is triggered, the object has
-
# a method by the name of the callback messaged. You can make these callbacks more flexible by passing in other
-
# initialization data such as the name of the attribute to work with:
-
#
-
# class BankAccount < ActiveRecord::Base
-
# before_save EncryptionWrapper.new("credit_card_number")
-
# after_save EncryptionWrapper.new("credit_card_number")
-
# after_initialize EncryptionWrapper.new("credit_card_number")
-
# end
-
#
-
# class EncryptionWrapper
-
# def initialize(attribute)
-
# @attribute = attribute
-
# end
-
#
-
# def before_save(record)
-
# record.send("#{@attribute}=", encrypt(record.send("#{@attribute}")))
-
# end
-
#
-
# def after_save(record)
-
# record.send("#{@attribute}=", decrypt(record.send("#{@attribute}")))
-
# end
-
#
-
# alias_method :after_initialize, :after_save
-
#
-
# private
-
# def encrypt(value)
-
# # Secrecy is committed
-
# end
-
#
-
# def decrypt(value)
-
# # Secrecy is unveiled
-
# end
-
# end
-
#
-
# The callback macros usually accept a symbol for the method they're supposed to run, but you can also
-
# pass a "method string", which will then be evaluated within the binding of the callback. Example:
-
#
-
# class Topic < ActiveRecord::Base
-
# before_destroy 'self.class.delete_all "parent_id = #{id}"'
-
# end
-
#
-
# Notice that single quotes (') are used so the <tt>#{id}</tt> part isn't evaluated until the callback
-
# is triggered. Also note that these inline callbacks can be stacked just like the regular ones:
-
#
-
# class Topic < ActiveRecord::Base
-
# before_destroy 'self.class.delete_all "parent_id = #{id}"',
-
# 'puts "Evaluated after parents are destroyed"'
-
# end
-
#
-
# == <tt>before_validation*</tt> returning statements
-
#
-
# If the returning value of a +before_validation+ callback can be evaluated to +false+, the process will be
-
# aborted and <tt>Base#save</tt> will return +false+. If Base#save! is called it will raise a
-
# ActiveRecord::RecordInvalid exception. Nothing will be appended to the errors object.
-
#
-
# == Canceling callbacks
-
#
-
# If a <tt>before_*</tt> callback returns +false+, all the later callbacks and the associated action are
-
# cancelled. If an <tt>after_*</tt> callback returns +false+, all the later callbacks are cancelled.
-
# Callbacks are generally run in the order they are defined, with the exception of callbacks defined as
-
# methods on the model, which are called last.
-
#
-
# == Ordering callbacks
-
#
-
# Sometimes the code needs that the callbacks execute in a specific order. For example, a +before_destroy+
-
# callback (+log_children+ in this case) should be executed before the children get destroyed by the +dependent: destroy+ option.
-
#
-
# Let's look at the code below:
-
#
-
# class Topic < ActiveRecord::Base
-
# has_many :children, dependent: destroy
-
#
-
# before_destroy :log_children
-
#
-
# private
-
# def log_children
-
# # Child processing
-
# end
-
# end
-
#
-
# In this case, the problem is that when the +before_destroy+ callback is executed, the children are not available
-
# because the +destroy+ callback gets executed first. You can use the +prepend+ option on the +before_destroy+ callback to avoid this.
-
#
-
# class Topic < ActiveRecord::Base
-
# has_many :children, dependent: destroy
-
#
-
# before_destroy :log_children, prepend: true
-
#
-
# private
-
# def log_children
-
# # Child processing
-
# end
-
# end
-
#
-
# This way, the +before_destroy+ gets executed before the <tt>dependent: destroy</tt> is called, and the data is still available.
-
#
-
# == Transactions
-
#
-
# The entire callback chain of a +save+, <tt>save!</tt>, or +destroy+ call runs
-
# within a transaction. That includes <tt>after_*</tt> hooks. If everything
-
# goes fine a COMMIT is executed once the chain has been completed.
-
#
-
# If a <tt>before_*</tt> callback cancels the action a ROLLBACK is issued. You
-
# can also trigger a ROLLBACK raising an exception in any of the callbacks,
-
# including <tt>after_*</tt> hooks. Note, however, that in that case the client
-
# needs to be aware of it because an ordinary +save+ will raise such exception
-
# instead of quietly returning +false+.
-
#
-
# == Debugging callbacks
-
#
-
# The callback chain is accessible via the <tt>_*_callbacks</tt> method on an object. ActiveModel Callbacks support
-
# <tt>:before</tt>, <tt>:after</tt> and <tt>:around</tt> as values for the <tt>kind</tt> property. The <tt>kind</tt> property
-
# defines what part of the chain the callback runs in.
-
#
-
# To find all callbacks in the before_save callback chain:
-
#
-
# Topic._save_callbacks.select { |cb| cb.kind.eql?(:before) }
-
#
-
# Returns an array of callback objects that form the before_save chain.
-
#
-
# To further check if the before_save chain contains a proc defined as <tt>rest_when_dead</tt> use the <tt>filter</tt> property of the callback object:
-
#
-
# Topic._save_callbacks.select { |cb| cb.kind.eql?(:before) }.collect(&:filter).include?(:rest_when_dead)
-
#
-
# Returns true or false depending on whether the proc is contained in the before_save callback chain on a Topic model.
-
#
-
1
module Callbacks
-
1
extend ActiveSupport::Concern
-
-
1
CALLBACKS = [
-
:after_initialize, :after_find, :after_touch, :before_validation, :after_validation,
-
:before_save, :around_save, :after_save, :before_create, :around_create,
-
:after_create, :before_update, :around_update, :after_update,
-
:before_destroy, :around_destroy, :after_destroy, :after_commit, :after_rollback
-
]
-
-
1
module ClassMethods
-
1
include ActiveModel::Callbacks
-
end
-
-
1
included do
-
1
include ActiveModel::Validations::Callbacks
-
-
1
define_model_callbacks :initialize, :find, :touch, :only => :after
-
1
define_model_callbacks :save, :create, :update, :destroy
-
end
-
-
1
def destroy #:nodoc:
-
run_callbacks(:destroy) { super }
-
end
-
-
1
def touch(*) #:nodoc:
-
run_callbacks(:touch) { super }
-
end
-
-
1
private
-
-
1
def create_or_update #:nodoc:
-
run_callbacks(:save) { super }
-
end
-
-
1
def create_record #:nodoc:
-
run_callbacks(:create) { super }
-
end
-
-
1
def update_record(*) #:nodoc:
-
run_callbacks(:update) { super }
-
end
-
end
-
end
-
1
require 'thread'
-
1
require 'thread_safe'
-
1
require 'monitor'
-
1
require 'set'
-
-
1
module ActiveRecord
-
# Raised when a connection could not be obtained within the connection
-
# acquisition timeout period: because max connections in pool
-
# are in use.
-
1
class ConnectionTimeoutError < ConnectionNotEstablished
-
end
-
-
1
module ConnectionAdapters
-
# Connection pool base class for managing Active Record database
-
# connections.
-
#
-
# == Introduction
-
#
-
# A connection pool synchronizes thread access to a limited number of
-
# database connections. The basic idea is that each thread checks out a
-
# database connection from the pool, uses that connection, and checks the
-
# connection back in. ConnectionPool is completely thread-safe, and will
-
# ensure that a connection cannot be used by two threads at the same time,
-
# as long as ConnectionPool's contract is correctly followed. It will also
-
# handle cases in which there are more threads than connections: if all
-
# connections have been checked out, and a thread tries to checkout a
-
# connection anyway, then ConnectionPool will wait until some other thread
-
# has checked in a connection.
-
#
-
# == Obtaining (checking out) a connection
-
#
-
# Connections can be obtained and used from a connection pool in several
-
# ways:
-
#
-
# 1. Simply use ActiveRecord::Base.connection as with Active Record 2.1 and
-
# earlier (pre-connection-pooling). Eventually, when you're done with
-
# the connection(s) and wish it to be returned to the pool, you call
-
# ActiveRecord::Base.clear_active_connections!. This will be the
-
# default behavior for Active Record when used in conjunction with
-
# Action Pack's request handling cycle.
-
# 2. Manually check out a connection from the pool with
-
# ActiveRecord::Base.connection_pool.checkout. You are responsible for
-
# returning this connection to the pool when finished by calling
-
# ActiveRecord::Base.connection_pool.checkin(connection).
-
# 3. Use ActiveRecord::Base.connection_pool.with_connection(&block), which
-
# obtains a connection, yields it as the sole argument to the block,
-
# and returns it to the pool after the block completes.
-
#
-
# Connections in the pool are actually AbstractAdapter objects (or objects
-
# compatible with AbstractAdapter's interface).
-
#
-
# == Options
-
#
-
# There are several connection-pooling-related options that you can add to
-
# your database connection configuration:
-
#
-
# * +pool+: number indicating size of connection pool (default 5)
-
# * +checkout_timeout+: number of seconds to block and wait for a connection
-
# before giving up and raising a timeout error (default 5 seconds).
-
# * +reaping_frequency+: frequency in seconds to periodically run the
-
# Reaper, which attempts to find and close dead connections, which can
-
# occur if a programmer forgets to close a connection at the end of a
-
# thread or a thread dies unexpectedly. (Default nil, which means don't
-
# run the Reaper).
-
# * +dead_connection_timeout+: number of seconds from last checkout
-
# after which the Reaper will consider a connection reapable. (default
-
# 5 seconds).
-
1
class ConnectionPool
-
# Threadsafe, fair, FIFO queue. Meant to be used by ConnectionPool
-
# with which it shares a Monitor. But could be a generic Queue.
-
#
-
# The Queue in stdlib's 'thread' could replace this class except
-
# stdlib's doesn't support waiting with a timeout.
-
1
class Queue
-
1
def initialize(lock = Monitor.new)
-
1
@lock = lock
-
1
@cond = @lock.new_cond
-
1
@num_waiting = 0
-
1
@queue = []
-
end
-
-
# Test if any threads are currently waiting on the queue.
-
1
def any_waiting?
-
synchronize do
-
@num_waiting > 0
-
end
-
end
-
-
# Returns the number of threads currently waiting on this
-
# queue.
-
1
def num_waiting
-
synchronize do
-
@num_waiting
-
end
-
end
-
-
# Add +element+ to the queue. Never blocks.
-
1
def add(element)
-
synchronize do
-
@queue.push element
-
@cond.signal
-
end
-
end
-
-
# If +element+ is in the queue, remove and return it, or nil.
-
1
def delete(element)
-
synchronize do
-
@queue.delete(element)
-
end
-
end
-
-
# Remove all elements from the queue.
-
1
def clear
-
synchronize do
-
@queue.clear
-
end
-
end
-
-
# Remove the head of the queue.
-
#
-
# If +timeout+ is not given, remove and return the head the
-
# queue if the number of available elements is strictly
-
# greater than the number of threads currently waiting (that
-
# is, don't jump ahead in line). Otherwise, return nil.
-
#
-
# If +timeout+ is given, block if it there is no element
-
# available, waiting up to +timeout+ seconds for an element to
-
# become available.
-
#
-
# Raises:
-
# - ConnectionTimeoutError if +timeout+ is given and no element
-
# becomes available after +timeout+ seconds,
-
1
def poll(timeout = nil)
-
1
synchronize do
-
1
if timeout
-
no_wait_poll || wait_poll(timeout)
-
else
-
1
no_wait_poll
-
end
-
end
-
end
-
-
1
private
-
-
1
def synchronize(&block)
-
1
@lock.synchronize(&block)
-
end
-
-
# Test if the queue currently contains any elements.
-
1
def any?
-
!@queue.empty?
-
end
-
-
# A thread can remove an element from the queue without
-
# waiting if an only if the number of currently available
-
# connections is strictly greater than the number of waiting
-
# threads.
-
1
def can_remove_no_wait?
-
1
@queue.size > @num_waiting
-
end
-
-
# Removes and returns the head of the queue if possible, or nil.
-
1
def remove
-
@queue.shift
-
end
-
-
# Remove and return the head the queue if the number of
-
# available elements is strictly greater than the number of
-
# threads currently waiting. Otherwise, return nil.
-
1
def no_wait_poll
-
1
remove if can_remove_no_wait?
-
end
-
-
# Waits on the queue up to +timeout+ seconds, then removes and
-
# returns the head of the queue.
-
1
def wait_poll(timeout)
-
@num_waiting += 1
-
-
t0 = Time.now
-
elapsed = 0
-
loop do
-
@cond.wait(timeout - elapsed)
-
-
return remove if any?
-
-
elapsed = Time.now - t0
-
if elapsed >= timeout
-
msg = 'could not obtain a database connection within %0.3f seconds (waited %0.3f seconds)' %
-
[timeout, elapsed]
-
raise ConnectionTimeoutError, msg
-
end
-
end
-
ensure
-
@num_waiting -= 1
-
end
-
end
-
-
# Every +frequency+ seconds, the reaper will call +reap+ on +pool+.
-
# A reaper instantiated with a nil frequency will never reap the
-
# connection pool.
-
#
-
# Configure the frequency by setting "reaping_frequency" in your
-
# database yaml file.
-
1
class Reaper
-
1
attr_reader :pool, :frequency
-
-
1
def initialize(pool, frequency)
-
1
@pool = pool
-
1
@frequency = frequency
-
end
-
-
1
def run
-
1
return unless frequency
-
Thread.new(frequency, pool) { |t, p|
-
while true
-
sleep t
-
p.reap
-
end
-
}
-
end
-
end
-
-
1
include MonitorMixin
-
-
1
attr_accessor :automatic_reconnect, :checkout_timeout, :dead_connection_timeout
-
1
attr_reader :spec, :connections, :size, :reaper
-
-
# Creates a new ConnectionPool object. +spec+ is a ConnectionSpecification
-
# object which describes database connection information (e.g. adapter,
-
# host name, username, password, etc), as well as the maximum size for
-
# this ConnectionPool.
-
#
-
# The default ConnectionPool maximum size is 5.
-
1
def initialize(spec)
-
1
super()
-
-
1
@spec = spec
-
-
1
@checkout_timeout = spec.config[:checkout_timeout] || 5
-
1
@dead_connection_timeout = spec.config[:dead_connection_timeout] || 5
-
1
@reaper = Reaper.new self, spec.config[:reaping_frequency]
-
1
@reaper.run
-
-
# default max pool size to 5
-
1
@size = (spec.config[:pool] && spec.config[:pool].to_i) || 5
-
-
# The cache of reserved connections mapped to threads
-
1
@reserved_connections = ThreadSafe::Cache.new(:initial_capacity => @size)
-
-
1
@connections = []
-
1
@automatic_reconnect = true
-
-
1
@available = Queue.new self
-
end
-
-
# Retrieve the connection associated with the current thread, or call
-
# #checkout to obtain one if necessary.
-
#
-
# #connection can be called any number of times; the connection is
-
# held in a hash keyed by the thread id.
-
1
def connection
-
# this is correctly done double-checked locking
-
# (ThreadSafe::Cache's lookups have volatile semantics)
-
@reserved_connections[current_connection_id] || synchronize do
-
1
@reserved_connections[current_connection_id] ||= checkout
-
1
end
-
end
-
-
# Is there an open connection that is being used for the current thread?
-
1
def active_connection?
-
synchronize do
-
@reserved_connections.fetch(current_connection_id) {
-
return false
-
}.in_use?
-
end
-
end
-
-
# Signal that the thread is finished with the current connection.
-
# #release_connection releases the connection-thread association
-
# and returns the connection to the pool.
-
1
def release_connection(with_id = current_connection_id)
-
synchronize do
-
conn = @reserved_connections.delete(with_id)
-
checkin conn if conn
-
end
-
end
-
-
# If a connection already exists yield it to the block. If no connection
-
# exists checkout a connection, yield it to the block, and checkin the
-
# connection when finished.
-
1
def with_connection
-
connection_id = current_connection_id
-
fresh_connection = true unless active_connection?
-
yield connection
-
ensure
-
release_connection(connection_id) if fresh_connection
-
end
-
-
# Returns true if a connection has already been opened.
-
1
def connected?
-
2
synchronize { @connections.any? }
-
end
-
-
# Disconnects all connections in the pool, and clears the pool.
-
1
def disconnect!
-
synchronize do
-
@reserved_connections.clear
-
@connections.each do |conn|
-
checkin conn
-
conn.disconnect!
-
end
-
@connections = []
-
@available.clear
-
end
-
end
-
-
# Clears the cache which maps classes.
-
1
def clear_reloadable_connections!
-
synchronize do
-
@reserved_connections.clear
-
@connections.each do |conn|
-
checkin conn
-
conn.disconnect! if conn.requires_reloading?
-
end
-
@connections.delete_if do |conn|
-
conn.requires_reloading?
-
end
-
@available.clear
-
@connections.each do |conn|
-
@available.add conn
-
end
-
end
-
end
-
-
# Check-out a database connection from the pool, indicating that you want
-
# to use it. You should call #checkin when you no longer need this.
-
#
-
# This is done by either returning and leasing existing connection, or by
-
# creating a new connection and leasing it.
-
#
-
# If all connections are leased and the pool is at capacity (meaning the
-
# number of currently leased connections is greater than or equal to the
-
# size limit set), an ActiveRecord::ConnectionTimeoutError exception will be raised.
-
#
-
# Returns: an AbstractAdapter object.
-
#
-
# Raises:
-
# - ConnectionTimeoutError: no connection can be obtained from the pool.
-
1
def checkout
-
1
synchronize do
-
1
conn = acquire_connection
-
1
conn.lease
-
1
checkout_and_verify(conn)
-
end
-
end
-
-
# Check-in a database connection back into the pool, indicating that you
-
# no longer need this connection.
-
#
-
# +conn+: an AbstractAdapter object, which was obtained by earlier by
-
# calling +checkout+ on this pool.
-
1
def checkin(conn)
-
synchronize do
-
conn.run_callbacks :checkin do
-
conn.expire
-
end
-
-
release conn
-
-
@available.add conn
-
end
-
end
-
-
# Remove a connection from the connection pool. The connection will
-
# remain open and active but will no longer be managed by this pool.
-
1
def remove(conn)
-
synchronize do
-
@connections.delete conn
-
@available.delete conn
-
-
# FIXME: we might want to store the key on the connection so that removing
-
# from the reserved hash will be a little easier.
-
release conn
-
-
@available.add checkout_new_connection if @available.any_waiting?
-
end
-
end
-
-
# Removes dead connections from the pool. A dead connection can occur
-
# if a programmer forgets to close a connection at the end of a thread
-
# or a thread dies unexpectedly.
-
1
def reap
-
synchronize do
-
stale = Time.now - @dead_connection_timeout
-
connections.dup.each do |conn|
-
if conn.in_use? && stale > conn.last_use && !conn.active_threadsafe?
-
remove conn
-
end
-
end
-
end
-
end
-
-
1
private
-
-
# Acquire a connection by one of 1) immediately removing one
-
# from the queue of available connections, 2) creating a new
-
# connection if the pool is not at capacity, 3) waiting on the
-
# queue for a connection to become available.
-
#
-
# Raises:
-
# - ConnectionTimeoutError if a connection could not be acquired
-
1
def acquire_connection
-
1
if conn = @available.poll
-
conn
-
1
elsif @connections.size < @size
-
1
checkout_new_connection
-
else
-
@available.poll(@checkout_timeout)
-
end
-
end
-
-
1
def release(conn)
-
thread_id = if @reserved_connections[current_connection_id] == conn
-
current_connection_id
-
else
-
@reserved_connections.keys.find { |k|
-
@reserved_connections[k] == conn
-
}
-
end
-
-
@reserved_connections.delete thread_id if thread_id
-
end
-
-
1
def new_connection
-
1
Base.send(spec.adapter_method, spec.config)
-
end
-
-
1
def current_connection_id #:nodoc:
-
2
Base.connection_id ||= Thread.current.object_id
-
end
-
-
1
def checkout_new_connection
-
1
raise ConnectionNotEstablished unless @automatic_reconnect
-
-
1
c = new_connection
-
1
c.pool = self
-
1
@connections << c
-
1
c
-
end
-
-
1
def checkout_and_verify(c)
-
1
c.run_callbacks :checkout do
-
1
c.verify!
-
end
-
1
c
-
end
-
end
-
-
# ConnectionHandler is a collection of ConnectionPool objects. It is used
-
# for keeping separate connection pools for Active Record models that connect
-
# to different databases.
-
#
-
# For example, suppose that you have 5 models, with the following hierarchy:
-
#
-
# |
-
# +-- Book
-
# | |
-
# | +-- ScaryBook
-
# | +-- GoodBook
-
# +-- Author
-
# +-- BankAccount
-
#
-
# Suppose that Book is to connect to a separate database (i.e. one other
-
# than the default database). Then Book, ScaryBook and GoodBook will all use
-
# the same connection pool. Likewise, Author and BankAccount will use the
-
# same connection pool. However, the connection pool used by Author/BankAccount
-
# is not the same as the one used by Book/ScaryBook/GoodBook.
-
#
-
# Normally there is only a single ConnectionHandler instance, accessible via
-
# ActiveRecord::Base.connection_handler. Active Record models use this to
-
# determine the connection pool that they should use.
-
1
class ConnectionHandler
-
1
def initialize
-
# These caches are keyed by klass.name, NOT klass. Keying them by klass
-
# alone would lead to memory leaks in development mode as all previous
-
# instances of the class would stay in memory.
-
1
@owner_to_pool = ThreadSafe::Cache.new(:initial_capacity => 2) do |h,k|
-
1
h[k] = ThreadSafe::Cache.new(:initial_capacity => 2)
-
end
-
1
@class_to_pool = ThreadSafe::Cache.new(:initial_capacity => 2) do |h,k|
-
1
h[k] = ThreadSafe::Cache.new
-
end
-
end
-
-
1
def connection_pool_list
-
owner_to_pool.values.compact
-
end
-
-
1
def connection_pools
-
ActiveSupport::Deprecation.warn(
-
"In the next release, this will return the same as #connection_pool_list. " \
-
"(An array of pools, rather than a hash mapping specs to pools.)"
-
)
-
Hash[connection_pool_list.map { |pool| [pool.spec, pool] }]
-
end
-
-
1
def establish_connection(owner, spec)
-
1
@class_to_pool.clear
-
1
raise RuntimeError, "Anonymous class is not allowed." unless owner.name
-
1
owner_to_pool[owner.name] = ConnectionAdapters::ConnectionPool.new(spec)
-
end
-
-
# Returns true if there are any active connections among the connection
-
# pools that the ConnectionHandler is managing.
-
1
def active_connections?
-
connection_pool_list.any?(&:active_connection?)
-
end
-
-
# Returns any connections in use by the current thread back to the pool,
-
# and also returns connections to the pool cached by threads that are no
-
# longer alive.
-
1
def clear_active_connections!
-
connection_pool_list.each(&:release_connection)
-
end
-
-
# Clears the cache which maps classes.
-
1
def clear_reloadable_connections!
-
connection_pool_list.each(&:clear_reloadable_connections!)
-
end
-
-
1
def clear_all_connections!
-
connection_pool_list.each(&:disconnect!)
-
end
-
-
# Locate the connection of the nearest super class. This can be an
-
# active or defined connection: if it is the latter, it will be
-
# opened and set as the active connection for the class it was defined
-
# for (not necessarily the current class).
-
1
def retrieve_connection(klass) #:nodoc:
-
1
pool = retrieve_connection_pool(klass)
-
1
(pool && pool.connection) or raise ConnectionNotEstablished
-
end
-
-
# Returns true if a connection that's accessible to this class has
-
# already been opened.
-
1
def connected?(klass)
-
1
conn = retrieve_connection_pool(klass)
-
1
conn && conn.connected?
-
end
-
-
# Remove the connection for this class. This will close the active
-
# connection and the defined connection (if they exist). The result
-
# can be used as an argument for establish_connection, for easily
-
# re-establishing the connection.
-
1
def remove_connection(owner)
-
1
if pool = owner_to_pool.delete(owner.name)
-
@class_to_pool.clear
-
pool.automatic_reconnect = false
-
pool.disconnect!
-
pool.spec.config
-
end
-
end
-
-
# Retrieving the connection pool happens a lot so we cache it in @class_to_pool.
-
# This makes retrieving the connection pool O(1) once the process is warm.
-
# When a connection is established or removed, we invalidate the cache.
-
#
-
# Ideally we would use #fetch here, as class_to_pool[klass] may sometimes be nil.
-
# However, benchmarking (https://gist.github.com/jonleighton/3552829) showed that
-
# #fetch is significantly slower than #[]. So in the nil case, no caching will
-
# take place, but that's ok since the nil case is not the common one that we wish
-
# to optimise for.
-
1
def retrieve_connection_pool(klass)
-
2
class_to_pool[klass.name] ||= begin
-
1
until pool = pool_for(klass)
-
klass = klass.superclass
-
break unless klass <= Base
-
end
-
-
1
class_to_pool[klass.name] = pool
-
end
-
end
-
-
1
private
-
-
1
def owner_to_pool
-
3
@owner_to_pool[Process.pid]
-
end
-
-
1
def class_to_pool
-
3
@class_to_pool[Process.pid]
-
end
-
-
1
def pool_for(owner)
-
1
owner_to_pool.fetch(owner.name) {
-
if ancestor_pool = pool_from_any_process_for(owner)
-
# A connection was established in an ancestor process that must have
-
# subsequently forked. We can't reuse the connection, but we can copy
-
# the specification and establish a new connection with it.
-
establish_connection owner, ancestor_pool.spec
-
else
-
owner_to_pool[owner.name] = nil
-
end
-
}
-
end
-
-
1
def pool_from_any_process_for(owner)
-
owner_to_pool = @owner_to_pool.values.find { |v| v[owner.name] }
-
owner_to_pool && owner_to_pool[owner.name]
-
end
-
end
-
-
1
class ConnectionManagement
-
1
def initialize(app)
-
1
@app = app
-
end
-
-
1
def call(env)
-
testing = env.key?('rack.test')
-
-
response = @app.call(env)
-
response[2] = ::Rack::BodyProxy.new(response[2]) do
-
ActiveRecord::Base.clear_active_connections! unless testing
-
end
-
-
response
-
rescue Exception
-
ActiveRecord::Base.clear_active_connections! unless testing
-
raise
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ConnectionAdapters # :nodoc:
-
1
module DatabaseLimits
-
-
# Returns the maximum length of a table alias.
-
1
def table_alias_length
-
255
-
end
-
-
# Returns the maximum length of a column name.
-
1
def column_name_length
-
64
-
end
-
-
# Returns the maximum length of a table name.
-
1
def table_name_length
-
64
-
end
-
-
# Returns the maximum allowed length for an index name. This
-
# limit is enforced by rails and Is less than or equal to
-
# <tt>index_name_length</tt>. The gap between
-
# <tt>index_name_length</tt> is to allow internal rails
-
# operations to use prefixes in temporary operations.
-
1
def allowed_index_name_length
-
index_name_length
-
end
-
-
# Returns the maximum length of an index name.
-
1
def index_name_length
-
64
-
end
-
-
# Returns the maximum number of columns per table.
-
1
def columns_per_table
-
1024
-
end
-
-
# Returns the maximum number of indexes per table.
-
1
def indexes_per_table
-
16
-
end
-
-
# Returns the maximum number of columns in a multicolumn index.
-
1
def columns_per_multicolumn_index
-
16
-
end
-
-
# Returns the maximum number of elements in an IN (x,y,z) clause.
-
# nil means no limit.
-
1
def in_clause_length
-
nil
-
end
-
-
# Returns the maximum length of an SQL query.
-
1
def sql_query_length
-
1048575
-
end
-
-
# Returns maximum number of joins in a single query.
-
1
def joins_per_query
-
256
-
end
-
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ConnectionAdapters # :nodoc:
-
1
module DatabaseStatements
-
1
def initialize
-
1
super
-
1
reset_transaction
-
end
-
-
# Converts an arel AST to SQL
-
1
def to_sql(arel, binds = [])
-
if arel.respond_to?(:ast)
-
binds = binds.dup
-
visitor.accept(arel.ast) do
-
quote(*binds.shift.reverse)
-
end
-
else
-
arel
-
end
-
end
-
-
# Returns an ActiveRecord::Result instance.
-
1
def select_all(arel, name = nil, binds = [])
-
if arel.is_a?(Relation)
-
relation = arel
-
arel = relation.arel
-
if !binds || binds.empty?
-
binds = relation.bind_values
-
end
-
end
-
-
select(to_sql(arel, binds), name, binds)
-
end
-
-
# Returns a record hash with the column names as keys and column values
-
# as values.
-
1
def select_one(arel, name = nil, binds = [])
-
select_all(arel, name, binds).first
-
end
-
-
# Returns a single value from a record
-
1
def select_value(arel, name = nil, binds = [])
-
if result = select_one(arel, name, binds)
-
result.values.first
-
end
-
end
-
-
# Returns an array of the values of the first column in a select:
-
# select_values("SELECT id FROM companies LIMIT 3") => [1,2,3]
-
1
def select_values(arel, name = nil)
-
binds = []
-
if arel.is_a?(Relation)
-
arel, binds = arel.arel, arel.bind_values
-
end
-
select_rows(to_sql(arel, binds), name, binds).map(&:first)
-
end
-
-
# Returns an array of arrays containing the field values.
-
# Order is the same as that returned by +columns+.
-
1
def select_rows(sql, name = nil, binds = [])
-
end
-
1
undef_method :select_rows
-
-
# Executes the SQL statement in the context of this connection.
-
1
def execute(sql, name = nil)
-
end
-
1
undef_method :execute
-
-
# Executes +sql+ statement in the context of this connection using
-
# +binds+ as the bind substitutes. +name+ is logged along with
-
# the executed +sql+ statement.
-
1
def exec_query(sql, name = 'SQL', binds = [])
-
end
-
-
# Executes insert +sql+ statement in the context of this connection using
-
# +binds+ as the bind substitutes. +name+ is logged along with
-
# the executed +sql+ statement.
-
1
def exec_insert(sql, name, binds, pk = nil, sequence_name = nil)
-
exec_query(sql, name, binds)
-
end
-
-
# Executes delete +sql+ statement in the context of this connection using
-
# +binds+ as the bind substitutes. +name+ is logged along with
-
# the executed +sql+ statement.
-
1
def exec_delete(sql, name, binds)
-
exec_query(sql, name, binds)
-
end
-
-
# Executes update +sql+ statement in the context of this connection using
-
# +binds+ as the bind substitutes. +name+ is logged along with
-
# the executed +sql+ statement.
-
1
def exec_update(sql, name, binds)
-
exec_query(sql, name, binds)
-
end
-
-
# Returns the last auto-generated ID from the affected table.
-
#
-
# +id_value+ will be returned unless the value is nil, in
-
# which case the database will attempt to calculate the last inserted
-
# id and return that value.
-
#
-
# If the next id was calculated in advance (as in Oracle), it should be
-
# passed in as +id_value+.
-
1
def insert(arel, name = nil, pk = nil, id_value = nil, sequence_name = nil, binds = [])
-
sql, binds = sql_for_insert(to_sql(arel, binds), pk, id_value, sequence_name, binds)
-
value = exec_insert(sql, name, binds, pk, sequence_name)
-
id_value || last_inserted_id(value)
-
end
-
-
# Executes the update statement and returns the number of rows affected.
-
1
def update(arel, name = nil, binds = [])
-
exec_update(to_sql(arel, binds), name, binds)
-
end
-
-
# Executes the delete statement and returns the number of rows affected.
-
1
def delete(arel, name = nil, binds = [])
-
exec_delete(to_sql(arel, binds), name, binds)
-
end
-
-
# Returns +true+ when the connection adapter supports prepared statement
-
# caching, otherwise returns +false+
-
1
def supports_statement_cache?
-
false
-
end
-
-
# Runs the given block in a database transaction, and returns the result
-
# of the block.
-
#
-
# == Nested transactions support
-
#
-
# Most databases don't support true nested transactions. At the time of
-
# writing, the only database that supports true nested transactions that
-
# we're aware of, is MS-SQL.
-
#
-
# In order to get around this problem, #transaction will emulate the effect
-
# of nested transactions, by using savepoints:
-
# http://dev.mysql.com/doc/refman/5.0/en/savepoint.html
-
# Savepoints are supported by MySQL and PostgreSQL. SQLite3 version >= '3.6.8'
-
# supports savepoints.
-
#
-
# It is safe to call this method if a database transaction is already open,
-
# i.e. if #transaction is called within another #transaction block. In case
-
# of a nested call, #transaction will behave as follows:
-
#
-
# - The block will be run without doing anything. All database statements
-
# that happen within the block are effectively appended to the already
-
# open database transaction.
-
# - However, if +:requires_new+ is set, the block will be wrapped in a
-
# database savepoint acting as a sub-transaction.
-
#
-
# === Caveats
-
#
-
# MySQL doesn't support DDL transactions. If you perform a DDL operation,
-
# then any created savepoints will be automatically released. For example,
-
# if you've created a savepoint, then you execute a CREATE TABLE statement,
-
# then the savepoint that was created will be automatically released.
-
#
-
# This means that, on MySQL, you shouldn't execute DDL operations inside
-
# a #transaction call that you know might create a savepoint. Otherwise,
-
# #transaction will raise exceptions when it tries to release the
-
# already-automatically-released savepoints:
-
#
-
# Model.connection.transaction do # BEGIN
-
# Model.connection.transaction(requires_new: true) do # CREATE SAVEPOINT active_record_1
-
# Model.connection.create_table(...)
-
# # active_record_1 now automatically released
-
# end # RELEASE SAVEPOINT active_record_1 <--- BOOM! database error!
-
# end
-
#
-
# == Transaction isolation
-
#
-
# If your database supports setting the isolation level for a transaction, you can set
-
# it like so:
-
#
-
# Post.transaction(isolation: :serializable) do
-
# # ...
-
# end
-
#
-
# Valid isolation levels are:
-
#
-
# * <tt>:read_uncommitted</tt>
-
# * <tt>:read_committed</tt>
-
# * <tt>:repeatable_read</tt>
-
# * <tt>:serializable</tt>
-
#
-
# You should consult the documentation for your database to understand the
-
# semantics of these different levels:
-
#
-
# * http://www.postgresql.org/docs/9.1/static/transaction-iso.html
-
# * https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html
-
#
-
# An <tt>ActiveRecord::TransactionIsolationError</tt> will be raised if:
-
#
-
# * The adapter does not support setting the isolation level
-
# * You are joining an existing open transaction
-
# * You are creating a nested (savepoint) transaction
-
#
-
# The mysql, mysql2 and postgresql adapters support setting the transaction
-
# isolation level. However, support is disabled for mysql versions below 5,
-
# because they are affected by a bug[http://bugs.mysql.com/bug.php?id=39170]
-
# which means the isolation level gets persisted outside the transaction.
-
1
def transaction(options = {})
-
options.assert_valid_keys :requires_new, :joinable, :isolation
-
-
if !options[:requires_new] && current_transaction.joinable?
-
if options[:isolation]
-
raise ActiveRecord::TransactionIsolationError, "cannot set isolation when joining a transaction"
-
end
-
-
yield
-
else
-
within_new_transaction(options) { yield }
-
end
-
rescue ActiveRecord::Rollback
-
# rollbacks are silently swallowed
-
end
-
-
1
def within_new_transaction(options = {}) #:nodoc:
-
transaction = begin_transaction(options)
-
yield
-
rescue Exception => error
-
rollback_transaction if transaction
-
raise
-
ensure
-
begin
-
commit_transaction unless error
-
rescue Exception
-
rollback_transaction
-
raise
-
end
-
end
-
-
1
def current_transaction #:nodoc:
-
@transaction
-
end
-
-
1
def transaction_open?
-
@transaction.open?
-
end
-
-
1
def begin_transaction(options = {}) #:nodoc:
-
@transaction = @transaction.begin(options)
-
end
-
-
1
def commit_transaction #:nodoc:
-
@transaction = @transaction.commit
-
end
-
-
1
def rollback_transaction #:nodoc:
-
@transaction = @transaction.rollback
-
end
-
-
1
def reset_transaction #:nodoc:
-
1
@transaction = ClosedTransaction.new(self)
-
end
-
-
# Register a record with the current transaction so that its after_commit and after_rollback callbacks
-
# can be called.
-
1
def add_transaction_record(record)
-
@transaction.add_record(record)
-
end
-
-
# Begins the transaction (and turns off auto-committing).
-
1
def begin_db_transaction() end
-
-
1
def transaction_isolation_levels
-
{
-
read_uncommitted: "READ UNCOMMITTED",
-
read_committed: "READ COMMITTED",
-
repeatable_read: "REPEATABLE READ",
-
serializable: "SERIALIZABLE"
-
}
-
end
-
-
# Begins the transaction with the isolation level set. Raises an error by
-
# default; adapters that support setting the isolation level should implement
-
# this method.
-
1
def begin_isolated_db_transaction(isolation)
-
raise ActiveRecord::TransactionIsolationError, "adapter does not support setting transaction isolation"
-
end
-
-
# Commits the transaction (and turns on auto-committing).
-
1
def commit_db_transaction() end
-
-
# Rolls back the transaction (and turns on auto-committing). Must be
-
# done if the transaction block raises an exception or returns false.
-
1
def rollback_db_transaction() end
-
-
1
def default_sequence_name(table, column)
-
nil
-
end
-
-
# Set the sequence to the max value of the table's column.
-
1
def reset_sequence!(table, column, sequence = nil)
-
# Do nothing by default. Implement for PostgreSQL, Oracle, ...
-
end
-
-
# Inserts the given fixture into the table. Overridden in adapters that require
-
# something beyond a simple insert (eg. Oracle).
-
1
def insert_fixture(fixture, table_name)
-
columns = schema_cache.columns_hash(table_name)
-
-
key_list = []
-
value_list = fixture.map do |name, value|
-
key_list << quote_column_name(name)
-
quote(value, columns[name])
-
end
-
-
execute "INSERT INTO #{quote_table_name(table_name)} (#{key_list.join(', ')}) VALUES (#{value_list.join(', ')})", 'Fixture Insert'
-
end
-
-
1
def empty_insert_statement_value
-
"DEFAULT VALUES"
-
end
-
-
1
def limited_update_conditions(where_sql, quoted_table_name, quoted_primary_key)
-
"WHERE #{quoted_primary_key} IN (SELECT #{quoted_primary_key} FROM #{quoted_table_name} #{where_sql})"
-
end
-
-
# Sanitizes the given LIMIT parameter in order to prevent SQL injection.
-
#
-
# The +limit+ may be anything that can evaluate to a string via #to_s. It
-
# should look like an integer, or a comma-delimited list of integers, or
-
# an Arel SQL literal.
-
#
-
# Returns Integer and Arel::Nodes::SqlLiteral limits as is.
-
# Returns the sanitized limit parameter, either as an integer, or as a
-
# string which contains a comma-delimited list of integers.
-
1
def sanitize_limit(limit)
-
if limit.is_a?(Integer) || limit.is_a?(Arel::Nodes::SqlLiteral)
-
limit
-
elsif limit.to_s =~ /,/
-
Arel.sql limit.to_s.split(',').map{ |i| Integer(i) }.join(',')
-
else
-
Integer(limit)
-
end
-
end
-
-
# The default strategy for an UPDATE with joins is to use a subquery. This doesn't work
-
# on mysql (even when aliasing the tables), but mysql allows using JOIN directly in
-
# an UPDATE statement, so in the mysql adapters we redefine this to do that.
-
1
def join_to_update(update, select) #:nodoc:
-
key = update.key
-
subselect = subquery_for(key, select)
-
-
update.where key.in(subselect)
-
end
-
-
1
def join_to_delete(delete, select, key) #:nodoc:
-
subselect = subquery_for(key, select)
-
-
delete.where key.in(subselect)
-
end
-
-
1
protected
-
-
# Returns a subquery for the given key using the join information.
-
1
def subquery_for(key, select)
-
subselect = select.clone
-
subselect.projections = [key]
-
subselect
-
end
-
-
# Returns an ActiveRecord::Result instance.
-
1
def select(sql, name = nil, binds = [])
-
end
-
1
undef_method :select
-
-
# Returns the last auto-generated ID from the affected table.
-
1
def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
-
execute(sql, name)
-
id_value
-
end
-
-
# Executes the update statement and returns the number of rows affected.
-
1
def update_sql(sql, name = nil)
-
execute(sql, name)
-
end
-
-
# Executes the delete statement and returns the number of rows affected.
-
1
def delete_sql(sql, name = nil)
-
update_sql(sql, name)
-
end
-
-
1
def sql_for_insert(sql, pk, id_value, sequence_name, binds)
-
[sql, binds]
-
end
-
-
1
def last_inserted_id(result)
-
row = result.rows.first
-
row && row.first
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ConnectionAdapters # :nodoc:
-
1
module QueryCache
-
1
class << self
-
1
def included(base) #:nodoc:
-
1
dirties_query_cache base, :insert, :update, :delete
-
end
-
-
1
def dirties_query_cache(base, *method_names)
-
1
method_names.each do |method_name|
-
3
base.class_eval <<-end_code, __FILE__, __LINE__ + 1
-
def #{method_name}(*)
-
clear_query_cache if @query_cache_enabled
-
super
-
end
-
end_code
-
end
-
end
-
end
-
-
1
attr_reader :query_cache, :query_cache_enabled
-
-
1
def initialize(*)
-
1
super
-
1
@query_cache = Hash.new { |h,sql| h[sql] = {} }
-
1
@query_cache_enabled = false
-
end
-
-
# Enable the query cache within the block.
-
1
def cache
-
old, @query_cache_enabled = @query_cache_enabled, true
-
yield
-
ensure
-
@query_cache_enabled = old
-
clear_query_cache unless @query_cache_enabled
-
end
-
-
1
def enable_query_cache!
-
@query_cache_enabled = true
-
end
-
-
1
def disable_query_cache!
-
@query_cache_enabled = false
-
end
-
-
# Disable the query cache within the block.
-
1
def uncached
-
old, @query_cache_enabled = @query_cache_enabled, false
-
yield
-
ensure
-
@query_cache_enabled = old
-
end
-
-
# Clears the query cache.
-
#
-
# One reason you may wish to call this method explicitly is between queries
-
# that ask the database to randomize results. Otherwise the cache would see
-
# the same SQL query and repeatedly return the same result each time, silently
-
# undermining the randomness you were expecting.
-
1
def clear_query_cache
-
@query_cache.clear
-
end
-
-
1
def select_all(arel, name = nil, binds = [])
-
if @query_cache_enabled && !locked?(arel)
-
sql = to_sql(arel, binds)
-
cache_sql(sql, binds) { super(sql, name, binds) }
-
else
-
super
-
end
-
end
-
-
1
private
-
-
1
def cache_sql(sql, binds)
-
result =
-
if @query_cache[sql].key?(binds)
-
ActiveSupport::Notifications.instrument("sql.active_record",
-
:sql => sql, :binds => binds, :name => "CACHE", :connection_id => object_id)
-
@query_cache[sql][binds]
-
else
-
@query_cache[sql][binds] = yield
-
end
-
result.dup
-
end
-
-
# If arel is locked this is a SELECT ... FOR UPDATE or somesuch. Such
-
# queries should not be cached.
-
1
def locked?(arel)
-
arel.respond_to?(:locked) && arel.locked
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/big_decimal/conversions'
-
-
1
module ActiveRecord
-
1
module ConnectionAdapters # :nodoc:
-
1
module Quoting
-
# Quotes the column value to help prevent
-
# {SQL injection attacks}[http://en.wikipedia.org/wiki/SQL_injection].
-
1
def quote(value, column = nil)
-
# records are quoted as their primary key
-
return value.quoted_id if value.respond_to?(:quoted_id)
-
-
case value
-
when String, ActiveSupport::Multibyte::Chars
-
value = value.to_s
-
return "'#{quote_string(value)}'" unless column
-
-
case column.type
-
when :integer then value.to_i.to_s
-
when :float then value.to_f.to_s
-
else
-
"'#{quote_string(value)}'"
-
end
-
-
when true, false
-
if column && column.type == :integer
-
value ? '1' : '0'
-
else
-
value ? quoted_true : quoted_false
-
end
-
# BigDecimals need to be put in a non-normalized form and quoted.
-
when nil then "NULL"
-
when BigDecimal then value.to_s('F')
-
when Numeric, ActiveSupport::Duration then value.to_s
-
when Date, Time then "'#{quoted_date(value)}'"
-
when Symbol then "'#{quote_string(value.to_s)}'"
-
when Class then "'#{value.to_s}'"
-
else
-
"'#{quote_string(YAML.dump(value))}'"
-
end
-
end
-
-
# Cast a +value+ to a type that the database understands. For example,
-
# SQLite does not understand dates, so this method will convert a Date
-
# to a String.
-
1
def type_cast(value, column)
-
if value.respond_to?(:quoted_id) && value.respond_to?(:id)
-
return value.id
-
end
-
-
case value
-
when String, ActiveSupport::Multibyte::Chars
-
value = value.to_s
-
return value unless column
-
-
case column.type
-
when :integer then value.to_i
-
when :float then value.to_f
-
else
-
value
-
end
-
-
when true, false
-
if column && column.type == :integer
-
value ? 1 : 0
-
else
-
value ? 't' : 'f'
-
end
-
# BigDecimals need to be put in a non-normalized form and quoted.
-
when nil then nil
-
when BigDecimal then value.to_s('F')
-
when Numeric then value
-
when Date, Time then quoted_date(value)
-
when Symbol then value.to_s
-
else
-
to_type = column ? " to #{column.type}" : ""
-
raise TypeError, "can't cast #{value.class}#{to_type}"
-
end
-
end
-
-
# Quotes a string, escaping any ' (single quote) and \ (backslash)
-
# characters.
-
1
def quote_string(s)
-
s.gsub(/\\/, '\&\&').gsub(/'/, "''") # ' (for ruby-mode)
-
end
-
-
# Quotes the column name. Defaults to no quoting.
-
1
def quote_column_name(column_name)
-
column_name
-
end
-
-
# Quotes the table name. Defaults to column name quoting.
-
1
def quote_table_name(table_name)
-
quote_column_name(table_name)
-
end
-
-
# Override to return the quoted table name for assignment. Defaults to
-
# table quoting.
-
#
-
# This works for mysql and mysql2 where table.column can be used to
-
# resolve ambiguity.
-
#
-
# We override this in the sqlite and postgresql adapters to use only
-
# the column name (as per syntax requirements).
-
1
def quote_table_name_for_assignment(table, attr)
-
quote_table_name("#{table}.#{attr}")
-
end
-
-
1
def quoted_true
-
"'t'"
-
end
-
-
1
def quoted_false
-
"'f'"
-
end
-
-
1
def quoted_date(value)
-
if value.acts_like?(:time)
-
zone_conversion_method = ActiveRecord::Base.default_timezone == :utc ? :getutc : :getlocal
-
-
if value.respond_to?(zone_conversion_method)
-
value = value.send(zone_conversion_method)
-
end
-
end
-
-
value.to_s(:db)
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ConnectionAdapters
-
1
module Savepoints #:nodoc:
-
1
def supports_savepoints?
-
true
-
end
-
-
1
def create_savepoint(name = current_savepoint_name)
-
execute("SAVEPOINT #{name}")
-
end
-
-
1
def rollback_to_savepoint(name = current_savepoint_name)
-
execute("ROLLBACK TO SAVEPOINT #{name}")
-
end
-
-
1
def release_savepoint(name = current_savepoint_name)
-
execute("RELEASE SAVEPOINT #{name}")
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ConnectionAdapters
-
1
class AbstractAdapter
-
1
class SchemaCreation # :nodoc:
-
1
def initialize(conn)
-
@conn = conn
-
@cache = {}
-
end
-
-
1
def accept(o)
-
m = @cache[o.class] ||= "visit_#{o.class.name.split('::').last}"
-
send m, o
-
end
-
-
1
def visit_AddColumn(o)
-
sql_type = type_to_sql(o.type.to_sym, o.limit, o.precision, o.scale)
-
sql = "ADD #{quote_column_name(o.name)} #{sql_type}"
-
add_column_options!(sql, column_options(o))
-
end
-
-
1
private
-
-
1
def visit_AlterTable(o)
-
sql = "ALTER TABLE #{quote_table_name(o.name)} "
-
sql << o.adds.map { |col| visit_AddColumn col }.join(' ')
-
end
-
-
1
def visit_ColumnDefinition(o)
-
sql_type = type_to_sql(o.type.to_sym, o.limit, o.precision, o.scale)
-
column_sql = "#{quote_column_name(o.name)} #{sql_type}"
-
add_column_options!(column_sql, column_options(o)) unless o.primary_key?
-
column_sql
-
end
-
-
1
def visit_TableDefinition(o)
-
create_sql = "CREATE#{' TEMPORARY' if o.temporary} TABLE "
-
create_sql << "#{quote_table_name(o.name)} "
-
create_sql << "(#{o.columns.map { |c| accept c }.join(', ')}) " unless o.as
-
create_sql << "#{o.options}"
-
create_sql << " AS #{@conn.to_sql(o.as)}" if o.as
-
create_sql
-
end
-
-
1
def column_options(o)
-
column_options = {}
-
column_options[:null] = o.null unless o.null.nil?
-
column_options[:default] = o.default unless o.default.nil?
-
column_options[:column] = o
-
column_options[:first] = o.first
-
column_options[:after] = o.after
-
column_options
-
end
-
-
1
def quote_column_name(name)
-
@conn.quote_column_name name
-
end
-
-
1
def quote_table_name(name)
-
@conn.quote_table_name name
-
end
-
-
1
def type_to_sql(type, limit, precision, scale)
-
@conn.type_to_sql type.to_sym, limit, precision, scale
-
end
-
-
1
def add_column_options!(sql, options)
-
sql << " DEFAULT #{@conn.quote(options[:default], options[:column])}" if options_include_default?(options)
-
# must explicitly check for :null to allow change_column to work on migrations
-
if options[:null] == false
-
sql << " NOT NULL"
-
end
-
if options[:auto_increment] == true
-
sql << " AUTO_INCREMENT"
-
end
-
sql
-
end
-
-
1
def options_include_default?(options)
-
options.include?(:default) && !(options[:null] == false && options[:default].nil?)
-
end
-
end
-
end
-
end
-
end
-
1
require 'date'
-
1
require 'set'
-
1
require 'bigdecimal'
-
1
require 'bigdecimal/util'
-
-
1
module ActiveRecord
-
1
module ConnectionAdapters #:nodoc:
-
# Abstract representation of an index definition on a table. Instances of
-
# this type are typically created and returned by methods in database
-
# adapters. e.g. ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter#indexes
-
1
class IndexDefinition < Struct.new(:table, :name, :unique, :columns, :lengths, :orders, :where, :type, :using) #:nodoc:
-
end
-
-
# Abstract representation of a column definition. Instances of this type
-
# are typically created by methods in TableDefinition, and added to the
-
# +columns+ attribute of said TableDefinition object, in order to be used
-
# for generating a number of table creation or table changing SQL statements.
-
1
class ColumnDefinition < Struct.new(:name, :type, :limit, :precision, :scale, :default, :null, :first, :after, :primary_key) #:nodoc:
-
-
1
def primary_key?
-
primary_key || type.to_sym == :primary_key
-
end
-
end
-
-
1
class ChangeColumnDefinition < Struct.new(:column, :type, :options) #:nodoc:
-
end
-
-
# Represents the schema of an SQL table in an abstract way. This class
-
# provides methods for manipulating the schema representation.
-
#
-
# Inside migration files, the +t+ object in +create_table+
-
# is actually of this type:
-
#
-
# class SomeMigration < ActiveRecord::Migration
-
# def up
-
# create_table :foo do |t|
-
# puts t.class # => "ActiveRecord::ConnectionAdapters::TableDefinition"
-
# end
-
# end
-
#
-
# def down
-
# ...
-
# end
-
# end
-
#
-
# The table definitions
-
# The Columns are stored as a ColumnDefinition in the +columns+ attribute.
-
1
class TableDefinition
-
# An array of ColumnDefinition objects, representing the column changes
-
# that have been defined.
-
1
attr_accessor :indexes
-
1
attr_reader :name, :temporary, :options, :as
-
-
1
def initialize(types, name, temporary, options, as = nil)
-
@columns_hash = {}
-
@indexes = {}
-
@native = types
-
@temporary = temporary
-
@options = options
-
@as = as
-
@name = name
-
end
-
-
1
def columns; @columns_hash.values; end
-
-
# Appends a primary key definition to the table definition.
-
# Can be called multiple times, but this is probably not a good idea.
-
1
def primary_key(name, type = :primary_key, options = {})
-
column(name, type, options.merge(:primary_key => true))
-
end
-
-
# Returns a ColumnDefinition for the column with name +name+.
-
1
def [](name)
-
@columns_hash[name.to_s]
-
end
-
-
# Instantiates a new column for the table.
-
# The +type+ parameter is normally one of the migrations native types,
-
# which is one of the following:
-
# <tt>:primary_key</tt>, <tt>:string</tt>, <tt>:text</tt>,
-
# <tt>:integer</tt>, <tt>:float</tt>, <tt>:decimal</tt>,
-
# <tt>:datetime</tt>, <tt>:timestamp</tt>, <tt>:time</tt>,
-
# <tt>:date</tt>, <tt>:binary</tt>, <tt>:boolean</tt>.
-
#
-
# You may use a type not in this list as long as it is supported by your
-
# database (for example, "polygon" in MySQL), but this will not be database
-
# agnostic and should usually be avoided.
-
#
-
# Available options are (none of these exists by default):
-
# * <tt>:limit</tt> -
-
# Requests a maximum column length. This is number of characters for <tt>:string</tt> and
-
# <tt>:text</tt> columns and number of bytes for <tt>:binary</tt> and <tt>:integer</tt> columns.
-
# * <tt>:default</tt> -
-
# The column's default value. Use nil for NULL.
-
# * <tt>:null</tt> -
-
# Allows or disallows +NULL+ values in the column. This option could
-
# have been named <tt>:null_allowed</tt>.
-
# * <tt>:precision</tt> -
-
# Specifies the precision for a <tt>:decimal</tt> column.
-
# * <tt>:scale</tt> -
-
# Specifies the scale for a <tt>:decimal</tt> column.
-
#
-
# For clarity's sake: the precision is the number of significant digits,
-
# while the scale is the number of digits that can be stored following
-
# the decimal point. For example, the number 123.45 has a precision of 5
-
# and a scale of 2. A decimal with a precision of 5 and a scale of 2 can
-
# range from -999.99 to 999.99.
-
#
-
# Please be aware of different RDBMS implementations behavior with
-
# <tt>:decimal</tt> columns:
-
# * The SQL standard says the default scale should be 0, <tt>:scale</tt> <=
-
# <tt>:precision</tt>, and makes no comments about the requirements of
-
# <tt>:precision</tt>.
-
# * MySQL: <tt>:precision</tt> [1..63], <tt>:scale</tt> [0..30].
-
# Default is (10,0).
-
# * PostgreSQL: <tt>:precision</tt> [1..infinity],
-
# <tt>:scale</tt> [0..infinity]. No default.
-
# * SQLite2: Any <tt>:precision</tt> and <tt>:scale</tt> may be used.
-
# Internal storage as strings. No default.
-
# * SQLite3: No restrictions on <tt>:precision</tt> and <tt>:scale</tt>,
-
# but the maximum supported <tt>:precision</tt> is 16. No default.
-
# * Oracle: <tt>:precision</tt> [1..38], <tt>:scale</tt> [-84..127].
-
# Default is (38,0).
-
# * DB2: <tt>:precision</tt> [1..63], <tt>:scale</tt> [0..62].
-
# Default unknown.
-
# * Firebird: <tt>:precision</tt> [1..18], <tt>:scale</tt> [0..18].
-
# Default (9,0). Internal types NUMERIC and DECIMAL have different
-
# storage rules, decimal being better.
-
# * FrontBase?: <tt>:precision</tt> [1..38], <tt>:scale</tt> [0..38].
-
# Default (38,0). WARNING Max <tt>:precision</tt>/<tt>:scale</tt> for
-
# NUMERIC is 19, and DECIMAL is 38.
-
# * SqlServer?: <tt>:precision</tt> [1..38], <tt>:scale</tt> [0..38].
-
# Default (38,0).
-
# * Sybase: <tt>:precision</tt> [1..38], <tt>:scale</tt> [0..38].
-
# Default (38,0).
-
# * OpenBase?: Documentation unclear. Claims storage in <tt>double</tt>.
-
#
-
# This method returns <tt>self</tt>.
-
#
-
# == Examples
-
# # Assuming +td+ is an instance of TableDefinition
-
# td.column(:granted, :boolean)
-
# # granted BOOLEAN
-
#
-
# td.column(:picture, :binary, limit: 2.megabytes)
-
# # => picture BLOB(2097152)
-
#
-
# td.column(:sales_stage, :string, limit: 20, default: 'new', null: false)
-
# # => sales_stage VARCHAR(20) DEFAULT 'new' NOT NULL
-
#
-
# td.column(:bill_gates_money, :decimal, precision: 15, scale: 2)
-
# # => bill_gates_money DECIMAL(15,2)
-
#
-
# td.column(:sensor_reading, :decimal, precision: 30, scale: 20)
-
# # => sensor_reading DECIMAL(30,20)
-
#
-
# # While <tt>:scale</tt> defaults to zero on most databases, it
-
# # probably wouldn't hurt to include it.
-
# td.column(:huge_integer, :decimal, precision: 30)
-
# # => huge_integer DECIMAL(30)
-
#
-
# # Defines a column with a database-specific type.
-
# td.column(:foo, 'polygon')
-
# # => foo polygon
-
#
-
# == Short-hand examples
-
#
-
# Instead of calling +column+ directly, you can also work with the short-hand definitions for the default types.
-
# They use the type as the method name instead of as a parameter and allow for multiple columns to be defined
-
# in a single statement.
-
#
-
# What can be written like this with the regular calls to column:
-
#
-
# create_table :products do |t|
-
# t.column :shop_id, :integer
-
# t.column :creator_id, :integer
-
# t.column :name, :string, default: "Untitled"
-
# t.column :value, :string, default: "Untitled"
-
# t.column :created_at, :datetime
-
# t.column :updated_at, :datetime
-
# end
-
#
-
# can also be written as follows using the short-hand:
-
#
-
# create_table :products do |t|
-
# t.integer :shop_id, :creator_id
-
# t.string :name, :value, default: "Untitled"
-
# t.timestamps
-
# end
-
#
-
# There's a short-hand method for each of the type values declared at the top. And then there's
-
# TableDefinition#timestamps that'll add +created_at+ and +updated_at+ as datetimes.
-
#
-
# TableDefinition#references will add an appropriately-named _id column, plus a corresponding _type
-
# column if the <tt>:polymorphic</tt> option is supplied. If <tt>:polymorphic</tt> is a hash of
-
# options, these will be used when creating the <tt>_type</tt> column. The <tt>:index</tt> option
-
# will also create an index, similar to calling <tt>add_index</tt>. So what can be written like this:
-
#
-
# create_table :taggings do |t|
-
# t.integer :tag_id, :tagger_id, :taggable_id
-
# t.string :tagger_type
-
# t.string :taggable_type, default: 'Photo'
-
# end
-
# add_index :taggings, :tag_id, name: 'index_taggings_on_tag_id'
-
# add_index :taggings, [:tagger_id, :tagger_type]
-
#
-
# Can also be written as follows using references:
-
#
-
# create_table :taggings do |t|
-
# t.references :tag, index: { name: 'index_taggings_on_tag_id' }
-
# t.references :tagger, polymorphic: true, index: true
-
# t.references :taggable, polymorphic: { default: 'Photo' }
-
# end
-
1
def column(name, type, options = {})
-
name = name.to_s
-
type = type.to_sym
-
-
if primary_key_column_name == name
-
raise ArgumentError, "you can't redefine the primary key column '#{name}'. To define a custom primary key, pass { id: false } to create_table."
-
end
-
-
@columns_hash[name] = new_column_definition(name, type, options)
-
self
-
end
-
-
1
def remove_column(name)
-
@columns_hash.delete name.to_s
-
end
-
-
1
[:string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean].each do |column_type|
-
11
define_method column_type do |*args|
-
options = args.extract_options!
-
column_names = args
-
column_names.each { |name| column(name, column_type, options) }
-
end
-
end
-
-
# Adds index options to the indexes hash, keyed by column name
-
# This is primarily used to track indexes that need to be created after the table
-
#
-
# index(:account_id, name: 'index_projects_on_account_id')
-
1
def index(column_name, options = {})
-
indexes[column_name] = options
-
end
-
-
# Appends <tt>:datetime</tt> columns <tt>:created_at</tt> and
-
# <tt>:updated_at</tt> to the table.
-
1
def timestamps(*args)
-
options = args.extract_options!
-
column(:created_at, :datetime, options)
-
column(:updated_at, :datetime, options)
-
end
-
-
1
def references(*args)
-
options = args.extract_options!
-
polymorphic = options.delete(:polymorphic)
-
index_options = options.delete(:index)
-
args.each do |col|
-
column("#{col}_id", :integer, options)
-
column("#{col}_type", :string, polymorphic.is_a?(Hash) ? polymorphic : options) if polymorphic
-
index(polymorphic ? %w(id type).map { |t| "#{col}_#{t}" } : "#{col}_id", index_options.is_a?(Hash) ? index_options : {}) if index_options
-
end
-
end
-
1
alias :belongs_to :references
-
-
1
def new_column_definition(name, type, options) # :nodoc:
-
column = create_column_definition name, type
-
limit = options.fetch(:limit) do
-
native[type][:limit] if native[type].is_a?(Hash)
-
end
-
-
column.limit = limit
-
column.array = options[:array] if column.respond_to?(:array)
-
column.precision = options[:precision]
-
column.scale = options[:scale]
-
column.default = options[:default]
-
column.null = options[:null]
-
column.first = options[:first]
-
column.after = options[:after]
-
column.primary_key = type == :primary_key || options[:primary_key]
-
column
-
end
-
-
1
private
-
1
def create_column_definition(name, type)
-
ColumnDefinition.new name, type
-
end
-
-
1
def primary_key_column_name
-
primary_key_column = columns.detect { |c| c.primary_key? }
-
primary_key_column && primary_key_column.name
-
end
-
-
1
def native
-
@native
-
end
-
end
-
-
1
class AlterTable # :nodoc:
-
1
attr_reader :adds
-
-
1
def initialize(td)
-
@td = td
-
@adds = []
-
end
-
-
1
def name; @td.name; end
-
-
1
def add_column(name, type, options)
-
name = name.to_s
-
type = type.to_sym
-
@adds << @td.new_column_definition(name, type, options)
-
end
-
end
-
-
# Represents an SQL table in an abstract way for updating a table.
-
# Also see TableDefinition and SchemaStatements#create_table
-
#
-
# Available transformations are:
-
#
-
# change_table :table do |t|
-
# t.column
-
# t.index
-
# t.rename_index
-
# t.timestamps
-
# t.change
-
# t.change_default
-
# t.rename
-
# t.references
-
# t.belongs_to
-
# t.string
-
# t.text
-
# t.integer
-
# t.float
-
# t.decimal
-
# t.datetime
-
# t.timestamp
-
# t.time
-
# t.date
-
# t.binary
-
# t.boolean
-
# t.remove
-
# t.remove_references
-
# t.remove_belongs_to
-
# t.remove_index
-
# t.remove_timestamps
-
# end
-
#
-
1
class Table
-
1
def initialize(table_name, base)
-
@table_name = table_name
-
@base = base
-
end
-
-
# Adds a new column to the named table.
-
# See TableDefinition#column for details of the options you can use.
-
#
-
# ====== Creating a simple column
-
# t.column(:name, :string)
-
1
def column(column_name, type, options = {})
-
@base.add_column(@table_name, column_name, type, options)
-
end
-
-
# Checks to see if a column exists. See SchemaStatements#column_exists?
-
1
def column_exists?(column_name, type = nil, options = {})
-
@base.column_exists?(@table_name, column_name, type, options)
-
end
-
-
# Adds a new index to the table. +column_name+ can be a single Symbol, or
-
# an Array of Symbols. See SchemaStatements#add_index
-
#
-
# ====== Creating a simple index
-
# t.index(:name)
-
# ====== Creating a unique index
-
# t.index([:branch_id, :party_id], unique: true)
-
# ====== Creating a named index
-
# t.index([:branch_id, :party_id], unique: true, name: 'by_branch_party')
-
1
def index(column_name, options = {})
-
@base.add_index(@table_name, column_name, options)
-
end
-
-
# Checks to see if an index exists. See SchemaStatements#index_exists?
-
1
def index_exists?(column_name, options = {})
-
@base.index_exists?(@table_name, column_name, options)
-
end
-
-
# Renames the given index on the table.
-
#
-
# t.rename_index(:user_id, :account_id)
-
1
def rename_index(index_name, new_index_name)
-
@base.rename_index(@table_name, index_name, new_index_name)
-
end
-
-
# Adds timestamps (+created_at+ and +updated_at+) columns to the table. See SchemaStatements#add_timestamps
-
#
-
# t.timestamps
-
1
def timestamps
-
@base.add_timestamps(@table_name)
-
end
-
-
# Changes the column's definition according to the new options.
-
# See TableDefinition#column for details of the options you can use.
-
#
-
# t.change(:name, :string, limit: 80)
-
# t.change(:description, :text)
-
1
def change(column_name, type, options = {})
-
@base.change_column(@table_name, column_name, type, options)
-
end
-
-
# Sets a new default value for a column. See SchemaStatements#change_column_default
-
#
-
# t.change_default(:qualification, 'new')
-
# t.change_default(:authorized, 1)
-
1
def change_default(column_name, default)
-
@base.change_column_default(@table_name, column_name, default)
-
end
-
-
# Removes the column(s) from the table definition.
-
#
-
# t.remove(:qualification)
-
# t.remove(:qualification, :experience)
-
1
def remove(*column_names)
-
@base.remove_columns(@table_name, *column_names)
-
end
-
-
# Removes the given index from the table.
-
#
-
# ====== Remove the index_table_name_on_column in the table_name table
-
# t.remove_index :column
-
# ====== Remove the index named index_table_name_on_branch_id in the table_name table
-
# t.remove_index column: :branch_id
-
# ====== Remove the index named index_table_name_on_branch_id_and_party_id in the table_name table
-
# t.remove_index column: [:branch_id, :party_id]
-
# ====== Remove the index named by_branch_party in the table_name table
-
# t.remove_index name: :by_branch_party
-
1
def remove_index(options = {})
-
@base.remove_index(@table_name, options)
-
end
-
-
# Removes the timestamp columns (+created_at+ and +updated_at+) from the table.
-
#
-
# t.remove_timestamps
-
1
def remove_timestamps
-
@base.remove_timestamps(@table_name)
-
end
-
-
# Renames a column.
-
#
-
# t.rename(:description, :name)
-
1
def rename(column_name, new_column_name)
-
@base.rename_column(@table_name, column_name, new_column_name)
-
end
-
-
# Adds a reference. Optionally adds a +type+ column, if <tt>:polymorphic</tt> option is provided.
-
# <tt>references</tt> and <tt>belongs_to</tt> are acceptable.
-
#
-
# t.references(:user)
-
# t.belongs_to(:supplier, polymorphic: true)
-
#
-
1
def references(*args)
-
options = args.extract_options!
-
args.each do |ref_name|
-
@base.add_reference(@table_name, ref_name, options)
-
end
-
end
-
1
alias :belongs_to :references
-
-
# Removes a reference. Optionally removes a +type+ column.
-
# <tt>remove_references</tt> and <tt>remove_belongs_to</tt> are acceptable.
-
#
-
# t.remove_references(:user)
-
# t.remove_belongs_to(:supplier, polymorphic: true)
-
#
-
1
def remove_references(*args)
-
options = args.extract_options!
-
args.each do |ref_name|
-
@base.remove_reference(@table_name, ref_name, options)
-
end
-
end
-
1
alias :remove_belongs_to :remove_references
-
-
# Adds a column or columns of a specified type
-
#
-
# t.string(:goat)
-
# t.string(:goat, :sheep)
-
1
[:string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean].each do |column_type|
-
11
define_method column_type do |*args|
-
options = args.extract_options!
-
args.each do |name|
-
@base.add_column(@table_name, name, column_type, options)
-
end
-
end
-
end
-
-
1
private
-
1
def native
-
@base.native_database_types
-
end
-
end
-
-
end
-
end
-
1
require 'ipaddr'
-
-
1
module ActiveRecord
-
1
module ConnectionAdapters # :nodoc:
-
# The goal of this module is to move Adapter specific column
-
# definitions to the Adapter instead of having it in the schema
-
# dumper itself. This code represents the normal case.
-
# We can then redefine how certain data types may be handled in the schema dumper on the
-
# Adapter level by over-writing this code inside the database specific adapters
-
1
module ColumnDumper
-
1
def column_spec(column, types)
-
spec = prepare_column_options(column, types)
-
(spec.keys - [:name, :type]).each{ |k| spec[k].insert(0, "#{k.to_s}: ")}
-
spec
-
end
-
-
# This can be overridden on a Adapter level basis to support other
-
# extended datatypes (Example: Adding an array option in the
-
# PostgreSQLAdapter)
-
1
def prepare_column_options(column, types)
-
spec = {}
-
spec[:name] = column.name.inspect
-
-
# AR has an optimization which handles zero-scale decimals as integers. This
-
# code ensures that the dumper still dumps the column as a decimal.
-
spec[:type] = if column.type == :integer && /^(numeric|decimal)/ =~ column.sql_type
-
'decimal'
-
else
-
column.type.to_s
-
end
-
spec[:limit] = column.limit.inspect if column.limit != types[column.type][:limit] && spec[:type] != 'decimal'
-
spec[:precision] = column.precision.inspect if column.precision
-
spec[:scale] = column.scale.inspect if column.scale
-
spec[:null] = 'false' unless column.null
-
spec[:default] = default_string(column.default) if column.has_default?
-
spec
-
end
-
-
# Lists the valid migration options
-
1
def migration_keys
-
[:name, :limit, :precision, :scale, :default, :null]
-
end
-
-
1
private
-
-
1
def default_string(value)
-
case value
-
when BigDecimal
-
value.to_s
-
when Date, DateTime, Time
-
"'#{value.to_s(:db)}'"
-
when Range
-
# infinity dumps as Infinity, which causes uninitialized constant error
-
value.inspect.gsub('Infinity', '::Float::INFINITY')
-
when IPAddr
-
subnet_mask = value.instance_variable_get(:@mask_addr)
-
-
# If the subnet mask is equal to /32, don't output it
-
if subnet_mask == (2**32 - 1)
-
"\"#{value.to_s}\""
-
else
-
"\"#{value.to_s}/#{subnet_mask.to_s(2).count('1')}\""
-
end
-
else
-
value.inspect
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_record/migration/join_table'
-
-
1
module ActiveRecord
-
1
module ConnectionAdapters # :nodoc:
-
1
module SchemaStatements
-
1
include ActiveRecord::Migration::JoinTable
-
-
# Returns a hash of mappings from the abstract data types to the native
-
# database types. See TableDefinition#column for details on the recognized
-
# abstract data types.
-
1
def native_database_types
-
{}
-
end
-
-
# Truncates a table alias according to the limits of the current adapter.
-
1
def table_alias_for(table_name)
-
table_name[0...table_alias_length].tr('.', '_')
-
end
-
-
# Checks to see if the table +table_name+ exists on the database.
-
#
-
# table_exists?(:developers)
-
#
-
1
def table_exists?(table_name)
-
tables.include?(table_name.to_s)
-
end
-
-
# Returns an array of indexes for the given table.
-
# def indexes(table_name, name = nil) end
-
-
# Checks to see if an index exists on a table for a given index definition.
-
#
-
# # Check an index exists
-
# index_exists?(:suppliers, :company_id)
-
#
-
# # Check an index on multiple columns exists
-
# index_exists?(:suppliers, [:company_id, :company_type])
-
#
-
# # Check a unique index exists
-
# index_exists?(:suppliers, :company_id, unique: true)
-
#
-
# # Check an index with a custom name exists
-
# index_exists?(:suppliers, :company_id, name: "idx_company_id")
-
#
-
1
def index_exists?(table_name, column_name, options = {})
-
column_names = Array(column_name)
-
index_name = options.key?(:name) ? options[:name].to_s : index_name(table_name, :column => column_names)
-
if options[:unique]
-
indexes(table_name).any?{ |i| i.unique && i.name == index_name }
-
else
-
indexes(table_name).any?{ |i| i.name == index_name }
-
end
-
end
-
-
# Returns an array of Column objects for the table specified by +table_name+.
-
# See the concrete implementation for details on the expected parameter values.
-
1
def columns(table_name) end
-
-
# Checks to see if a column exists in a given table.
-
#
-
# # Check a column exists
-
# column_exists?(:suppliers, :name)
-
#
-
# # Check a column exists of a particular type
-
# column_exists?(:suppliers, :name, :string)
-
#
-
# # Check a column exists with a specific definition
-
# column_exists?(:suppliers, :name, :string, limit: 100)
-
# column_exists?(:suppliers, :name, :string, default: 'default')
-
# column_exists?(:suppliers, :name, :string, null: false)
-
# column_exists?(:suppliers, :tax, :decimal, precision: 8, scale: 2)
-
#
-
1
def column_exists?(table_name, column_name, type = nil, options = {})
-
columns(table_name).any?{ |c| c.name == column_name.to_s &&
-
(!type || c.type == type) &&
-
(!options.key?(:limit) || c.limit == options[:limit]) &&
-
(!options.key?(:precision) || c.precision == options[:precision]) &&
-
(!options.key?(:scale) || c.scale == options[:scale]) &&
-
(!options.key?(:default) || c.default == options[:default]) &&
-
(!options.key?(:null) || c.null == options[:null]) }
-
end
-
-
# Creates a new table with the name +table_name+. +table_name+ may either
-
# be a String or a Symbol.
-
#
-
# There are two ways to work with +create_table+. You can use the block
-
# form or the regular form, like this:
-
#
-
# === Block form
-
#
-
# # create_table() passes a TableDefinition object to the block.
-
# # This form will not only create the table, but also columns for the
-
# # table.
-
#
-
# create_table(:suppliers) do |t|
-
# t.column :name, :string, limit: 60
-
# # Other fields here
-
# end
-
#
-
# === Block form, with shorthand
-
#
-
# # You can also use the column types as method calls, rather than calling the column method.
-
# create_table(:suppliers) do |t|
-
# t.string :name, limit: 60
-
# # Other fields here
-
# end
-
#
-
# === Regular form
-
#
-
# # Creates a table called 'suppliers' with no columns.
-
# create_table(:suppliers)
-
# # Add a column to 'suppliers'.
-
# add_column(:suppliers, :name, :string, {limit: 60})
-
#
-
# The +options+ hash can include the following keys:
-
# [<tt>:id</tt>]
-
# Whether to automatically add a primary key column. Defaults to true.
-
# Join tables for +has_and_belongs_to_many+ should set it to false.
-
# [<tt>:primary_key</tt>]
-
# The name of the primary key, if one is to be added automatically.
-
# Defaults to +id+. If <tt>:id</tt> is false this option is ignored.
-
#
-
# Note that Active Record models will automatically detect their
-
# primary key. This can be avoided by using +self.primary_key=+ on the model
-
# to define the key explicitly.
-
#
-
# [<tt>:options</tt>]
-
# Any extra options you want appended to the table definition.
-
# [<tt>:temporary</tt>]
-
# Make a temporary table.
-
# [<tt>:force</tt>]
-
# Set to true to drop the table before creating it.
-
# Defaults to false.
-
# [<tt>:as</tt>]
-
# SQL to use to generate the table. When this option is used, the block is
-
# ignored, as are the <tt>:id</tt> and <tt>:primary_key</tt> options.
-
#
-
# ====== Add a backend specific option to the generated SQL (MySQL)
-
#
-
# create_table(:suppliers, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8')
-
#
-
# generates:
-
#
-
# CREATE TABLE suppliers (
-
# id int(11) DEFAULT NULL auto_increment PRIMARY KEY
-
# ) ENGINE=InnoDB DEFAULT CHARSET=utf8
-
#
-
# ====== Rename the primary key column
-
#
-
# create_table(:objects, primary_key: 'guid') do |t|
-
# t.column :name, :string, limit: 80
-
# end
-
#
-
# generates:
-
#
-
# CREATE TABLE objects (
-
# guid int(11) DEFAULT NULL auto_increment PRIMARY KEY,
-
# name varchar(80)
-
# )
-
#
-
# ====== Do not add a primary key column
-
#
-
# create_table(:categories_suppliers, id: false) do |t|
-
# t.column :category_id, :integer
-
# t.column :supplier_id, :integer
-
# end
-
#
-
# generates:
-
#
-
# CREATE TABLE categories_suppliers (
-
# category_id int,
-
# supplier_id int
-
# )
-
#
-
# ====== Create a temporary table based on a query
-
#
-
# create_table(:long_query, temporary: true,
-
# as: "SELECT * FROM orders INNER JOIN line_items ON order_id=orders.id")
-
#
-
# generates:
-
#
-
# CREATE TEMPORARY TABLE long_query AS
-
# SELECT * FROM orders INNER JOIN line_items ON order_id=orders.id
-
#
-
# See also TableDefinition#column for details on how to create columns.
-
1
def create_table(table_name, options = {})
-
td = create_table_definition table_name, options[:temporary], options[:options], options[:as]
-
-
if !options[:as]
-
unless options[:id] == false
-
pk = options.fetch(:primary_key) {
-
Base.get_primary_key table_name.to_s.singularize
-
}
-
-
td.primary_key pk, options.fetch(:id, :primary_key), options
-
end
-
-
yield td if block_given?
-
end
-
-
if options[:force] && table_exists?(table_name)
-
drop_table(table_name, options)
-
end
-
-
execute schema_creation.accept td
-
td.indexes.each_pair { |c,o| add_index table_name, c, o }
-
end
-
-
# Creates a new join table with the name created using the lexical order of the first two
-
# arguments. These arguments can be a String or a Symbol.
-
#
-
# # Creates a table called 'assemblies_parts' with no id.
-
# create_join_table(:assemblies, :parts)
-
#
-
# You can pass a +options+ hash can include the following keys:
-
# [<tt>:table_name</tt>]
-
# Sets the table name overriding the default
-
# [<tt>:column_options</tt>]
-
# Any extra options you want appended to the columns definition.
-
# [<tt>:options</tt>]
-
# Any extra options you want appended to the table definition.
-
# [<tt>:temporary</tt>]
-
# Make a temporary table.
-
# [<tt>:force</tt>]
-
# Set to true to drop the table before creating it.
-
# Defaults to false.
-
#
-
# Note that +create_join_table+ does not create any indices by default; you can use
-
# its block form to do so yourself:
-
#
-
# create_join_table :products, :categories do |t|
-
# t.index :product_id
-
# t.index :category_id
-
# end
-
#
-
# ====== Add a backend specific option to the generated SQL (MySQL)
-
#
-
# create_join_table(:assemblies, :parts, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8')
-
#
-
# generates:
-
#
-
# CREATE TABLE assemblies_parts (
-
# assembly_id int NOT NULL,
-
# part_id int NOT NULL,
-
# ) ENGINE=InnoDB DEFAULT CHARSET=utf8
-
#
-
1
def create_join_table(table_1, table_2, options = {})
-
join_table_name = find_join_table_name(table_1, table_2, options)
-
-
column_options = options.delete(:column_options) || {}
-
column_options.reverse_merge!(null: false)
-
-
t1_column, t2_column = [table_1, table_2].map{ |t| t.to_s.singularize.foreign_key }
-
-
create_table(join_table_name, options.merge!(id: false)) do |td|
-
td.integer t1_column, column_options
-
td.integer t2_column, column_options
-
yield td if block_given?
-
end
-
end
-
-
# Drops the join table specified by the given arguments.
-
# See +create_join_table+ for details.
-
#
-
# Although this command ignores the block if one is given, it can be helpful
-
# to provide one in a migration's +change+ method so it can be reverted.
-
# In that case, the block will be used by create_join_table.
-
1
def drop_join_table(table_1, table_2, options = {})
-
join_table_name = find_join_table_name(table_1, table_2, options)
-
drop_table(join_table_name)
-
end
-
-
# A block for changing columns in +table+.
-
#
-
# # change_table() yields a Table instance
-
# change_table(:suppliers) do |t|
-
# t.column :name, :string, limit: 60
-
# # Other column alterations here
-
# end
-
#
-
# The +options+ hash can include the following keys:
-
# [<tt>:bulk</tt>]
-
# Set this to true to make this a bulk alter query, such as
-
#
-
# ALTER TABLE `users` ADD COLUMN age INT(11), ADD COLUMN birthdate DATETIME ...
-
#
-
# Defaults to false.
-
#
-
# ====== Add a column
-
#
-
# change_table(:suppliers) do |t|
-
# t.column :name, :string, limit: 60
-
# end
-
#
-
# ====== Add 2 integer columns
-
#
-
# change_table(:suppliers) do |t|
-
# t.integer :width, :height, null: false, default: 0
-
# end
-
#
-
# ====== Add created_at/updated_at columns
-
#
-
# change_table(:suppliers) do |t|
-
# t.timestamps
-
# end
-
#
-
# ====== Add a foreign key column
-
#
-
# change_table(:suppliers) do |t|
-
# t.references :company
-
# end
-
#
-
# Creates a <tt>company_id(integer)</tt> column.
-
#
-
# ====== Add a polymorphic foreign key column
-
#
-
# change_table(:suppliers) do |t|
-
# t.belongs_to :company, polymorphic: true
-
# end
-
#
-
# Creates <tt>company_type(varchar)</tt> and <tt>company_id(integer)</tt> columns.
-
#
-
# ====== Remove a column
-
#
-
# change_table(:suppliers) do |t|
-
# t.remove :company
-
# end
-
#
-
# ====== Remove several columns
-
#
-
# change_table(:suppliers) do |t|
-
# t.remove :company_id
-
# t.remove :width, :height
-
# end
-
#
-
# ====== Remove an index
-
#
-
# change_table(:suppliers) do |t|
-
# t.remove_index :company_id
-
# end
-
#
-
# See also Table for details on all of the various column transformation.
-
1
def change_table(table_name, options = {})
-
if supports_bulk_alter? && options[:bulk]
-
recorder = ActiveRecord::Migration::CommandRecorder.new(self)
-
yield update_table_definition(table_name, recorder)
-
bulk_change_table(table_name, recorder.commands)
-
else
-
yield update_table_definition(table_name, self)
-
end
-
end
-
-
# Renames a table.
-
#
-
# rename_table('octopuses', 'octopi')
-
#
-
1
def rename_table(table_name, new_name)
-
raise NotImplementedError, "rename_table is not implemented"
-
end
-
-
# Drops a table from the database.
-
#
-
# Although this command ignores +options+ and the block if one is given, it can be helpful
-
# to provide these in a migration's +change+ method so it can be reverted.
-
# In that case, +options+ and the block will be used by create_table.
-
1
def drop_table(table_name, options = {})
-
execute "DROP TABLE #{quote_table_name(table_name)}"
-
end
-
-
# Adds a new column to the named table.
-
# See TableDefinition#column for details of the options you can use.
-
1
def add_column(table_name, column_name, type, options = {})
-
at = create_alter_table table_name
-
at.add_column(column_name, type, options)
-
execute schema_creation.accept at
-
end
-
-
# Removes the given columns from the table definition.
-
#
-
# remove_columns(:suppliers, :qualification, :experience)
-
#
-
1
def remove_columns(table_name, *column_names)
-
raise ArgumentError.new("You must specify at least one column name. Example: remove_columns(:people, :first_name)") if column_names.empty?
-
column_names.each do |column_name|
-
remove_column(table_name, column_name)
-
end
-
end
-
-
# Removes the column from the table definition.
-
#
-
# remove_column(:suppliers, :qualification)
-
#
-
# The +type+ and +options+ parameters will be ignored if present. It can be helpful
-
# to provide these in a migration's +change+ method so it can be reverted.
-
# In that case, +type+ and +options+ will be used by add_column.
-
1
def remove_column(table_name, column_name, type = nil, options = {})
-
execute "ALTER TABLE #{quote_table_name(table_name)} DROP #{quote_column_name(column_name)}"
-
end
-
-
# Changes the column's definition according to the new options.
-
# See TableDefinition#column for details of the options you can use.
-
#
-
# change_column(:suppliers, :name, :string, limit: 80)
-
# change_column(:accounts, :description, :text)
-
#
-
1
def change_column(table_name, column_name, type, options = {})
-
raise NotImplementedError, "change_column is not implemented"
-
end
-
-
# Sets a new default value for a column:
-
#
-
# change_column_default(:suppliers, :qualification, 'new')
-
# change_column_default(:accounts, :authorized, 1)
-
#
-
# Setting the default to +nil+ effectively drops the default:
-
#
-
# change_column_default(:users, :email, nil)
-
#
-
1
def change_column_default(table_name, column_name, default)
-
raise NotImplementedError, "change_column_default is not implemented"
-
end
-
-
# Sets or removes a +NOT NULL+ constraint on a column. The +null+ flag
-
# indicates whether the value can be +NULL+. For example
-
#
-
# change_column_null(:users, :nickname, false)
-
#
-
# says nicknames cannot be +NULL+ (adds the constraint), whereas
-
#
-
# change_column_null(:users, :nickname, true)
-
#
-
# allows them to be +NULL+ (drops the constraint).
-
#
-
# The method accepts an optional fourth argument to replace existing
-
# +NULL+s with some other value. Use that one when enabling the
-
# constraint if needed, since otherwise those rows would not be valid.
-
#
-
# Please note the fourth argument does not set a column's default.
-
1
def change_column_null(table_name, column_name, null, default = nil)
-
raise NotImplementedError, "change_column_null is not implemented"
-
end
-
-
# Renames a column.
-
#
-
# rename_column(:suppliers, :description, :name)
-
#
-
1
def rename_column(table_name, column_name, new_column_name)
-
raise NotImplementedError, "rename_column is not implemented"
-
end
-
-
# Adds a new index to the table. +column_name+ can be a single Symbol, or
-
# an Array of Symbols.
-
#
-
# The index will be named after the table and the column name(s), unless
-
# you pass <tt>:name</tt> as an option.
-
#
-
# ====== Creating a simple index
-
#
-
# add_index(:suppliers, :name)
-
#
-
# generates:
-
#
-
# CREATE INDEX suppliers_name_index ON suppliers(name)
-
#
-
# ====== Creating a unique index
-
#
-
# add_index(:accounts, [:branch_id, :party_id], unique: true)
-
#
-
# generates:
-
#
-
# CREATE UNIQUE INDEX accounts_branch_id_party_id_index ON accounts(branch_id, party_id)
-
#
-
# ====== Creating a named index
-
#
-
# add_index(:accounts, [:branch_id, :party_id], unique: true, name: 'by_branch_party')
-
#
-
# generates:
-
#
-
# CREATE UNIQUE INDEX by_branch_party ON accounts(branch_id, party_id)
-
#
-
# ====== Creating an index with specific key length
-
#
-
# add_index(:accounts, :name, name: 'by_name', length: 10)
-
#
-
# generates:
-
#
-
# CREATE INDEX by_name ON accounts(name(10))
-
#
-
# add_index(:accounts, [:name, :surname], name: 'by_name_surname', length: {name: 10, surname: 15})
-
#
-
# generates:
-
#
-
# CREATE INDEX by_name_surname ON accounts(name(10), surname(15))
-
#
-
# Note: SQLite doesn't support index length.
-
#
-
# ====== Creating an index with a sort order (desc or asc, asc is the default)
-
#
-
# add_index(:accounts, [:branch_id, :party_id, :surname], order: {branch_id: :desc, party_id: :asc})
-
#
-
# generates:
-
#
-
# CREATE INDEX by_branch_desc_party ON accounts(branch_id DESC, party_id ASC, surname)
-
#
-
# Note: MySQL doesn't yet support index order (it accepts the syntax but ignores it).
-
#
-
# ====== Creating a partial index
-
#
-
# add_index(:accounts, [:branch_id, :party_id], unique: true, where: "active")
-
#
-
# generates:
-
#
-
# CREATE UNIQUE INDEX index_accounts_on_branch_id_and_party_id ON accounts(branch_id, party_id) WHERE active
-
#
-
# ====== Creating an index with a specific method
-
#
-
# add_index(:developers, :name, using: 'btree')
-
#
-
# generates:
-
#
-
# CREATE INDEX index_developers_on_name ON developers USING btree (name) -- PostgreSQL
-
# CREATE INDEX index_developers_on_name USING btree ON developers (name) -- MySQL
-
#
-
# Note: only supported by PostgreSQL and MySQL
-
#
-
# ====== Creating an index with a specific type
-
#
-
# add_index(:developers, :name, type: :fulltext)
-
#
-
# generates:
-
#
-
# CREATE FULLTEXT INDEX index_developers_on_name ON developers (name) -- MySQL
-
#
-
# Note: only supported by MySQL. Supported: <tt>:fulltext</tt> and <tt>:spatial</tt> on MyISAM tables.
-
1
def add_index(table_name, column_name, options = {})
-
index_name, index_type, index_columns, index_options = add_index_options(table_name, column_name, options)
-
execute "CREATE #{index_type} INDEX #{quote_column_name(index_name)} ON #{quote_table_name(table_name)} (#{index_columns})#{index_options}"
-
end
-
-
# Removes the given index from the table.
-
#
-
# Removes the +index_accounts_on_column+ in the +accounts+ table.
-
#
-
# remove_index :accounts, :column
-
#
-
# Removes the index named +index_accounts_on_branch_id+ in the +accounts+ table.
-
#
-
# remove_index :accounts, column: :branch_id
-
#
-
# Removes the index named +index_accounts_on_branch_id_and_party_id+ in the +accounts+ table.
-
#
-
# remove_index :accounts, column: [:branch_id, :party_id]
-
#
-
# Removes the index named +by_branch_party+ in the +accounts+ table.
-
#
-
# remove_index :accounts, name: :by_branch_party
-
#
-
1
def remove_index(table_name, options = {})
-
remove_index!(table_name, index_name_for_remove(table_name, options))
-
end
-
-
1
def remove_index!(table_name, index_name) #:nodoc:
-
execute "DROP INDEX #{quote_column_name(index_name)} ON #{quote_table_name(table_name)}"
-
end
-
-
# Renames an index.
-
#
-
# Rename the +index_people_on_last_name+ index to +index_users_on_last_name+:
-
#
-
# rename_index :people, 'index_people_on_last_name', 'index_users_on_last_name'
-
#
-
1
def rename_index(table_name, old_name, new_name)
-
# this is a naive implementation; some DBs may support this more efficiently (Postgres, for instance)
-
old_index_def = indexes(table_name).detect { |i| i.name == old_name }
-
return unless old_index_def
-
add_index(table_name, old_index_def.columns, name: new_name, unique: old_index_def.unique)
-
remove_index(table_name, name: old_name)
-
end
-
-
1
def index_name(table_name, options) #:nodoc:
-
if Hash === options
-
if options[:column]
-
"index_#{table_name}_on_#{Array(options[:column]) * '_and_'}"
-
elsif options[:name]
-
options[:name]
-
else
-
raise ArgumentError, "You must specify the index name"
-
end
-
else
-
index_name(table_name, :column => options)
-
end
-
end
-
-
# Verifies the existence of an index with a given name.
-
#
-
# The default argument is returned if the underlying implementation does not define the indexes method,
-
# as there's no way to determine the correct answer in that case.
-
1
def index_name_exists?(table_name, index_name, default)
-
return default unless respond_to?(:indexes)
-
index_name = index_name.to_s
-
indexes(table_name).detect { |i| i.name == index_name }
-
end
-
-
# Adds a reference. Optionally adds a +type+ column, if <tt>:polymorphic</tt> option is provided.
-
# <tt>add_reference</tt> and <tt>add_belongs_to</tt> are acceptable.
-
#
-
# ====== Create a user_id column
-
#
-
# add_reference(:products, :user)
-
#
-
# ====== Create a supplier_id and supplier_type columns
-
#
-
# add_belongs_to(:products, :supplier, polymorphic: true)
-
#
-
# ====== Create a supplier_id, supplier_type columns and appropriate index
-
#
-
# add_reference(:products, :supplier, polymorphic: true, index: true)
-
#
-
1
def add_reference(table_name, ref_name, options = {})
-
polymorphic = options.delete(:polymorphic)
-
index_options = options.delete(:index)
-
add_column(table_name, "#{ref_name}_id", :integer, options)
-
add_column(table_name, "#{ref_name}_type", :string, polymorphic.is_a?(Hash) ? polymorphic : options) if polymorphic
-
add_index(table_name, polymorphic ? %w[id type].map{ |t| "#{ref_name}_#{t}" } : "#{ref_name}_id", index_options.is_a?(Hash) ? index_options : {}) if index_options
-
end
-
1
alias :add_belongs_to :add_reference
-
-
# Removes the reference(s). Also removes a +type+ column if one exists.
-
# <tt>remove_reference</tt>, <tt>remove_references</tt> and <tt>remove_belongs_to</tt> are acceptable.
-
#
-
# ====== Remove the reference
-
#
-
# remove_reference(:products, :user, index: true)
-
#
-
# ====== Remove polymorphic reference
-
#
-
# remove_reference(:products, :supplier, polymorphic: true)
-
#
-
1
def remove_reference(table_name, ref_name, options = {})
-
remove_column(table_name, "#{ref_name}_id")
-
remove_column(table_name, "#{ref_name}_type") if options[:polymorphic]
-
end
-
1
alias :remove_belongs_to :remove_reference
-
-
1
def dump_schema_information #:nodoc:
-
sm_table = ActiveRecord::Migrator.schema_migrations_table_name
-
-
ActiveRecord::SchemaMigration.order('version').map { |sm|
-
"INSERT INTO #{sm_table} (version) VALUES ('#{sm.version}');"
-
}.join "\n\n"
-
end
-
-
# Should not be called normally, but this operation is non-destructive.
-
# The migrations module handles this automatically.
-
1
def initialize_schema_migrations_table
-
ActiveRecord::SchemaMigration.create_table
-
end
-
-
1
def assume_migrated_upto_version(version, migrations_paths = ActiveRecord::Migrator.migrations_paths)
-
migrations_paths = Array(migrations_paths)
-
version = version.to_i
-
sm_table = quote_table_name(ActiveRecord::Migrator.schema_migrations_table_name)
-
-
migrated = select_values("SELECT version FROM #{sm_table}").map { |v| v.to_i }
-
paths = migrations_paths.map {|p| "#{p}/[0-9]*_*.rb" }
-
versions = Dir[*paths].map do |filename|
-
filename.split('/').last.split('_').first.to_i
-
end
-
-
unless migrated.include?(version)
-
execute "INSERT INTO #{sm_table} (version) VALUES ('#{version}')"
-
end
-
-
inserted = Set.new
-
(versions - migrated).each do |v|
-
if inserted.include?(v)
-
raise "Duplicate migration #{v}. Please renumber your migrations to resolve the conflict."
-
elsif v < version
-
execute "INSERT INTO #{sm_table} (version) VALUES ('#{v}')"
-
inserted << v
-
end
-
end
-
end
-
-
1
def type_to_sql(type, limit = nil, precision = nil, scale = nil) #:nodoc:
-
if native = native_database_types[type.to_sym]
-
column_type_sql = (native.is_a?(Hash) ? native[:name] : native).dup
-
-
if type == :decimal # ignore limit, use precision and scale
-
scale ||= native[:scale]
-
-
if precision ||= native[:precision]
-
if scale
-
column_type_sql << "(#{precision},#{scale})"
-
else
-
column_type_sql << "(#{precision})"
-
end
-
elsif scale
-
raise ArgumentError, "Error adding decimal column: precision cannot be empty if scale is specified"
-
end
-
-
elsif (type != :primary_key) && (limit ||= native.is_a?(Hash) && native[:limit])
-
column_type_sql << "(#{limit})"
-
end
-
-
column_type_sql
-
else
-
type.to_s
-
end
-
end
-
-
# Given a set of columns and an ORDER BY clause, returns the columns for a SELECT DISTINCT.
-
# Both PostgreSQL and Oracle overrides this for custom DISTINCT syntax - they
-
# require the order columns appear in the SELECT.
-
#
-
# columns_for_distinct("posts.id", ["posts.created_at desc"])
-
1
def columns_for_distinct(columns, orders) #:nodoc:
-
columns
-
end
-
-
# Adds timestamps (+created_at+ and +updated_at+) columns to the named table.
-
#
-
# add_timestamps(:suppliers)
-
#
-
1
def add_timestamps(table_name)
-
add_column table_name, :created_at, :datetime
-
add_column table_name, :updated_at, :datetime
-
end
-
-
# Removes the timestamp columns (+created_at+ and +updated_at+) from the table definition.
-
#
-
# remove_timestamps(:suppliers)
-
#
-
1
def remove_timestamps(table_name)
-
remove_column table_name, :updated_at
-
remove_column table_name, :created_at
-
end
-
-
1
def update_table_definition(table_name, base) #:nodoc:
-
Table.new(table_name, base)
-
end
-
-
1
protected
-
1
def add_index_sort_order(option_strings, column_names, options = {})
-
if options.is_a?(Hash) && order = options[:order]
-
case order
-
when Hash
-
column_names.each {|name| option_strings[name] += " #{order[name].upcase}" if order.has_key?(name)}
-
when String
-
column_names.each {|name| option_strings[name] += " #{order.upcase}"}
-
end
-
end
-
-
return option_strings
-
end
-
-
# Overridden by the mysql adapter for supporting index lengths
-
1
def quoted_columns_for_index(column_names, options = {})
-
option_strings = Hash[column_names.map {|name| [name, '']}]
-
-
# add index sort order if supported
-
if supports_index_sort_order?
-
option_strings = add_index_sort_order(option_strings, column_names, options)
-
end
-
-
column_names.map {|name| quote_column_name(name) + option_strings[name]}
-
end
-
-
1
def options_include_default?(options)
-
options.include?(:default) && !(options[:null] == false && options[:default].nil?)
-
end
-
-
1
def add_index_options(table_name, column_name, options = {})
-
column_names = Array(column_name)
-
index_name = index_name(table_name, column: column_names)
-
-
options.assert_valid_keys(:unique, :order, :name, :where, :length, :internal, :using, :algorithm, :type)
-
-
index_type = options[:unique] ? "UNIQUE" : ""
-
index_type = options[:type].to_s if options.key?(:type)
-
index_name = options[:name].to_s if options.key?(:name)
-
max_index_length = options.fetch(:internal, false) ? index_name_length : allowed_index_name_length
-
-
if options.key?(:algorithm)
-
algorithm = index_algorithms.fetch(options[:algorithm]) {
-
raise ArgumentError.new("Algorithm must be one of the following: #{index_algorithms.keys.map(&:inspect).join(', ')}")
-
}
-
end
-
-
using = "USING #{options[:using]}" if options[:using].present?
-
-
if supports_partial_index?
-
index_options = options[:where] ? " WHERE #{options[:where]}" : ""
-
end
-
-
if index_name.length > max_index_length
-
raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' is too long; the limit is #{max_index_length} characters"
-
end
-
if index_name_exists?(table_name, index_name, false)
-
raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' already exists"
-
end
-
index_columns = quoted_columns_for_index(column_names, options).join(", ")
-
-
[index_name, index_type, index_columns, index_options, algorithm, using]
-
end
-
-
1
def index_name_for_remove(table_name, options = {})
-
index_name = index_name(table_name, options)
-
-
unless index_name_exists?(table_name, index_name, true)
-
if options.is_a?(Hash) && options.has_key?(:name)
-
options_without_column = options.dup
-
options_without_column.delete :column
-
index_name_without_column = index_name(table_name, options_without_column)
-
-
return index_name_without_column if index_name_exists?(table_name, index_name_without_column, false)
-
end
-
-
raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' does not exist"
-
end
-
-
index_name
-
end
-
-
1
def rename_table_indexes(table_name, new_name)
-
indexes(new_name).each do |index|
-
generated_index_name = index_name(table_name, column: index.columns)
-
if generated_index_name == index.name
-
rename_index new_name, generated_index_name, index_name(new_name, column: index.columns)
-
end
-
end
-
end
-
-
1
def rename_column_indexes(table_name, column_name, new_column_name)
-
column_name, new_column_name = column_name.to_s, new_column_name.to_s
-
indexes(table_name).each do |index|
-
next unless index.columns.include?(new_column_name)
-
old_columns = index.columns.dup
-
old_columns[old_columns.index(new_column_name)] = column_name
-
generated_index_name = index_name(table_name, column: old_columns)
-
if generated_index_name == index.name
-
rename_index table_name, generated_index_name, index_name(table_name, column: index.columns)
-
end
-
end
-
end
-
-
1
private
-
1
def create_table_definition(name, temporary, options, as = nil)
-
TableDefinition.new native_database_types, name, temporary, options, as
-
end
-
-
1
def create_alter_table(name)
-
AlterTable.new create_table_definition(name, false, {})
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ConnectionAdapters
-
1
class Transaction #:nodoc:
-
1
attr_reader :connection
-
-
1
def initialize(connection)
-
1
@connection = connection
-
1
@state = TransactionState.new
-
end
-
-
1
def state
-
@state
-
end
-
end
-
-
1
class TransactionState
-
1
attr_accessor :parent
-
-
1
VALID_STATES = Set.new([:committed, :rolledback, nil])
-
-
1
def initialize(state = nil)
-
1
@state = state
-
1
@parent = nil
-
end
-
-
1
def finalized?
-
@state
-
end
-
-
1
def committed?
-
@state == :committed
-
end
-
-
1
def rolledback?
-
@state == :rolledback
-
end
-
-
1
def set_state(state)
-
if !VALID_STATES.include?(state)
-
raise ArgumentError, "Invalid transaction state: #{state}"
-
end
-
@state = state
-
end
-
end
-
-
1
class ClosedTransaction < Transaction #:nodoc:
-
1
def number
-
0
-
end
-
-
1
def begin(options = {})
-
RealTransaction.new(connection, self, options)
-
end
-
-
1
def closed?
-
true
-
end
-
-
1
def open?
-
false
-
end
-
-
1
def joinable?
-
false
-
end
-
-
# This is a noop when there are no open transactions
-
1
def add_record(record)
-
end
-
end
-
-
1
class OpenTransaction < Transaction #:nodoc:
-
1
attr_reader :parent, :records
-
1
attr_writer :joinable
-
-
1
def initialize(connection, parent, options = {})
-
super connection
-
-
@parent = parent
-
@records = []
-
@finishing = false
-
@joinable = options.fetch(:joinable, true)
-
end
-
-
# This state is necessary so that we correctly handle stuff that might
-
# happen in a commit/rollback. But it's kinda distasteful. Maybe we can
-
# find a better way to structure it in the future.
-
1
def finishing?
-
@finishing
-
end
-
-
1
def joinable?
-
@joinable && !finishing?
-
end
-
-
1
def number
-
if finishing?
-
parent.number
-
else
-
parent.number + 1
-
end
-
end
-
-
1
def begin(options = {})
-
if finishing?
-
parent.begin
-
else
-
SavepointTransaction.new(connection, self, options)
-
end
-
end
-
-
1
def rollback
-
@finishing = true
-
perform_rollback
-
parent
-
end
-
-
1
def commit
-
@finishing = true
-
perform_commit
-
parent
-
end
-
-
1
def add_record(record)
-
if record.has_transactional_callbacks?
-
records << record
-
else
-
record.set_transaction_state(@state)
-
end
-
end
-
-
1
def rollback_records
-
@state.set_state(:rolledback)
-
records.uniq.each do |record|
-
begin
-
record.rolledback!(parent.closed?)
-
rescue => e
-
record.logger.error(e) if record.respond_to?(:logger) && record.logger
-
end
-
end
-
end
-
-
1
def commit_records
-
@state.set_state(:committed)
-
records.uniq.each do |record|
-
begin
-
record.committed!
-
rescue => e
-
record.logger.error(e) if record.respond_to?(:logger) && record.logger
-
end
-
end
-
end
-
-
1
def closed?
-
false
-
end
-
-
1
def open?
-
true
-
end
-
end
-
-
1
class RealTransaction < OpenTransaction #:nodoc:
-
1
def initialize(connection, parent, options = {})
-
super
-
-
if options[:isolation]
-
connection.begin_isolated_db_transaction(options[:isolation])
-
else
-
connection.begin_db_transaction
-
end
-
end
-
-
1
def perform_rollback
-
connection.rollback_db_transaction
-
rollback_records
-
end
-
-
1
def perform_commit
-
connection.commit_db_transaction
-
commit_records
-
end
-
end
-
-
1
class SavepointTransaction < OpenTransaction #:nodoc:
-
1
def initialize(connection, parent, options = {})
-
if options[:isolation]
-
raise ActiveRecord::TransactionIsolationError, "cannot set transaction isolation in a nested transaction"
-
end
-
-
super
-
connection.create_savepoint
-
end
-
-
1
def perform_rollback
-
connection.rollback_to_savepoint
-
rollback_records
-
end
-
-
1
def perform_commit
-
@state.set_state(:committed)
-
@state.parent = parent.state
-
connection.release_savepoint
-
end
-
end
-
end
-
end
-
1
require 'date'
-
1
require 'bigdecimal'
-
1
require 'bigdecimal/util'
-
1
require 'active_support/core_ext/benchmark'
-
1
require 'active_record/connection_adapters/schema_cache'
-
1
require 'active_record/connection_adapters/abstract/schema_dumper'
-
1
require 'active_record/connection_adapters/abstract/schema_creation'
-
1
require 'monitor'
-
-
1
module ActiveRecord
-
1
module ConnectionAdapters # :nodoc:
-
1
extend ActiveSupport::Autoload
-
-
1
autoload :Column
-
1
autoload :ConnectionSpecification
-
-
1
autoload_at 'active_record/connection_adapters/abstract/schema_definitions' do
-
1
autoload :IndexDefinition
-
1
autoload :ColumnDefinition
-
1
autoload :ChangeColumnDefinition
-
1
autoload :TableDefinition
-
1
autoload :Table
-
1
autoload :AlterTable
-
end
-
-
1
autoload_at 'active_record/connection_adapters/abstract/connection_pool' do
-
1
autoload :ConnectionHandler
-
1
autoload :ConnectionManagement
-
end
-
-
1
autoload_under 'abstract' do
-
1
autoload :SchemaStatements
-
1
autoload :DatabaseStatements
-
1
autoload :DatabaseLimits
-
1
autoload :Quoting
-
1
autoload :ConnectionPool
-
1
autoload :QueryCache
-
1
autoload :Savepoints
-
end
-
-
1
autoload_at 'active_record/connection_adapters/abstract/transaction' do
-
1
autoload :ClosedTransaction
-
1
autoload :RealTransaction
-
1
autoload :SavepointTransaction
-
1
autoload :TransactionState
-
end
-
-
# Active Record supports multiple database systems. AbstractAdapter and
-
# related classes form the abstraction layer which makes this possible.
-
# An AbstractAdapter represents a connection to a database, and provides an
-
# abstract interface for database-specific functionality such as establishing
-
# a connection, escaping values, building the right SQL fragments for ':offset'
-
# and ':limit' options, etc.
-
#
-
# All the concrete database adapters follow the interface laid down in this class.
-
# ActiveRecord::Base.connection returns an AbstractAdapter object, which
-
# you can use.
-
#
-
# Most of the methods in the adapter are useful during migrations. Most
-
# notably, the instance methods provided by SchemaStatement are very useful.
-
1
class AbstractAdapter
-
1
include Quoting, DatabaseStatements, SchemaStatements
-
1
include DatabaseLimits
-
1
include QueryCache
-
1
include ActiveSupport::Callbacks
-
1
include MonitorMixin
-
1
include ColumnDumper
-
-
1
SIMPLE_INT = /\A\d+\z/
-
-
1
define_callbacks :checkout, :checkin
-
-
1
attr_accessor :visitor, :pool
-
1
attr_reader :schema_cache, :last_use, :in_use, :logger
-
1
alias :in_use? :in_use
-
-
1
def self.type_cast_config_to_integer(config)
-
1
if config =~ SIMPLE_INT
-
config.to_i
-
else
-
1
config
-
end
-
end
-
-
1
def self.type_cast_config_to_boolean(config)
-
1
if config == "false"
-
false
-
else
-
1
config
-
end
-
end
-
-
1
def initialize(connection, logger = nil, pool = nil) #:nodoc:
-
1
super()
-
-
1
@connection = connection
-
1
@in_use = false
-
1
@instrumenter = ActiveSupport::Notifications.instrumenter
-
1
@last_use = false
-
1
@logger = logger
-
1
@pool = pool
-
1
@schema_cache = SchemaCache.new self
-
1
@visitor = nil
-
1
@prepared_statements = false
-
end
-
-
1
def valid_type?(type)
-
true
-
end
-
-
1
def schema_creation
-
SchemaCreation.new self
-
end
-
-
1
def lease
-
1
synchronize do
-
1
unless in_use
-
1
@in_use = true
-
1
@last_use = Time.now
-
end
-
end
-
end
-
-
1
def schema_cache=(cache)
-
cache.connection = self
-
@schema_cache = cache
-
end
-
-
1
def expire
-
@in_use = false
-
end
-
-
1
def unprepared_visitor
-
self.class::BindSubstitution.new self
-
end
-
-
1
def unprepared_statement
-
old_prepared_statements, @prepared_statements = @prepared_statements, false
-
old_visitor, @visitor = @visitor, unprepared_visitor
-
yield
-
ensure
-
@visitor, @prepared_statements = old_visitor, old_prepared_statements
-
end
-
-
# Returns the human-readable name of the adapter. Use mixed case - one
-
# can always use downcase if needed.
-
1
def adapter_name
-
'Abstract'
-
end
-
-
# Does this adapter support migrations? Backend specific, as the
-
# abstract adapter always returns +false+.
-
1
def supports_migrations?
-
false
-
end
-
-
# Can this adapter determine the primary key for tables not attached
-
# to an Active Record class, such as join tables? Backend specific, as
-
# the abstract adapter always returns +false+.
-
1
def supports_primary_key?
-
false
-
end
-
-
# Does this adapter support using DISTINCT within COUNT? This is +true+
-
# for all adapters except sqlite.
-
1
def supports_count_distinct?
-
true
-
end
-
-
# Does this adapter support DDL rollbacks in transactions? That is, would
-
# CREATE TABLE or ALTER TABLE get rolled back by a transaction? PostgreSQL,
-
# SQL Server, and others support this. MySQL and others do not.
-
1
def supports_ddl_transactions?
-
false
-
end
-
-
1
def supports_bulk_alter?
-
false
-
end
-
-
# Does this adapter support savepoints? PostgreSQL and MySQL do,
-
# SQLite < 3.6.8 does not.
-
1
def supports_savepoints?
-
false
-
end
-
-
# Should primary key values be selected from their corresponding
-
# sequence before the insert statement? If true, next_sequence_value
-
# is called before each insert to set the record's primary key.
-
# This is false for all adapters but Firebird.
-
1
def prefetch_primary_key?(table_name = nil)
-
false
-
end
-
-
# Does this adapter support index sort order?
-
1
def supports_index_sort_order?
-
false
-
end
-
-
# Does this adapter support partial indices?
-
1
def supports_partial_index?
-
false
-
end
-
-
# Does this adapter support explain? As of this writing sqlite3,
-
# mysql2, and postgresql are the only ones that do.
-
1
def supports_explain?
-
false
-
end
-
-
# Does this adapter support setting the isolation level for a transaction?
-
1
def supports_transaction_isolation?
-
false
-
end
-
-
# Does this adapter support database extensions? As of this writing only
-
# postgresql does.
-
1
def supports_extensions?
-
false
-
end
-
-
# This is meant to be implemented by the adapters that support extensions
-
1
def disable_extension(name)
-
end
-
-
# This is meant to be implemented by the adapters that support extensions
-
1
def enable_extension(name)
-
end
-
-
# A list of extensions, to be filled in by adapters that support them. At
-
# the moment only postgresql does.
-
1
def extensions
-
[]
-
end
-
-
# A list of index algorithms, to be filled by adapters that support them.
-
# MySQL and PostgreSQL have support for them right now.
-
1
def index_algorithms
-
{}
-
end
-
-
# QUOTING ==================================================
-
-
# Returns a bind substitution value given a bind +index+ and +column+
-
# NOTE: The column param is currently being used by the sqlserver-adapter
-
1
def substitute_at(column, index)
-
Arel::Nodes::BindParam.new '?'
-
end
-
-
# REFERENTIAL INTEGRITY ====================================
-
-
# Override to turn off referential integrity while executing <tt>&block</tt>.
-
1
def disable_referential_integrity
-
yield
-
end
-
-
# CONNECTION MANAGEMENT ====================================
-
-
# Checks whether the connection to the database is still active. This includes
-
# checking whether the database is actually capable of responding, i.e. whether
-
# the connection isn't stale.
-
1
def active?
-
end
-
-
# Adapter should redefine this if it needs a threadsafe way to approximate
-
# if the connection is active
-
1
def active_threadsafe?
-
active?
-
end
-
-
# Disconnects from the database if already connected, and establishes a
-
# new connection with the database. Implementors should call super if they
-
# override the default implementation.
-
1
def reconnect!
-
clear_cache!
-
reset_transaction
-
end
-
-
# Disconnects from the database if already connected. Otherwise, this
-
# method does nothing.
-
1
def disconnect!
-
clear_cache!
-
reset_transaction
-
end
-
-
# Reset the state of this connection, directing the DBMS to clear
-
# transactions and other connection-related server-side state. Usually a
-
# database-dependent operation.
-
#
-
# The default implementation does nothing; the implementation should be
-
# overridden by concrete adapters.
-
1
def reset!
-
# this should be overridden by concrete adapters
-
end
-
-
###
-
# Clear any caching the database adapter may be doing, for example
-
# clearing the prepared statement cache. This is database specific.
-
1
def clear_cache!
-
# this should be overridden by concrete adapters
-
end
-
-
# Returns true if its required to reload the connection between requests for development mode.
-
# This is not the case for Ruby/MySQL and it's not necessary for any adapters except SQLite.
-
1
def requires_reloading?
-
false
-
end
-
-
# Checks whether the connection to the database is still active (i.e. not stale).
-
# This is done under the hood by calling <tt>active?</tt>. If the connection
-
# is no longer active, then this method will reconnect to the database.
-
1
def verify!(*ignored)
-
1
reconnect! unless active?
-
end
-
-
# Provides access to the underlying database driver for this adapter. For
-
# example, this method returns a Mysql object in case of MysqlAdapter,
-
# and a PGconn object in case of PostgreSQLAdapter.
-
#
-
# This is useful for when you need to call a proprietary method such as
-
# PostgreSQL's lo_* methods.
-
1
def raw_connection
-
@connection
-
end
-
-
1
def open_transactions
-
@transaction.number
-
end
-
-
1
def create_savepoint(name = nil)
-
end
-
-
1
def rollback_to_savepoint(name = nil)
-
end
-
-
1
def release_savepoint(name = nil)
-
end
-
-
1
def case_sensitive_modifier(node)
-
node
-
end
-
-
1
def case_insensitive_comparison(table, attribute, column, value)
-
table[attribute].lower.eq(table.lower(value))
-
end
-
-
1
def current_savepoint_name
-
"active_record_#{open_transactions}"
-
end
-
-
# Check the connection back in to the connection pool
-
1
def close
-
pool.checkin self
-
end
-
-
1
protected
-
-
1
def translate_exception_class(e, sql)
-
message = "#{e.class.name}: #{e.message}: #{sql}"
-
@logger.error message if @logger
-
exception = translate_exception(e, message)
-
exception.set_backtrace e.backtrace
-
exception
-
end
-
-
1
def log(sql, name = "SQL", binds = [], statement_name = nil)
-
@instrumenter.instrument(
-
"sql.active_record",
-
:sql => sql,
-
:name => name,
-
:connection_id => object_id,
-
:statement_name => statement_name,
-
18
:binds => binds) { yield }
-
rescue => e
-
raise translate_exception_class(e, sql)
-
end
-
-
1
def translate_exception(exception, message)
-
# override in derived class
-
ActiveRecord::StatementInvalid.new(message, exception)
-
end
-
-
1
def without_prepared_statement?(binds)
-
1
!@prepared_statements || binds.empty?
-
end
-
end
-
end
-
end
-
1
require 'set'
-
-
1
module ActiveRecord
-
# :stopdoc:
-
1
module ConnectionAdapters
-
# An abstract definition of a column in a table.
-
1
class Column
-
1
TRUE_VALUES = [true, 1, '1', 't', 'T', 'true', 'TRUE', 'on', 'ON'].to_set
-
1
FALSE_VALUES = [false, 0, '0', 'f', 'F', 'false', 'FALSE', 'off', 'OFF'].to_set
-
-
1
module Format
-
1
ISO_DATE = /\A(\d{4})-(\d\d)-(\d\d)\z/
-
1
ISO_DATETIME = /\A(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)(\.\d+)?\z/
-
end
-
-
1
attr_reader :name, :default, :type, :limit, :null, :sql_type, :precision, :scale, :default_function
-
1
attr_accessor :primary, :coder
-
-
1
alias :encoded? :coder
-
-
# Instantiates a new column in the table.
-
#
-
# +name+ is the column's name, such as <tt>supplier_id</tt> in <tt>supplier_id int(11)</tt>.
-
# +default+ is the type-casted default value, such as +new+ in <tt>sales_stage varchar(20) default 'new'</tt>.
-
# +sql_type+ is used to extract the column's length, if necessary. For example +60+ in
-
# <tt>company_name varchar(60)</tt>.
-
# It will be mapped to one of the standard Rails SQL types in the <tt>type</tt> attribute.
-
# +null+ determines if this column allows +NULL+ values.
-
1
def initialize(name, default, sql_type = nil, null = true)
-
@name = name
-
@sql_type = sql_type
-
@null = null
-
@limit = extract_limit(sql_type)
-
@precision = extract_precision(sql_type)
-
@scale = extract_scale(sql_type)
-
@type = simplified_type(sql_type)
-
@default = extract_default(default)
-
@default_function = nil
-
@primary = nil
-
@coder = nil
-
end
-
-
# Returns +true+ if the column is either of type string or text.
-
1
def text?
-
type == :string || type == :text
-
end
-
-
# Returns +true+ if the column is either of type integer, float or decimal.
-
1
def number?
-
type == :integer || type == :float || type == :decimal
-
end
-
-
1
def has_default?
-
!default.nil?
-
end
-
-
# Returns the Ruby class that corresponds to the abstract data type.
-
1
def klass
-
case type
-
when :integer then Fixnum
-
when :float then Float
-
when :decimal then BigDecimal
-
when :datetime, :timestamp, :time then Time
-
when :date then Date
-
when :text, :string, :binary then String
-
when :boolean then Object
-
end
-
end
-
-
1
def binary?
-
type == :binary
-
end
-
-
# Casts a Ruby value to something appropriate for writing to the database.
-
1
def type_cast_for_write(value)
-
return value unless number?
-
-
case value
-
when FalseClass
-
0
-
when TrueClass
-
1
-
when String
-
value.presence
-
else
-
value
-
end
-
end
-
-
# Casts value (which is a String) to an appropriate instance.
-
1
def type_cast(value)
-
return nil if value.nil?
-
return coder.load(value) if encoded?
-
-
klass = self.class
-
-
case type
-
when :string, :text then value
-
when :integer then klass.value_to_integer(value)
-
when :float then value.to_f
-
when :decimal then klass.value_to_decimal(value)
-
when :datetime, :timestamp then klass.string_to_time(value)
-
when :time then klass.string_to_dummy_time(value)
-
when :date then klass.value_to_date(value)
-
when :binary then klass.binary_to_string(value)
-
when :boolean then klass.value_to_boolean(value)
-
else value
-
end
-
end
-
-
# Returns the human name of the column name.
-
#
-
# ===== Examples
-
# Column.new('sales_stage', ...).human_name # => 'Sales stage'
-
1
def human_name
-
Base.human_attribute_name(@name)
-
end
-
-
1
def extract_default(default)
-
type_cast(default)
-
end
-
-
1
class << self
-
# Used to convert from BLOBs to Strings
-
1
def binary_to_string(value)
-
value
-
end
-
-
1
def value_to_date(value)
-
if value.is_a?(String)
-
return nil if value.empty?
-
fast_string_to_date(value) || fallback_string_to_date(value)
-
elsif value.respond_to?(:to_date)
-
value.to_date
-
else
-
value
-
end
-
end
-
-
1
def string_to_time(string)
-
return string unless string.is_a?(String)
-
return nil if string.empty?
-
-
fast_string_to_time(string) || fallback_string_to_time(string)
-
end
-
-
1
def string_to_dummy_time(string)
-
return string unless string.is_a?(String)
-
return nil if string.empty?
-
-
dummy_time_string = "2000-01-01 #{string}"
-
-
fast_string_to_time(dummy_time_string) || begin
-
time_hash = Date._parse(dummy_time_string)
-
return nil if time_hash[:hour].nil?
-
new_time(*time_hash.values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction))
-
end
-
end
-
-
# convert something to a boolean
-
1
def value_to_boolean(value)
-
if value.is_a?(String) && value.empty?
-
nil
-
else
-
TRUE_VALUES.include?(value)
-
end
-
end
-
-
# Used to convert values to integer.
-
# handle the case when an integer column is used to store boolean values
-
1
def value_to_integer(value)
-
case value
-
when TrueClass, FalseClass
-
value ? 1 : 0
-
else
-
value.to_i rescue nil
-
end
-
end
-
-
# convert something to a BigDecimal
-
1
def value_to_decimal(value)
-
# Using .class is faster than .is_a? and
-
# subclasses of BigDecimal will be handled
-
# in the else clause
-
if value.class == BigDecimal
-
value
-
elsif value.respond_to?(:to_d)
-
value.to_d
-
else
-
value.to_s.to_d
-
end
-
end
-
-
1
protected
-
# '0.123456' -> 123456
-
# '1.123456' -> 123456
-
1
def microseconds(time)
-
time[:sec_fraction] ? (time[:sec_fraction] * 1_000_000).to_i : 0
-
end
-
-
1
def new_date(year, mon, mday)
-
if year && year != 0
-
Date.new(year, mon, mday) rescue nil
-
end
-
end
-
-
1
def new_time(year, mon, mday, hour, min, sec, microsec, offset = nil)
-
# Treat 0000-00-00 00:00:00 as nil.
-
return nil if year.nil? || (year == 0 && mon == 0 && mday == 0)
-
-
if offset
-
time = Time.utc(year, mon, mday, hour, min, sec, microsec) rescue nil
-
return nil unless time
-
-
time -= offset
-
Base.default_timezone == :utc ? time : time.getlocal
-
else
-
Time.public_send(Base.default_timezone, year, mon, mday, hour, min, sec, microsec) rescue nil
-
end
-
end
-
-
1
def fast_string_to_date(string)
-
if string =~ Format::ISO_DATE
-
new_date $1.to_i, $2.to_i, $3.to_i
-
end
-
end
-
-
# Doesn't handle time zones.
-
1
def fast_string_to_time(string)
-
if string =~ Format::ISO_DATETIME
-
microsec = ($7.to_r * 1_000_000).to_i
-
new_time $1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i, microsec
-
end
-
end
-
-
1
def fallback_string_to_date(string)
-
new_date(*::Date._parse(string, false).values_at(:year, :mon, :mday))
-
end
-
-
1
def fallback_string_to_time(string)
-
time_hash = Date._parse(string)
-
time_hash[:sec_fraction] = microseconds(time_hash)
-
-
new_time(*time_hash.values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction, :offset))
-
end
-
end
-
-
1
private
-
1
def extract_limit(sql_type)
-
$1.to_i if sql_type =~ /\((.*)\)/
-
end
-
-
1
def extract_precision(sql_type)
-
$2.to_i if sql_type =~ /^(numeric|decimal|number)\((\d+)(,\d+)?\)/i
-
end
-
-
1
def extract_scale(sql_type)
-
case sql_type
-
when /^(numeric|decimal|number)\((\d+)\)/i then 0
-
when /^(numeric|decimal|number)\((\d+)(,(\d+))\)/i then $4.to_i
-
end
-
end
-
-
1
def simplified_type(field_type)
-
case field_type
-
when /int/i
-
:integer
-
when /float|double/i
-
:float
-
when /decimal|numeric|number/i
-
extract_scale(field_type) == 0 ? :integer : :decimal
-
when /datetime/i
-
:datetime
-
when /timestamp/i
-
:timestamp
-
when /time/i
-
:time
-
when /date/i
-
:date
-
when /clob/i, /text/i
-
:text
-
when /blob/i, /binary/i
-
:binary
-
when /char/i
-
:string
-
when /boolean/i
-
:boolean
-
end
-
end
-
end
-
end
-
# :startdoc:
-
end
-
1
require 'uri'
-
-
1
module ActiveRecord
-
1
module ConnectionAdapters
-
1
class ConnectionSpecification #:nodoc:
-
1
attr_reader :config, :adapter_method
-
-
1
def initialize(config, adapter_method)
-
1
@config, @adapter_method = config, adapter_method
-
end
-
-
1
def initialize_dup(original)
-
@config = original.config.dup
-
end
-
-
# Expands a connection string into a hash.
-
1
class ConnectionUrlResolver # :nodoc:
-
-
# == Example
-
#
-
# url = "postgresql://foo:bar@localhost:9000/foo_test?pool=5&timeout=3000"
-
# ConnectionUrlResolver.new(url).to_hash
-
# # => {
-
# "adapter" => "postgresql",
-
# "host" => "localhost",
-
# "port" => 9000,
-
# "database" => "foo_test",
-
# "username" => "foo",
-
# "password" => "bar",
-
# "pool" => "5",
-
# "timeout" => "3000"
-
# }
-
1
def initialize(url)
-
raise "Database URL cannot be empty" if url.blank?
-
@uri = URI.parse(url)
-
@adapter = @uri.scheme.gsub('-', '_')
-
@adapter = "postgresql" if @adapter == "postgres"
-
-
if @uri.opaque
-
@uri.opaque, @query = @uri.opaque.split('?', 2)
-
else
-
@query = @uri.query
-
end
-
@authority = url =~ %r{\A[^:]*://}
-
end
-
-
# Converts the given URL to a full connection hash.
-
1
def to_hash
-
config = raw_config.reject { |_,value| value.blank? }
-
config.map { |key,value| config[key] = uri_parser.unescape(value) if value.is_a? String }
-
config
-
end
-
-
1
private
-
-
1
def uri
-
@uri
-
end
-
-
1
def uri_parser
-
@uri_parser ||= URI::Parser.new
-
end
-
-
# Converts the query parameters of the URI into a hash.
-
#
-
# "localhost?pool=5&reap_frequency=2"
-
# # => { "pool" => "5", "reap_frequency" => "2" }
-
#
-
# returns empty hash if no query present.
-
#
-
# "localhost"
-
# # => {}
-
1
def query_hash
-
Hash[(@query || '').split("&").map { |pair| pair.split("=") }]
-
end
-
-
1
def raw_config
-
if uri.opaque
-
query_hash.merge({
-
"adapter" => @adapter,
-
"database" => uri.opaque })
-
else
-
query_hash.merge({
-
"adapter" => @adapter,
-
"username" => uri.user,
-
"password" => uri.password,
-
"port" => uri.port,
-
"database" => database_from_path,
-
"host" => uri.host })
-
end
-
end
-
-
# Returns name of the database.
-
# Sqlite3's handling of a leading slash is in transition as of
-
# Rails 4.1.
-
1
def database_from_path
-
if @authority && @adapter == 'sqlite3'
-
# 'sqlite3:///foo' is relative, for backwards compatibility.
-
-
database_name = uri.path.sub(%r{^/}, "")
-
-
msg = "Paths in SQLite3 database URLs of the form `sqlite3:///path` will be treated as absolute in Rails 4.2. " \
-
"Please switch to `sqlite3:#{database_name}`."
-
ActiveSupport::Deprecation.warn(msg)
-
-
database_name
-
-
elsif @adapter == 'sqlite3'
-
# 'sqlite3:/foo' is absolute, because that makes sense. The
-
# corresponding relative version, 'sqlite3:foo', is handled
-
# elsewhere, as an "opaque".
-
-
uri.path
-
else
-
# Only SQLite uses a filename as the "database" name; for
-
# anything else, a leading slash would be silly.
-
-
uri.path.sub(%r{^/}, "")
-
end
-
end
-
end
-
-
##
-
# Builds a ConnectionSpecification from user input.
-
1
class Resolver # :nodoc:
-
1
attr_reader :configurations
-
-
# Accepts a hash two layers deep, keys on the first layer represent
-
# environments such as "production". Keys must be strings.
-
1
def initialize(configurations)
-
3
@configurations = configurations
-
end
-
-
# Returns a hash with database connection information.
-
#
-
# == Examples
-
#
-
# Full hash Configuration.
-
#
-
# configurations = { "production" => { "host" => "localhost", "database" => "foo", "adapter" => "sqlite3" } }
-
# Resolver.new(configurations).resolve(:production)
-
# # => { "host" => "localhost", "database" => "foo", "adapter" => "sqlite3"}
-
#
-
# Initialized with URL configuration strings.
-
#
-
# configurations = { "production" => "postgresql://localhost/foo" }
-
# Resolver.new(configurations).resolve(:production)
-
# # => { "host" => "localhost", "database" => "foo", "adapter" => "postgresql" }
-
#
-
1
def resolve(config)
-
4
if config
-
4
resolve_connection config
-
elsif env = ActiveRecord::ConnectionHandling::RAILS_ENV.call
-
resolve_symbol_connection env.to_sym
-
else
-
raise AdapterNotSpecified
-
end
-
end
-
-
# Expands each key in @configurations hash into fully resolved hash
-
1
def resolve_all
-
2
config = configurations.dup
-
2
config.each do |key, value|
-
3
config[key] = resolve(value) if value
-
end
-
2
config
-
end
-
-
# Returns an instance of ConnectionSpecification for a given adapter.
-
# Accepts a hash one layer deep that contains all connection information.
-
#
-
# == Example
-
#
-
# config = { "production" => { "host" => "localhost", "database" => "foo", "adapter" => "sqlite3" } }
-
# spec = Resolver.new(config).spec(:production)
-
# spec.adapter_method
-
# # => "sqlite3"
-
# spec.config
-
# # => { "host" => "localhost", "database" => "foo", "adapter" => "sqlite3" }
-
#
-
1
def spec(config)
-
1
spec = resolve(config).symbolize_keys
-
-
1
raise(AdapterNotSpecified, "database configuration does not specify adapter") unless spec.key?(:adapter)
-
-
1
path_to_adapter = "active_record/connection_adapters/#{spec[:adapter]}_adapter"
-
1
begin
-
1
require path_to_adapter
-
rescue Gem::LoadError => e
-
raise Gem::LoadError, "Specified '#{spec[:adapter]}' for database adapter, but the gem is not loaded. Add `gem '#{e.name}'` to your Gemfile (and ensure its version is at the minimum required by ActiveRecord)."
-
rescue LoadError => e
-
raise LoadError, "Could not load '#{path_to_adapter}'. Make sure that the adapter in config/database.yml is valid. If you use an adapter other than 'mysql', 'mysql2', 'postgresql' or 'sqlite3' add the necessary adapter gem to the Gemfile.", e.backtrace
-
end
-
-
1
adapter_method = "#{spec[:adapter]}_connection"
-
1
ConnectionSpecification.new(spec, adapter_method)
-
end
-
-
1
private
-
-
# Returns fully resolved connection, accepts hash, string or symbol.
-
# Always returns a hash.
-
#
-
# == Examples
-
#
-
# Symbol representing current environment.
-
#
-
# Resolver.new("production" => {}).resolve_connection(:production)
-
# # => {}
-
#
-
# One layer deep hash of connection values.
-
#
-
# Resolver.new({}).resolve_connection("adapter" => "sqlite3")
-
# # => { "adapter" => "sqlite3" }
-
#
-
# Connection URL.
-
#
-
# Resolver.new({}).resolve_connection("postgresql://localhost/foo")
-
# # => { "host" => "localhost", "database" => "foo", "adapter" => "postgresql" }
-
#
-
1
def resolve_connection(spec)
-
5
case spec
-
when Symbol
-
1
resolve_symbol_connection spec
-
when String
-
resolve_string_connection spec
-
when Hash
-
4
resolve_hash_connection spec
-
end
-
end
-
-
1
def resolve_string_connection(spec)
-
# Rails has historically accepted a string to mean either
-
# an environment key or a URL spec, so we have deprecated
-
# this ambiguous behaviour and in the future this function
-
# can be removed in favor of resolve_url_connection.
-
if configurations.key?(spec) || spec !~ /:/
-
ActiveSupport::Deprecation.warn "Passing a string to ActiveRecord::Base.establish_connection " \
-
"for a configuration lookup is deprecated, please pass a symbol (#{spec.to_sym.inspect}) instead"
-
resolve_symbol_connection(spec)
-
else
-
resolve_url_connection(spec)
-
end
-
end
-
-
# Takes the environment such as `:production` or `:development`.
-
# This requires that the @configurations was initialized with a key that
-
# matches.
-
#
-
# Resolver.new("production" => {}).resolve_symbol_connection(:production)
-
# # => {}
-
#
-
1
def resolve_symbol_connection(spec)
-
1
if config = configurations[spec.to_s]
-
1
resolve_connection(config)
-
else
-
raise(AdapterNotSpecified, "'#{spec}' database is not configured. Available: #{configurations.keys.inspect}")
-
end
-
end
-
-
# Accepts a hash. Expands the "url" key that contains a
-
# URL database connection to a full connection
-
# hash and merges with the rest of the hash.
-
# Connection details inside of the "url" key win any merge conflicts
-
1
def resolve_hash_connection(spec)
-
4
if spec["url"] && spec["url"] !~ /^jdbc:/
-
connection_hash = resolve_string_connection(spec.delete("url"))
-
spec.merge!(connection_hash)
-
end
-
4
spec
-
end
-
-
# Takes a connection URL.
-
#
-
# Resolver.new({}).resolve_url_connection("postgresql://localhost/foo")
-
# # => { "host" => "localhost", "database" => "foo", "adapter" => "postgresql" }
-
#
-
1
def resolve_url_connection(url)
-
ConnectionUrlResolver.new(url).to_hash
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ConnectionAdapters
-
1
class PostgreSQLColumn < Column
-
1
module ArrayParser
-
-
1
DOUBLE_QUOTE = '"'
-
1
BACKSLASH = "\\"
-
1
COMMA = ','
-
1
BRACKET_OPEN = '{'
-
1
BRACKET_CLOSE = '}'
-
-
1
private
-
# Loads pg_array_parser if available. String parsing can be
-
# performed quicker by a native extension, which will not create
-
# a large amount of Ruby objects that will need to be garbage
-
# collected. pg_array_parser has a C and Java extension
-
1
begin
-
1
require 'pg_array_parser'
-
include PgArrayParser
-
rescue LoadError
-
1
def parse_pg_array(string)
-
parse_data(string)
-
end
-
end
-
-
1
def parse_data(string)
-
local_index = 0
-
array = []
-
while(local_index < string.length)
-
case string[local_index]
-
when BRACKET_OPEN
-
local_index,array = parse_array_contents(array, string, local_index + 1)
-
when BRACKET_CLOSE
-
return array
-
end
-
local_index += 1
-
end
-
-
array
-
end
-
-
1
def parse_array_contents(array, string, index)
-
is_escaping = false
-
is_quoted = false
-
was_quoted = false
-
current_item = ''
-
-
local_index = index
-
while local_index
-
token = string[local_index]
-
if is_escaping
-
current_item << token
-
is_escaping = false
-
else
-
if is_quoted
-
case token
-
when DOUBLE_QUOTE
-
is_quoted = false
-
was_quoted = true
-
when BACKSLASH
-
is_escaping = true
-
else
-
current_item << token
-
end
-
else
-
case token
-
when BACKSLASH
-
is_escaping = true
-
when COMMA
-
add_item_to_array(array, current_item, was_quoted)
-
current_item = ''
-
was_quoted = false
-
when DOUBLE_QUOTE
-
is_quoted = true
-
when BRACKET_OPEN
-
internal_items = []
-
local_index,internal_items = parse_array_contents(internal_items, string, local_index + 1)
-
array.push(internal_items)
-
when BRACKET_CLOSE
-
add_item_to_array(array, current_item, was_quoted)
-
return local_index,array
-
else
-
current_item << token
-
end
-
end
-
end
-
-
local_index += 1
-
end
-
return local_index,array
-
end
-
-
1
def add_item_to_array(array, current_item, quoted)
-
return if !quoted && current_item.length == 0
-
-
if !quoted && current_item == 'NULL'
-
array.push nil
-
else
-
array.push current_item
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ConnectionAdapters
-
1
class PostgreSQLColumn < Column
-
1
module Cast
-
1
def point_to_string(point)
-
"(#{point[0]},#{point[1]})"
-
end
-
-
1
def string_to_point(string)
-
if string[0] == '(' && string[-1] == ')'
-
string = string[1...-1]
-
end
-
string.split(',').map{ |v| Float(v) }
-
end
-
-
1
def string_to_time(string)
-
return string unless String === string
-
-
case string
-
when 'infinity'; Float::INFINITY
-
when '-infinity'; -Float::INFINITY
-
when / BC$/
-
super("-" + string.sub(/ BC$/, ""))
-
else
-
super
-
end
-
end
-
-
1
def string_to_bit(value)
-
case value
-
when /^0x/i
-
value[2..-1].hex.to_s(2) # Hexadecimal notation
-
else
-
value # Bit-string notation
-
end
-
end
-
-
1
def hstore_to_string(object, array_member = false)
-
if Hash === object
-
string = object.map { |k, v| "#{escape_hstore(k)}=>#{escape_hstore(v)}" }.join(',')
-
string = escape_hstore(string) if array_member
-
string
-
else
-
object
-
end
-
end
-
-
1
def string_to_hstore(string)
-
if string.nil?
-
nil
-
elsif String === string
-
Hash[string.scan(HstorePair).map { |k, v|
-
v = v.upcase == 'NULL' ? nil : v.gsub(/\A"(.*)"\Z/m,'\1').gsub(/\\(.)/, '\1')
-
k = k.gsub(/\A"(.*)"\Z/m,'\1').gsub(/\\(.)/, '\1')
-
[k, v]
-
}]
-
else
-
string
-
end
-
end
-
-
1
def json_to_string(object)
-
if Hash === object || Array === object
-
ActiveSupport::JSON.encode(object)
-
else
-
object
-
end
-
end
-
-
1
def array_to_string(value, column, adapter)
-
casted_values = value.map do |val|
-
if String === val
-
if val == "NULL"
-
"\"#{val}\""
-
else
-
quote_and_escape(adapter.type_cast(val, column, true))
-
end
-
else
-
adapter.type_cast(val, column, true)
-
end
-
end
-
"{#{casted_values.join(',')}}"
-
end
-
-
1
def range_to_string(object)
-
from = object.begin.respond_to?(:infinite?) && object.begin.infinite? ? '' : object.begin
-
to = object.end.respond_to?(:infinite?) && object.end.infinite? ? '' : object.end
-
"[#{from},#{to}#{object.exclude_end? ? ')' : ']'}"
-
end
-
-
1
def string_to_json(string)
-
if String === string
-
ActiveSupport::JSON.decode(string)
-
else
-
string
-
end
-
end
-
-
1
def string_to_cidr(string)
-
if string.nil?
-
nil
-
elsif String === string
-
begin
-
IPAddr.new(string)
-
rescue ArgumentError
-
nil
-
end
-
else
-
string
-
end
-
end
-
-
1
def cidr_to_string(object)
-
if IPAddr === object
-
"#{object.to_s}/#{object.instance_variable_get(:@mask_addr).to_s(2).count('1')}"
-
else
-
object
-
end
-
end
-
-
1
def string_to_array(string, oid)
-
parse_pg_array(string).map {|val| type_cast_array(oid, val)}
-
end
-
-
1
private
-
-
1
HstorePair = begin
-
1
quoted_string = /"[^"\\]*(?:\\.[^"\\]*)*"/
-
1
unquoted_string = /(?:\\.|[^\s,])[^\s=,\\]*(?:\\.[^\s=,\\]*|=[^,>])*/
-
1
/(#{quoted_string}|#{unquoted_string})\s*=>\s*(#{quoted_string}|#{unquoted_string})/
-
end
-
-
1
def escape_hstore(value)
-
if value.nil?
-
'NULL'
-
else
-
if value == ""
-
'""'
-
else
-
'"%s"' % value.to_s.gsub(/(["\\])/, '\\\\\1')
-
end
-
end
-
end
-
-
1
ARRAY_ESCAPE = "\\" * 2 * 2 # escape the backslash twice for PG arrays
-
-
1
def quote_and_escape(value)
-
case value
-
when "NULL", Numeric
-
value
-
else
-
value = value.gsub(/\\/, ARRAY_ESCAPE)
-
value.gsub!(/"/,"\\\"")
-
"\"#{value}\""
-
end
-
end
-
-
1
def type_cast_array(oid, value)
-
if ::Array === value
-
value.map {|item| type_cast_array(oid, item)}
-
else
-
oid.type_cast value
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ConnectionAdapters
-
1
class PostgreSQLAdapter < AbstractAdapter
-
1
module DatabaseStatements
-
1
def explain(arel, binds = [])
-
sql = "EXPLAIN #{to_sql(arel, binds)}"
-
ExplainPrettyPrinter.new.pp(exec_query(sql, 'EXPLAIN', binds))
-
end
-
-
1
class ExplainPrettyPrinter # :nodoc:
-
# Pretty prints the result of a EXPLAIN in a way that resembles the output of the
-
# PostgreSQL shell:
-
#
-
# QUERY PLAN
-
# ------------------------------------------------------------------------------
-
# Nested Loop Left Join (cost=0.00..37.24 rows=8 width=0)
-
# Join Filter: (posts.user_id = users.id)
-
# -> Index Scan using users_pkey on users (cost=0.00..8.27 rows=1 width=4)
-
# Index Cond: (id = 1)
-
# -> Seq Scan on posts (cost=0.00..28.88 rows=8 width=4)
-
# Filter: (posts.user_id = 1)
-
# (6 rows)
-
#
-
1
def pp(result)
-
header = result.columns.first
-
lines = result.rows.map(&:first)
-
-
# We add 2 because there's one char of padding at both sides, note
-
# the extra hyphens in the example above.
-
width = [header, *lines].map(&:length).max + 2
-
-
pp = []
-
-
pp << header.center(width).rstrip
-
pp << '-' * width
-
-
pp += lines.map {|line| " #{line}"}
-
-
nrows = result.rows.length
-
rows_label = nrows == 1 ? 'row' : 'rows'
-
pp << "(#{nrows} #{rows_label})"
-
-
pp.join("\n") + "\n"
-
end
-
end
-
-
# Executes a SELECT query and returns an array of rows. Each row is an
-
# array of field values.
-
1
def select_rows(sql, name = nil, binds = [])
-
exec_query(sql, name, binds).rows
-
end
-
-
# Executes an INSERT query and returns the new record's ID
-
1
def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
-
unless pk
-
# Extract the table from the insert sql. Yuck.
-
table_ref = extract_table_ref_from_insert_sql(sql)
-
pk = primary_key(table_ref) if table_ref
-
end
-
-
if pk && use_insert_returning?
-
select_value("#{sql} RETURNING #{quote_column_name(pk)}")
-
elsif pk
-
super
-
last_insert_id_value(sequence_name || default_sequence_name(table_ref, pk))
-
else
-
super
-
end
-
end
-
-
1
def create
-
super.insert
-
end
-
-
# create a 2D array representing the result set
-
1
def result_as_array(res) #:nodoc:
-
# check if we have any binary column and if they need escaping
-
1
ftypes = Array.new(res.nfields) do |i|
-
1
[i, res.ftype(i)]
-
end
-
-
1
rows = res.values
-
1
return rows unless ftypes.any? { |_, x|
-
1
x == BYTEA_COLUMN_TYPE_OID || x == MONEY_COLUMN_TYPE_OID
-
}
-
-
typehash = ftypes.group_by { |_, type| type }
-
binaries = typehash[BYTEA_COLUMN_TYPE_OID] || []
-
monies = typehash[MONEY_COLUMN_TYPE_OID] || []
-
-
rows.each do |row|
-
# unescape string passed BYTEA field (OID == 17)
-
binaries.each do |index, _|
-
row[index] = unescape_bytea(row[index])
-
end
-
-
# If this is a money type column and there are any currency symbols,
-
# then strip them off. Indeed it would be prettier to do this in
-
# PostgreSQLColumn.string_to_decimal but would break form input
-
# fields that call value_before_type_cast.
-
monies.each do |index, _|
-
data = row[index]
-
# Because money output is formatted according to the locale, there are two
-
# cases to consider (note the decimal separators):
-
# (1) $12,345,678.12
-
# (2) $12.345.678,12
-
case data
-
when /^-?\D+[\d,]+\.\d{2}$/ # (1)
-
data.gsub!(/[^-\d.]/, '')
-
when /^-?\D+[\d.]+,\d{2}$/ # (2)
-
data.gsub!(/[^-\d,]/, '').sub!(/,/, '.')
-
end
-
end
-
end
-
end
-
-
# Queries the database and returns the results in an Array-like object
-
1
def query(sql, name = nil) #:nodoc:
-
1
log(sql, name) do
-
1
result_as_array @connection.async_exec(sql)
-
end
-
end
-
-
# Executes an SQL statement, returning a PGresult object on success
-
# or raising a PGError exception otherwise.
-
1
def execute(sql, name = nil)
-
7
log(sql, name) do
-
7
@connection.async_exec(sql)
-
end
-
end
-
-
1
def substitute_at(column, index)
-
Arel::Nodes::BindParam.new "$#{index + 1}"
-
end
-
-
1
def exec_query(sql, name = 'SQL', binds = [])
-
1
result = without_prepared_statement?(binds) ? exec_no_cache(sql, name, binds) :
-
exec_cache(sql, name, binds)
-
-
1
types = {}
-
1
fields = result.fields
-
1
fields.each_with_index do |fname, i|
-
1
ftype = result.ftype i
-
1
fmod = result.fmod i
-
1
types[fname] = type_map.fetch(ftype, fmod) { |oid, mod|
-
warn "unknown OID: #{fname}(#{oid}) (#{sql})"
-
OID::Identity.new
-
}
-
end
-
-
1
ret = ActiveRecord::Result.new(fields, result.values, types)
-
1
result.clear
-
1
return ret
-
end
-
-
1
def exec_delete(sql, name = 'SQL', binds = [])
-
result = without_prepared_statement?(binds) ? exec_no_cache(sql, name, binds) :
-
exec_cache(sql, name, binds)
-
affected = result.cmd_tuples
-
result.clear
-
affected
-
end
-
1
alias :exec_update :exec_delete
-
-
1
def sql_for_insert(sql, pk, id_value, sequence_name, binds)
-
unless pk
-
# Extract the table from the insert sql. Yuck.
-
table_ref = extract_table_ref_from_insert_sql(sql)
-
pk = primary_key(table_ref) if table_ref
-
end
-
-
if pk && use_insert_returning?
-
sql = "#{sql} RETURNING #{quote_column_name(pk)}"
-
end
-
-
[sql, binds]
-
end
-
-
1
def exec_insert(sql, name, binds, pk = nil, sequence_name = nil)
-
val = exec_query(sql, name, binds)
-
if !use_insert_returning? && pk
-
unless sequence_name
-
table_ref = extract_table_ref_from_insert_sql(sql)
-
sequence_name = default_sequence_name(table_ref, pk)
-
return val unless sequence_name
-
end
-
last_insert_id_result(sequence_name)
-
else
-
val
-
end
-
end
-
-
# Executes an UPDATE query and returns the number of affected tuples.
-
1
def update_sql(sql, name = nil)
-
super.cmd_tuples
-
end
-
-
# Begins a transaction.
-
1
def begin_db_transaction
-
execute "BEGIN"
-
end
-
-
1
def begin_isolated_db_transaction(isolation)
-
begin_db_transaction
-
execute "SET TRANSACTION ISOLATION LEVEL #{transaction_isolation_levels.fetch(isolation)}"
-
end
-
-
# Commits a transaction.
-
1
def commit_db_transaction
-
execute "COMMIT"
-
end
-
-
# Aborts a transaction.
-
1
def rollback_db_transaction
-
execute "ROLLBACK"
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_record/connection_adapters/abstract_adapter'
-
-
1
module ActiveRecord
-
1
module ConnectionAdapters
-
1
class PostgreSQLAdapter < AbstractAdapter
-
1
module OID
-
1
class Type
-
1
def type; end
-
end
-
-
1
class Identity < Type
-
1
def type_cast(value)
-
value
-
end
-
end
-
-
1
class Bit < Type
-
1
def type_cast(value)
-
if String === value
-
ConnectionAdapters::PostgreSQLColumn.string_to_bit value
-
else
-
value
-
end
-
end
-
end
-
-
1
class Bytea < Type
-
1
def type_cast(value)
-
return if value.nil?
-
PGconn.unescape_bytea value
-
end
-
end
-
-
1
class Money < Type
-
1
def type_cast(value)
-
return if value.nil?
-
return value unless String === value
-
-
# Because money output is formatted according to the locale, there are two
-
# cases to consider (note the decimal separators):
-
# (1) $12,345,678.12
-
# (2) $12.345.678,12
-
# Negative values are represented as follows:
-
# (3) -$2.55
-
# (4) ($2.55)
-
-
value.sub!(/^\((.+)\)$/, '-\1') # (4)
-
case value
-
when /^-?\D+[\d,]+\.\d{2}$/ # (1)
-
value.gsub!(/[^-\d.]/, '')
-
when /^-?\D+[\d.]+,\d{2}$/ # (2)
-
value.gsub!(/[^-\d,]/, '').sub!(/,/, '.')
-
end
-
-
ConnectionAdapters::Column.value_to_decimal value
-
end
-
end
-
-
1
class Vector < Type
-
1
attr_reader :delim, :subtype
-
-
# +delim+ corresponds to the `typdelim` column in the pg_types
-
# table. +subtype+ is derived from the `typelem` column in the
-
# pg_types table.
-
1
def initialize(delim, subtype)
-
6
@delim = delim
-
6
@subtype = subtype
-
end
-
-
# FIXME: this should probably split on +delim+ and use +subtype+
-
# to cast the values. Unfortunately, the current Rails behavior
-
# is to just return the string.
-
1
def type_cast(value)
-
value
-
end
-
end
-
-
1
class Point < Type
-
1
def type_cast(value)
-
if String === value
-
ConnectionAdapters::PostgreSQLColumn.string_to_point value
-
else
-
value
-
end
-
end
-
end
-
-
1
class Array < Type
-
1
attr_reader :subtype
-
1
def initialize(subtype)
-
44
@subtype = subtype
-
end
-
-
1
def type_cast(value)
-
if String === value
-
ConnectionAdapters::PostgreSQLColumn.string_to_array value, @subtype
-
else
-
value
-
end
-
end
-
end
-
-
1
class Range < Type
-
1
attr_reader :subtype
-
1
def initialize(subtype)
-
4
@subtype = subtype
-
end
-
-
1
def extract_bounds(value)
-
from, to = value[1..-2].split(',')
-
{
-
from: (value[1] == ',' || from == '-infinity') ? infinity(:negative => true) : from,
-
to: (value[-2] == ',' || to == 'infinity') ? infinity : to,
-
exclude_start: (value[0] == '('),
-
exclude_end: (value[-1] == ')')
-
}
-
end
-
-
1
def infinity(options = {})
-
::Float::INFINITY * (options[:negative] ? -1 : 1)
-
end
-
-
1
def infinity?(value)
-
value.respond_to?(:infinite?) && value.infinite?
-
end
-
-
1
def to_integer(value)
-
infinity?(value) ? value : value.to_i
-
end
-
-
1
def type_cast(value)
-
return if value.nil? || value == 'empty'
-
return value if value.is_a?(::Range)
-
-
extracted = extract_bounds(value)
-
-
case @subtype
-
when :date
-
from = ConnectionAdapters::Column.value_to_date(extracted[:from])
-
from -= 1.day if extracted[:exclude_start]
-
to = ConnectionAdapters::Column.value_to_date(extracted[:to])
-
when :decimal
-
from = BigDecimal.new(extracted[:from].to_s)
-
# FIXME: add exclude start for ::Range, same for timestamp ranges
-
to = BigDecimal.new(extracted[:to].to_s)
-
when :time
-
from = ConnectionAdapters::Column.string_to_time(extracted[:from])
-
to = ConnectionAdapters::Column.string_to_time(extracted[:to])
-
when :integer
-
from = to_integer(extracted[:from]) rescue value ? 1 : 0
-
from -= 1 if extracted[:exclude_start]
-
to = to_integer(extracted[:to]) rescue value ? 1 : 0
-
else
-
return value
-
end
-
-
::Range.new(from, to, extracted[:exclude_end])
-
end
-
end
-
-
1
class Integer < Type
-
1
def type_cast(value)
-
return if value.nil?
-
-
ConnectionAdapters::Column.value_to_integer value
-
end
-
end
-
-
1
class Boolean < Type
-
1
def type_cast(value)
-
return if value.nil?
-
-
ConnectionAdapters::Column.value_to_boolean value
-
end
-
end
-
-
1
class Timestamp < Type
-
1
def type; :timestamp; end
-
-
1
def type_cast(value)
-
return if value.nil?
-
-
# FIXME: probably we can improve this since we know it is PG
-
# specific
-
ConnectionAdapters::PostgreSQLColumn.string_to_time value
-
end
-
end
-
-
1
class Date < Type
-
1
def type; :datetime; end
-
-
1
def type_cast(value)
-
return if value.nil?
-
-
# FIXME: probably we can improve this since we know it is PG
-
# specific
-
ConnectionAdapters::Column.value_to_date value
-
end
-
end
-
-
1
class Time < Type
-
1
def type_cast(value)
-
return if value.nil?
-
-
# FIXME: probably we can improve this since we know it is PG
-
# specific
-
ConnectionAdapters::Column.string_to_dummy_time value
-
end
-
end
-
-
1
class Float < Type
-
1
def type_cast(value)
-
return if value.nil?
-
-
value.to_f
-
end
-
end
-
-
1
class Decimal < Type
-
1
def type_cast(value)
-
return if value.nil?
-
-
ConnectionAdapters::Column.value_to_decimal value
-
end
-
end
-
-
1
class Hstore < Type
-
1
def type_cast_for_write(value)
-
ConnectionAdapters::PostgreSQLColumn.hstore_to_string value
-
end
-
-
1
def type_cast(value)
-
return if value.nil?
-
-
ConnectionAdapters::PostgreSQLColumn.string_to_hstore value
-
end
-
-
1
def accessor
-
ActiveRecord::Store::StringKeyedHashAccessor
-
end
-
end
-
-
1
class Cidr < Type
-
1
def type_cast(value)
-
return if value.nil?
-
-
ConnectionAdapters::PostgreSQLColumn.string_to_cidr value
-
end
-
end
-
-
1
class Json < Type
-
1
def type_cast_for_write(value)
-
ConnectionAdapters::PostgreSQLColumn.json_to_string value
-
end
-
-
1
def type_cast(value)
-
return if value.nil?
-
-
ConnectionAdapters::PostgreSQLColumn.string_to_json value
-
end
-
-
1
def accessor
-
ActiveRecord::Store::StringKeyedHashAccessor
-
end
-
end
-
-
1
class TypeMap
-
1
def initialize
-
1
@mapping = {}
-
end
-
-
1
def []=(oid, type)
-
88
@mapping[oid] = type
-
end
-
-
1
def [](oid)
-
50
@mapping[oid]
-
end
-
-
1
def clear
-
@mapping.clear
-
end
-
-
1
def key?(oid)
-
79
@mapping.key? oid
-
end
-
-
1
def fetch(ftype, fmod)
-
# The type for the numeric depends on the width of the field,
-
# so we'll do something special here.
-
#
-
# When dealing with decimal columns:
-
#
-
# places after decimal = fmod - 4 & 0xffff
-
# places before decimal = (fmod - 4) >> 16 & 0xffff
-
1
if ftype == 1700 && (fmod - 4 & 0xffff).zero?
-
ftype = 23
-
end
-
-
1
@mapping.fetch(ftype) { |oid| yield oid, fmod }
-
end
-
end
-
-
# When the PG adapter connects, the pg_type table is queried. The
-
# key of this hash maps to the `typname` column from the table.
-
# type_map is then dynamically built with oids as the key and type
-
# objects as values.
-
1
NAMES = Hash.new { |h,k| # :nodoc:
-
h[k] = OID::Identity.new
-
}
-
-
# Register an OID type named +name+ with a typecasting object in
-
# +type+. +name+ should correspond to the `typname` column in
-
# the `pg_type` table.
-
1
def self.register_type(name, type)
-
25
NAMES[name] = type
-
end
-
-
# Alias the +old+ type to the +new+ type.
-
1
def self.alias_type(new, old)
-
15
NAMES[new] = NAMES[old]
-
end
-
-
# Is +name+ a registered type?
-
1
def self.registered_type?(name)
-
267
NAMES.key? name
-
end
-
-
1
register_type 'int2', OID::Integer.new
-
1
alias_type 'int4', 'int2'
-
1
alias_type 'int8', 'int2'
-
1
alias_type 'oid', 'int2'
-
-
1
register_type 'daterange', OID::Range.new(:date)
-
1
register_type 'numrange', OID::Range.new(:decimal)
-
1
register_type 'tsrange', OID::Range.new(:time)
-
1
register_type 'int4range', OID::Range.new(:integer)
-
1
alias_type 'tstzrange', 'tsrange'
-
1
alias_type 'int8range', 'int4range'
-
-
1
register_type 'numeric', OID::Decimal.new
-
1
register_type 'text', OID::Identity.new
-
1
alias_type 'varchar', 'text'
-
1
alias_type 'char', 'text'
-
1
alias_type 'bpchar', 'text'
-
1
alias_type 'xml', 'text'
-
-
# FIXME: why are we keeping these types as strings?
-
1
alias_type 'tsvector', 'text'
-
1
alias_type 'interval', 'text'
-
1
alias_type 'macaddr', 'text'
-
1
alias_type 'uuid', 'text'
-
-
1
register_type 'money', OID::Money.new
-
1
register_type 'bytea', OID::Bytea.new
-
1
register_type 'bool', OID::Boolean.new
-
1
register_type 'bit', OID::Bit.new
-
1
register_type 'varbit', OID::Bit.new
-
-
1
register_type 'float4', OID::Float.new
-
1
alias_type 'float8', 'float4'
-
-
1
register_type 'timestamp', OID::Timestamp.new
-
1
register_type 'timestamptz', OID::Timestamp.new
-
1
register_type 'date', OID::Date.new
-
1
register_type 'time', OID::Time.new
-
-
1
register_type 'path', OID::Identity.new
-
1
register_type 'point', OID::Point.new
-
1
register_type 'polygon', OID::Identity.new
-
1
register_type 'circle', OID::Identity.new
-
1
register_type 'hstore', OID::Hstore.new
-
1
register_type 'json', OID::Json.new
-
1
register_type 'ltree', OID::Identity.new
-
-
1
register_type 'cidr', OID::Cidr.new
-
1
alias_type 'inet', 'cidr'
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ConnectionAdapters
-
1
class PostgreSQLAdapter < AbstractAdapter
-
1
module Quoting
-
# Escapes binary strings for bytea input to the database.
-
1
def escape_bytea(value)
-
PGconn.escape_bytea(value) if value
-
end
-
-
# Unescapes bytea output from a database to the binary string it represents.
-
# NOTE: This is NOT an inverse of escape_bytea! This is only to be used
-
# on escaped binary output from database drive.
-
1
def unescape_bytea(value)
-
PGconn.unescape_bytea(value) if value
-
end
-
-
# Quotes PostgreSQL-specific data types for SQL input.
-
1
def quote(value, column = nil) #:nodoc:
-
return super unless column
-
-
sql_type = type_to_sql(column.type, column.limit, column.precision, column.scale)
-
-
case value
-
when Range
-
if /range$/ =~ sql_type
-
"'#{PostgreSQLColumn.range_to_string(value)}'::#{sql_type}"
-
else
-
super
-
end
-
when Array
-
case sql_type
-
when 'point' then super(PostgreSQLColumn.point_to_string(value))
-
when 'json' then super(PostgreSQLColumn.json_to_string(value))
-
else
-
if column.array
-
"'#{PostgreSQLColumn.array_to_string(value, column, self).gsub(/'/, "''")}'"
-
else
-
super
-
end
-
end
-
when Hash
-
case sql_type
-
when 'hstore' then super(PostgreSQLColumn.hstore_to_string(value), column)
-
when 'json' then super(PostgreSQLColumn.json_to_string(value), column)
-
else super
-
end
-
when IPAddr
-
case sql_type
-
when 'inet', 'cidr' then super(PostgreSQLColumn.cidr_to_string(value), column)
-
else super
-
end
-
when Float
-
if value.infinite? && column.type == :datetime
-
"'#{value.to_s.downcase}'"
-
elsif value.infinite? || value.nan?
-
"'#{value.to_s}'"
-
else
-
super
-
end
-
when Numeric
-
if sql_type == 'money' || [:string, :text].include?(column.type)
-
# Not truly string input, so doesn't require (or allow) escape string syntax.
-
"'#{value}'"
-
else
-
super
-
end
-
when String
-
case sql_type
-
when 'bytea' then "'#{escape_bytea(value)}'"
-
when 'xml' then "xml '#{quote_string(value)}'"
-
when /^bit/
-
case value
-
when /^[01]*$/ then "B'#{value}'" # Bit-string notation
-
when /^[0-9A-F]*$/i then "X'#{value}'" # Hexadecimal notation
-
end
-
else
-
super
-
end
-
else
-
super
-
end
-
end
-
-
1
def type_cast(value, column, array_member = false)
-
return super(value, column) unless column
-
-
case value
-
when Range
-
if /range$/ =~ column.sql_type
-
PostgreSQLColumn.range_to_string(value)
-
else
-
super(value, column)
-
end
-
when NilClass
-
if column.array && array_member
-
'NULL'
-
elsif column.array
-
value
-
else
-
super(value, column)
-
end
-
when Array
-
case column.sql_type
-
when 'point' then PostgreSQLColumn.point_to_string(value)
-
when 'json' then PostgreSQLColumn.json_to_string(value)
-
else
-
if column.array
-
PostgreSQLColumn.array_to_string(value, column, self)
-
else
-
super(value, column)
-
end
-
end
-
when String
-
if 'bytea' == column.sql_type
-
# Return a bind param hash with format as binary.
-
# See http://deveiate.org/code/pg/PGconn.html#method-i-exec_prepared-doc
-
# for more information
-
{ value: value, format: 1 }
-
else
-
super(value, column)
-
end
-
when Hash
-
case column.sql_type
-
when 'hstore' then PostgreSQLColumn.hstore_to_string(value, array_member)
-
when 'json' then PostgreSQLColumn.json_to_string(value)
-
else super(value, column)
-
end
-
when IPAddr
-
if %w(inet cidr).include? column.sql_type
-
PostgreSQLColumn.cidr_to_string(value)
-
else
-
super(value, column)
-
end
-
else
-
super(value, column)
-
end
-
end
-
-
# Quotes strings for use in SQL input.
-
1
def quote_string(s) #:nodoc:
-
@connection.escape(s)
-
end
-
-
# Checks the following cases:
-
#
-
# - table_name
-
# - "table.name"
-
# - schema_name.table_name
-
# - schema_name."table.name"
-
# - "schema.name".table_name
-
# - "schema.name"."table.name"
-
1
def quote_table_name(name)
-
schema, name_part = extract_pg_identifier_from_name(name.to_s)
-
-
unless name_part
-
quote_column_name(schema)
-
else
-
table_name, name_part = extract_pg_identifier_from_name(name_part)
-
"#{quote_column_name(schema)}.#{quote_column_name(table_name)}"
-
end
-
end
-
-
1
def quote_table_name_for_assignment(table, attr)
-
quote_column_name(attr)
-
end
-
-
# Quotes column names for use in SQL queries.
-
1
def quote_column_name(name) #:nodoc:
-
PGconn.quote_ident(name.to_s)
-
end
-
-
# Quote date/time values for use in SQL input. Includes microseconds
-
# if the value is a Time responding to usec.
-
1
def quoted_date(value) #:nodoc:
-
result = super
-
if value.acts_like?(:time) && value.respond_to?(:usec)
-
result = "#{result}.#{sprintf("%06d", value.usec)}"
-
end
-
-
if value.year < 0
-
result = result.sub(/^-/, "") + " BC"
-
end
-
result
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ConnectionAdapters
-
1
class PostgreSQLAdapter < AbstractAdapter
-
1
module ReferentialIntegrity
-
1
def supports_disable_referential_integrity? #:nodoc:
-
true
-
end
-
-
1
def disable_referential_integrity #:nodoc:
-
if supports_disable_referential_integrity?
-
begin
-
execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} DISABLE TRIGGER ALL" }.join(";"))
-
rescue
-
execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} DISABLE TRIGGER USER" }.join(";"))
-
end
-
end
-
yield
-
ensure
-
if supports_disable_referential_integrity?
-
begin
-
execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} ENABLE TRIGGER ALL" }.join(";"))
-
rescue
-
execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} ENABLE TRIGGER USER" }.join(";"))
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ConnectionAdapters
-
1
class PostgreSQLAdapter < AbstractAdapter
-
1
class SchemaCreation < AbstractAdapter::SchemaCreation
-
1
private
-
-
1
def visit_AddColumn(o)
-
sql_type = type_to_sql(o.type.to_sym, o.limit, o.precision, o.scale)
-
sql = "ADD COLUMN #{quote_column_name(o.name)} #{sql_type}"
-
add_column_options!(sql, column_options(o))
-
end
-
-
1
def visit_ColumnDefinition(o)
-
sql = super
-
if o.primary_key? && o.type == :uuid
-
sql << " PRIMARY KEY "
-
add_column_options!(sql, column_options(o))
-
end
-
sql
-
end
-
-
1
def add_column_options!(sql, options)
-
if options[:array] || options[:column].try(:array)
-
sql << '[]'
-
end
-
-
column = options.fetch(:column) { return super }
-
if column.type == :uuid && options[:default] =~ /\(\)/
-
sql << " DEFAULT #{options[:default]}"
-
else
-
super
-
end
-
end
-
end
-
-
1
def schema_creation
-
SchemaCreation.new self
-
end
-
-
1
module SchemaStatements
-
# Drops the database specified on the +name+ attribute
-
# and creates it again using the provided +options+.
-
1
def recreate_database(name, options = {}) #:nodoc:
-
drop_database(name)
-
create_database(name, options)
-
end
-
-
# Create a new PostgreSQL database. Options include <tt>:owner</tt>, <tt>:template</tt>,
-
# <tt>:encoding</tt> (defaults to utf8), <tt>:collation</tt>, <tt>:ctype</tt>,
-
# <tt>:tablespace</tt>, and <tt>:connection_limit</tt> (note that MySQL uses
-
# <tt>:charset</tt> while PostgreSQL uses <tt>:encoding</tt>).
-
#
-
# Example:
-
# create_database config[:database], config
-
# create_database 'foo_development', encoding: 'unicode'
-
1
def create_database(name, options = {})
-
options = { encoding: 'utf8' }.merge!(options.symbolize_keys)
-
-
option_string = options.sum do |key, value|
-
case key
-
when :owner
-
" OWNER = \"#{value}\""
-
when :template
-
" TEMPLATE = \"#{value}\""
-
when :encoding
-
" ENCODING = '#{value}'"
-
when :collation
-
" LC_COLLATE = '#{value}'"
-
when :ctype
-
" LC_CTYPE = '#{value}'"
-
when :tablespace
-
" TABLESPACE = \"#{value}\""
-
when :connection_limit
-
" CONNECTION LIMIT = #{value}"
-
else
-
""
-
end
-
end
-
-
execute "CREATE DATABASE #{quote_table_name(name)}#{option_string}"
-
end
-
-
# Drops a PostgreSQL database.
-
#
-
# Example:
-
# drop_database 'matt_development'
-
1
def drop_database(name) #:nodoc:
-
execute "DROP DATABASE IF EXISTS #{quote_table_name(name)}"
-
end
-
-
# Returns the list of all tables in the schema search path or a specified schema.
-
1
def tables(name = nil)
-
query(<<-SQL, 'SCHEMA').map { |row| row[0] }
-
SELECT tablename
-
FROM pg_tables
-
WHERE schemaname = ANY (current_schemas(false))
-
SQL
-
end
-
-
# Returns true if table exists.
-
# If the schema is not specified as part of +name+ then it will only find tables within
-
# the current schema search path (regardless of permissions to access tables in other schemas)
-
1
def table_exists?(name)
-
1
schema, table = Utils.extract_schema_and_table(name.to_s)
-
1
return false unless table
-
-
1
binds = [[nil, table]]
-
1
binds << [nil, schema] if schema
-
-
exec_query(<<-SQL, 'SCHEMA').rows.first[0].to_i > 0
-
SELECT COUNT(*)
-
FROM pg_class c
-
LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
-
WHERE c.relkind in ('v','r')
-
AND c.relname = '#{table.gsub(/(^"|"$)/,'')}'
-
AND n.nspname = #{schema ? "'#{schema}'" : 'ANY (current_schemas(false))'}
-
1
SQL
-
end
-
-
# Returns true if schema exists.
-
1
def schema_exists?(name)
-
exec_query(<<-SQL, 'SCHEMA').rows.first[0].to_i > 0
-
SELECT COUNT(*)
-
FROM pg_namespace
-
WHERE nspname = '#{name}'
-
SQL
-
end
-
-
1
def index_name_exists?(table_name, index_name, default)
-
exec_query(<<-SQL, 'SCHEMA').rows.first[0].to_i > 0
-
SELECT COUNT(*)
-
FROM pg_class t
-
INNER JOIN pg_index d ON t.oid = d.indrelid
-
INNER JOIN pg_class i ON d.indexrelid = i.oid
-
WHERE i.relkind = 'i'
-
AND i.relname = '#{index_name}'
-
AND t.relname = '#{table_name}'
-
AND i.relnamespace IN (SELECT oid FROM pg_namespace WHERE nspname = ANY (current_schemas(false)) )
-
SQL
-
end
-
-
# Returns an array of indexes for the given table.
-
1
def indexes(table_name, name = nil)
-
result = query(<<-SQL, 'SCHEMA')
-
SELECT distinct i.relname, d.indisunique, d.indkey, pg_get_indexdef(d.indexrelid), t.oid
-
FROM pg_class t
-
INNER JOIN pg_index d ON t.oid = d.indrelid
-
INNER JOIN pg_class i ON d.indexrelid = i.oid
-
WHERE i.relkind = 'i'
-
AND d.indisprimary = 'f'
-
AND t.relname = '#{table_name}'
-
AND i.relnamespace IN (SELECT oid FROM pg_namespace WHERE nspname = ANY (current_schemas(false)) )
-
ORDER BY i.relname
-
SQL
-
-
result.map do |row|
-
index_name = row[0]
-
unique = row[1] == 't'
-
indkey = row[2].split(" ")
-
inddef = row[3]
-
oid = row[4]
-
-
columns = Hash[query(<<-SQL, "SCHEMA")]
-
SELECT a.attnum, a.attname
-
FROM pg_attribute a
-
WHERE a.attrelid = #{oid}
-
AND a.attnum IN (#{indkey.join(",")})
-
SQL
-
-
column_names = columns.values_at(*indkey).compact
-
-
unless column_names.empty?
-
# add info on sort order for columns (only desc order is explicitly specified, asc is the default)
-
desc_order_columns = inddef.scan(/(\w+) DESC/).flatten
-
orders = desc_order_columns.any? ? Hash[desc_order_columns.map {|order_column| [order_column, :desc]}] : {}
-
where = inddef.scan(/WHERE (.+)$/).flatten[0]
-
using = inddef.scan(/USING (.+?) /).flatten[0].to_sym
-
-
IndexDefinition.new(table_name, index_name, unique, column_names, [], orders, where, nil, using)
-
end
-
end.compact
-
end
-
-
# Returns the list of all column definitions for a table.
-
1
def columns(table_name)
-
# Limit, precision, and scale are all handled by the superclass.
-
column_definitions(table_name).map do |column_name, type, default, notnull, oid, fmod|
-
oid = type_map.fetch(oid.to_i, fmod.to_i) {
-
OID::Identity.new
-
}
-
PostgreSQLColumn.new(column_name, default, oid, type, notnull == 'f')
-
end
-
end
-
-
# Returns the current database name.
-
1
def current_database
-
query('select current_database()', 'SCHEMA')[0][0]
-
end
-
-
# Returns the current schema name.
-
1
def current_schema
-
query('SELECT current_schema', 'SCHEMA')[0][0]
-
end
-
-
# Returns the current database encoding format.
-
1
def encoding
-
query(<<-end_sql, 'SCHEMA')[0][0]
-
SELECT pg_encoding_to_char(pg_database.encoding) FROM pg_database
-
WHERE pg_database.datname LIKE '#{current_database}'
-
end_sql
-
end
-
-
# Returns the current database collation.
-
1
def collation
-
query(<<-end_sql, 'SCHEMA')[0][0]
-
SELECT pg_database.datcollate FROM pg_database WHERE pg_database.datname LIKE '#{current_database}'
-
end_sql
-
end
-
-
# Returns the current database ctype.
-
1
def ctype
-
query(<<-end_sql, 'SCHEMA')[0][0]
-
SELECT pg_database.datctype FROM pg_database WHERE pg_database.datname LIKE '#{current_database}'
-
end_sql
-
end
-
-
# Returns an array of schema names.
-
1
def schema_names
-
query(<<-SQL, 'SCHEMA').flatten
-
SELECT nspname
-
FROM pg_namespace
-
WHERE nspname !~ '^pg_.*'
-
AND nspname NOT IN ('information_schema')
-
ORDER by nspname;
-
SQL
-
end
-
-
# Creates a schema for the given schema name.
-
1
def create_schema schema_name
-
execute "CREATE SCHEMA #{schema_name}"
-
end
-
-
# Drops the schema for the given schema name.
-
1
def drop_schema schema_name
-
execute "DROP SCHEMA #{schema_name} CASCADE"
-
end
-
-
# Sets the schema search path to a string of comma-separated schema names.
-
# Names beginning with $ have to be quoted (e.g. $user => '$user').
-
# See: http://www.postgresql.org/docs/current/static/ddl-schemas.html
-
#
-
# This should be not be called manually but set in database.yml.
-
1
def schema_search_path=(schema_csv)
-
1
if schema_csv
-
execute("SET search_path TO #{schema_csv}", 'SCHEMA')
-
@schema_search_path = schema_csv
-
end
-
end
-
-
# Returns the active schema search path.
-
1
def schema_search_path
-
@schema_search_path ||= query('SHOW search_path', 'SCHEMA')[0][0]
-
end
-
-
# Returns the current client message level.
-
1
def client_min_messages
-
1
query('SHOW client_min_messages', 'SCHEMA')[0][0]
-
end
-
-
# Set the client message level.
-
1
def client_min_messages=(level)
-
3
execute("SET client_min_messages TO '#{level}'", 'SCHEMA')
-
end
-
-
# Returns the sequence name for a table's primary key or some other specified key.
-
1
def default_sequence_name(table_name, pk = nil) #:nodoc:
-
result = serial_sequence(table_name, pk || 'id')
-
return nil unless result
-
result.split('.').last
-
rescue ActiveRecord::StatementInvalid
-
"#{table_name}_#{pk || 'id'}_seq"
-
end
-
-
1
def serial_sequence(table, column)
-
result = exec_query(<<-eosql, 'SCHEMA')
-
SELECT pg_get_serial_sequence('#{table}', '#{column}')
-
eosql
-
result.rows.first.first
-
end
-
-
# Resets the sequence of a table's primary key to the maximum value.
-
1
def reset_pk_sequence!(table, pk = nil, sequence = nil) #:nodoc:
-
unless pk and sequence
-
default_pk, default_sequence = pk_and_sequence_for(table)
-
-
pk ||= default_pk
-
sequence ||= default_sequence
-
end
-
-
if @logger && pk && !sequence
-
@logger.warn "#{table} has primary key #{pk} with no default sequence"
-
end
-
-
if pk && sequence
-
quoted_sequence = quote_table_name(sequence)
-
-
select_value <<-end_sql, 'SCHEMA'
-
SELECT setval('#{quoted_sequence}', (SELECT COALESCE(MAX(#{quote_column_name pk})+(SELECT increment_by FROM #{quoted_sequence}), (SELECT min_value FROM #{quoted_sequence})) FROM #{quote_table_name(table)}), false)
-
end_sql
-
end
-
end
-
-
# Returns a table's primary key and belonging sequence.
-
1
def pk_and_sequence_for(table) #:nodoc:
-
# First try looking for a sequence with a dependency on the
-
# given table's primary key.
-
result = query(<<-end_sql, 'SCHEMA')[0]
-
SELECT attr.attname, seq.relname
-
FROM pg_class seq,
-
pg_attribute attr,
-
pg_depend dep,
-
pg_constraint cons
-
WHERE seq.oid = dep.objid
-
AND seq.relkind = 'S'
-
AND attr.attrelid = dep.refobjid
-
AND attr.attnum = dep.refobjsubid
-
AND attr.attrelid = cons.conrelid
-
AND attr.attnum = cons.conkey[1]
-
AND cons.contype = 'p'
-
AND dep.refobjid = '#{quote_table_name(table)}'::regclass
-
end_sql
-
-
if result.nil? or result.empty?
-
result = query(<<-end_sql, 'SCHEMA')[0]
-
SELECT attr.attname,
-
CASE
-
WHEN pg_get_expr(def.adbin, def.adrelid) !~* 'nextval' THEN NULL
-
WHEN split_part(pg_get_expr(def.adbin, def.adrelid), '''', 2) ~ '.' THEN
-
substr(split_part(pg_get_expr(def.adbin, def.adrelid), '''', 2),
-
strpos(split_part(pg_get_expr(def.adbin, def.adrelid), '''', 2), '.')+1)
-
ELSE split_part(pg_get_expr(def.adbin, def.adrelid), '''', 2)
-
END
-
FROM pg_class t
-
JOIN pg_attribute attr ON (t.oid = attrelid)
-
JOIN pg_attrdef def ON (adrelid = attrelid AND adnum = attnum)
-
JOIN pg_constraint cons ON (conrelid = adrelid AND adnum = conkey[1])
-
WHERE t.oid = '#{quote_table_name(table)}'::regclass
-
AND cons.contype = 'p'
-
AND pg_get_expr(def.adbin, def.adrelid) ~* 'nextval|uuid_generate'
-
end_sql
-
end
-
-
[result.first, result.last]
-
rescue
-
nil
-
end
-
-
# Returns just a table's primary key
-
1
def primary_key(table)
-
row = exec_query(<<-end_sql, 'SCHEMA').rows.first
-
SELECT attr.attname
-
FROM pg_attribute attr
-
INNER JOIN pg_constraint cons ON attr.attrelid = cons.conrelid AND attr.attnum = cons.conkey[1]
-
WHERE cons.contype = 'p'
-
AND cons.conrelid = '#{quote_table_name(table)}'::regclass
-
end_sql
-
-
row && row.first
-
end
-
-
# Renames a table.
-
# Also renames a table's primary key sequence if the sequence name matches the
-
# Active Record default.
-
#
-
# Example:
-
# rename_table('octopuses', 'octopi')
-
1
def rename_table(table_name, new_name)
-
clear_cache!
-
execute "ALTER TABLE #{quote_table_name(table_name)} RENAME TO #{quote_table_name(new_name)}"
-
pk, seq = pk_and_sequence_for(new_name)
-
if seq == "#{table_name}_#{pk}_seq"
-
new_seq = "#{new_name}_#{pk}_seq"
-
execute "ALTER TABLE #{quote_table_name(seq)} RENAME TO #{quote_table_name(new_seq)}"
-
end
-
-
rename_table_indexes(table_name, new_name)
-
end
-
-
# Adds a new column to the named table.
-
# See TableDefinition#column for details of the options you can use.
-
1
def add_column(table_name, column_name, type, options = {})
-
clear_cache!
-
super
-
end
-
-
# Changes the column of a table.
-
1
def change_column(table_name, column_name, type, options = {})
-
clear_cache!
-
quoted_table_name = quote_table_name(table_name)
-
sql_type = type_to_sql(type, options[:limit], options[:precision], options[:scale])
-
sql_type << "[]" if options[:array]
-
execute "ALTER TABLE #{quoted_table_name} ALTER COLUMN #{quote_column_name(column_name)} TYPE #{sql_type}"
-
-
change_column_default(table_name, column_name, options[:default]) if options_include_default?(options)
-
change_column_null(table_name, column_name, options[:null], options[:default]) if options.key?(:null)
-
end
-
-
# Changes the default value of a table column.
-
1
def change_column_default(table_name, column_name, default)
-
clear_cache!
-
execute "ALTER TABLE #{quote_table_name(table_name)} ALTER COLUMN #{quote_column_name(column_name)} SET DEFAULT #{quote(default)}"
-
end
-
-
1
def change_column_null(table_name, column_name, null, default = nil)
-
clear_cache!
-
unless null || default.nil?
-
execute("UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)}=#{quote(default)} WHERE #{quote_column_name(column_name)} IS NULL")
-
end
-
execute("ALTER TABLE #{quote_table_name(table_name)} ALTER #{quote_column_name(column_name)} #{null ? 'DROP' : 'SET'} NOT NULL")
-
end
-
-
# Renames a column in a table.
-
1
def rename_column(table_name, column_name, new_column_name)
-
clear_cache!
-
execute "ALTER TABLE #{quote_table_name(table_name)} RENAME COLUMN #{quote_column_name(column_name)} TO #{quote_column_name(new_column_name)}"
-
rename_column_indexes(table_name, column_name, new_column_name)
-
end
-
-
1
def add_index(table_name, column_name, options = {}) #:nodoc:
-
index_name, index_type, index_columns, index_options, index_algorithm, index_using = add_index_options(table_name, column_name, options)
-
execute "CREATE #{index_type} INDEX #{index_algorithm} #{quote_column_name(index_name)} ON #{quote_table_name(table_name)} #{index_using} (#{index_columns})#{index_options}"
-
end
-
-
1
def remove_index!(table_name, index_name) #:nodoc:
-
execute "DROP INDEX #{quote_table_name(index_name)}"
-
end
-
-
1
def rename_index(table_name, old_name, new_name)
-
execute "ALTER INDEX #{quote_column_name(old_name)} RENAME TO #{quote_table_name(new_name)}"
-
end
-
-
1
def index_name_length
-
63
-
end
-
-
# Maps logical Rails types to PostgreSQL-specific data types.
-
1
def type_to_sql(type, limit = nil, precision = nil, scale = nil)
-
case type.to_s
-
when 'binary'
-
# PostgreSQL doesn't support limits on binary (bytea) columns.
-
# The hard limit is 1Gb, because of a 32-bit size field, and TOAST.
-
case limit
-
when nil, 0..0x3fffffff; super(type)
-
else raise(ActiveRecordError, "No binary type has byte size #{limit}.")
-
end
-
when 'text'
-
# PostgreSQL doesn't support limits on text columns.
-
# The hard limit is 1Gb, according to section 8.3 in the manual.
-
case limit
-
when nil, 0..0x3fffffff; super(type)
-
else raise(ActiveRecordError, "The limit on text can be at most 1GB - 1byte.")
-
end
-
when 'integer'
-
return 'integer' unless limit
-
-
case limit
-
when 1, 2; 'smallint'
-
when 3, 4; 'integer'
-
when 5..8; 'bigint'
-
else raise(ActiveRecordError, "No integer type has byte size #{limit}. Use a numeric with precision 0 instead.")
-
end
-
when 'datetime'
-
return super unless precision
-
-
case precision
-
when 0..6; "timestamp(#{precision})"
-
else raise(ActiveRecordError, "No timestamp type has precision of #{precision}. The allowed range of precision is from 0 to 6")
-
end
-
else
-
super
-
end
-
end
-
-
# PostgreSQL requires the ORDER BY columns in the select list for distinct queries, and
-
# requires that the ORDER BY include the distinct column.
-
1
def columns_for_distinct(columns, orders) #:nodoc:
-
order_columns = orders.reject(&:blank?).map{ |s|
-
# Convert Arel node to string
-
s = s.to_sql unless s.is_a?(String)
-
# Remove any ASC/DESC modifiers
-
s.gsub(/\s+(ASC|DESC)\s*(NULLS\s+(FIRST|LAST)\s*)?/i, '')
-
}.reject(&:blank?).map.with_index { |column, i| "#{column} AS alias_#{i}" }
-
-
[super, *order_columns].join(', ')
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_record/connection_adapters/abstract_adapter'
-
1
require 'active_record/connection_adapters/statement_pool'
-
1
require 'active_record/connection_adapters/postgresql/oid'
-
1
require 'active_record/connection_adapters/postgresql/cast'
-
1
require 'active_record/connection_adapters/postgresql/array_parser'
-
1
require 'active_record/connection_adapters/postgresql/quoting'
-
1
require 'active_record/connection_adapters/postgresql/schema_statements'
-
1
require 'active_record/connection_adapters/postgresql/database_statements'
-
1
require 'active_record/connection_adapters/postgresql/referential_integrity'
-
1
require 'arel/visitors/bind_visitor'
-
-
# Make sure we're using pg high enough for PGResult#values
-
1
gem 'pg', '~> 0.11'
-
1
require 'pg'
-
-
1
require 'ipaddr'
-
-
1
module ActiveRecord
-
1
module ConnectionHandling # :nodoc:
-
1
VALID_CONN_PARAMS = [:host, :hostaddr, :port, :dbname, :user, :password, :connect_timeout,
-
:client_encoding, :options, :application_name, :fallback_application_name,
-
:keepalives, :keepalives_idle, :keepalives_interval, :keepalives_count,
-
:tty, :sslmode, :requiressl, :sslcompression, :sslcert, :sslkey,
-
:sslrootcert, :sslcrl, :requirepeer, :krbsrvname, :gsslib, :service]
-
-
# Establishes a connection to the database that's used by all Active Record objects
-
1
def postgresql_connection(config)
-
1
conn_params = config.symbolize_keys
-
-
6
conn_params.delete_if { |_, v| v.nil? }
-
-
# Map ActiveRecords param names to PGs.
-
1
conn_params[:user] = conn_params.delete(:username) if conn_params[:username]
-
1
conn_params[:dbname] = conn_params.delete(:database) if conn_params[:database]
-
-
# Forward only valid config params to PGconn.connect.
-
6
conn_params.keep_if { |k, _| VALID_CONN_PARAMS.include?(k) }
-
-
# The postgres drivers don't allow the creation of an unconnected PGconn object,
-
# so just pass a nil connection object for the time being.
-
1
ConnectionAdapters::PostgreSQLAdapter.new(nil, logger, conn_params, config)
-
end
-
end
-
-
1
module ConnectionAdapters
-
# PostgreSQL-specific extensions to column definitions in a table.
-
1
class PostgreSQLColumn < Column #:nodoc:
-
1
attr_accessor :array
-
-
1
def initialize(name, default, oid_type, sql_type = nil, null = true)
-
@oid_type = oid_type
-
default_value = self.class.extract_value_from_default(default)
-
-
if sql_type =~ /\[\]$/
-
@array = true
-
super(name, default_value, sql_type[0..sql_type.length - 3], null)
-
else
-
@array = false
-
super(name, default_value, sql_type, null)
-
end
-
-
@default_function = default if has_default_function?(default_value, default)
-
end
-
-
1
def number?
-
!array && super
-
end
-
-
1
def text?
-
!array && super
-
end
-
-
# :stopdoc:
-
1
class << self
-
1
include ConnectionAdapters::PostgreSQLColumn::Cast
-
1
include ConnectionAdapters::PostgreSQLColumn::ArrayParser
-
1
attr_accessor :money_precision
-
end
-
# :startdoc:
-
-
# Extracts the value from a PostgreSQL column default definition.
-
1
def self.extract_value_from_default(default)
-
# This is a performance optimization for Ruby 1.9.2 in development.
-
# If the value is nil, we return nil straight away without checking
-
# the regular expressions. If we check each regular expression,
-
# Regexp#=== will call NilClass#to_str, which will trigger
-
# method_missing (defined by whiny nil in ActiveSupport) which
-
# makes this method very very slow.
-
return default unless default
-
-
case default
-
when /\A'(.*)'::(num|date|tstz|ts|int4|int8)range\z/m
-
$1
-
# Numeric types
-
when /\A\(?(-?\d+(\.\d*)?\)?(::bigint)?)\z/
-
$1
-
# Character types
-
when /\A\(?'(.*)'::.*\b(?:character varying|bpchar|text)\z/m
-
$1.gsub(/''/, "'")
-
# Binary data types
-
when /\A'(.*)'::bytea\z/m
-
$1
-
# Date/time types
-
when /\A'(.+)'::(?:time(?:stamp)? with(?:out)? time zone|date)\z/
-
$1
-
when /\A'(.*)'::interval\z/
-
$1
-
# Boolean type
-
when 'true'
-
true
-
when 'false'
-
false
-
# Geometric types
-
when /\A'(.*)'::(?:point|line|lseg|box|"?path"?|polygon|circle)\z/
-
$1
-
# Network address types
-
when /\A'(.*)'::(?:cidr|inet|macaddr)\z/
-
$1
-
# Bit string types
-
when /\AB'(.*)'::"?bit(?: varying)?"?\z/
-
$1
-
# XML type
-
when /\A'(.*)'::xml\z/m
-
$1
-
# Arrays
-
when /\A'(.*)'::"?\D+"?\[\]\z/
-
$1
-
# Hstore
-
when /\A'(.*)'::hstore\z/
-
$1
-
# JSON
-
when /\A'(.*)'::json\z/
-
$1
-
# Object identifier types
-
when /\A-?\d+\z/
-
$1
-
else
-
# Anything else is blank, some user type, or some function
-
# and we can't know the value of that, so return nil.
-
nil
-
end
-
end
-
-
1
def type_cast_for_write(value)
-
if @oid_type.respond_to?(:type_cast_for_write)
-
@oid_type.type_cast_for_write(value)
-
else
-
super
-
end
-
end
-
-
1
def type_cast(value)
-
return if value.nil?
-
return super if encoded?
-
-
@oid_type.type_cast value
-
end
-
-
1
def accessor
-
@oid_type.accessor
-
end
-
-
1
private
-
-
1
def has_default_function?(default_value, default)
-
!default_value && (%r{\w+\(.*\)} === default)
-
end
-
-
1
def extract_limit(sql_type)
-
case sql_type
-
when /^bigint/i; 8
-
when /^smallint/i; 2
-
when /^timestamp/i; nil
-
else super
-
end
-
end
-
-
# Extracts the scale from PostgreSQL-specific data types.
-
1
def extract_scale(sql_type)
-
# Money type has a fixed scale of 2.
-
sql_type =~ /^money/ ? 2 : super
-
end
-
-
# Extracts the precision from PostgreSQL-specific data types.
-
1
def extract_precision(sql_type)
-
if sql_type == 'money'
-
self.class.money_precision
-
elsif sql_type =~ /timestamp/i
-
$1.to_i if sql_type =~ /\((\d+)\)/
-
else
-
super
-
end
-
end
-
-
# Maps PostgreSQL-specific data types to logical Rails types.
-
1
def simplified_type(field_type)
-
case field_type
-
# Numeric and monetary types
-
when /^(?:real|double precision)$/
-
:float
-
# Monetary types
-
when 'money'
-
:decimal
-
when 'hstore'
-
:hstore
-
when 'ltree'
-
:ltree
-
# Network address types
-
when 'inet'
-
:inet
-
when 'cidr'
-
:cidr
-
when 'macaddr'
-
:macaddr
-
# Character types
-
when /^(?:character varying|bpchar)(?:\(\d+\))?$/
-
:string
-
# Binary data types
-
when 'bytea'
-
:binary
-
# Date/time types
-
when /^timestamp with(?:out)? time zone$/
-
:datetime
-
when /^interval(?:|\(\d+\))$/
-
:string
-
# Geometric types
-
when /^(?:point|line|lseg|box|"?path"?|polygon|circle)$/
-
:string
-
# Bit strings
-
when /^bit(?: varying)?(?:\(\d+\))?$/
-
:string
-
# XML type
-
when 'xml'
-
:xml
-
# tsvector type
-
when 'tsvector'
-
:tsvector
-
# Arrays
-
when /^\D+\[\]$/
-
:string
-
# Object identifier types
-
when 'oid'
-
:integer
-
# UUID type
-
when 'uuid'
-
:uuid
-
# JSON type
-
when 'json'
-
:json
-
# Small and big integer types
-
when /^(?:small|big)int$/
-
:integer
-
when /(num|date|tstz|ts|int4|int8)range$/
-
field_type.to_sym
-
# Pass through all types that are not specific to PostgreSQL.
-
else
-
super
-
end
-
end
-
end
-
-
# The PostgreSQL adapter works with the native C (https://bitbucket.org/ged/ruby-pg) driver.
-
#
-
# Options:
-
#
-
# * <tt>:host</tt> - Defaults to a Unix-domain socket in /tmp. On machines without Unix-domain sockets,
-
# the default is to connect to localhost.
-
# * <tt>:port</tt> - Defaults to 5432.
-
# * <tt>:username</tt> - Defaults to be the same as the operating system name of the user running the application.
-
# * <tt>:password</tt> - Password to be used if the server demands password authentication.
-
# * <tt>:database</tt> - Defaults to be the same as the user name.
-
# * <tt>:schema_search_path</tt> - An optional schema search path for the connection given
-
# as a string of comma-separated schema names. This is backward-compatible with the <tt>:schema_order</tt> option.
-
# * <tt>:encoding</tt> - An optional client encoding that is used in a <tt>SET client_encoding TO
-
# <encoding></tt> call on the connection.
-
# * <tt>:min_messages</tt> - An optional client min messages that is used in a
-
# <tt>SET client_min_messages TO <min_messages></tt> call on the connection.
-
# * <tt>:variables</tt> - An optional hash of additional parameters that
-
# will be used in <tt>SET SESSION key = val</tt> calls on the connection.
-
# * <tt>:insert_returning</tt> - An optional boolean to control the use or <tt>RETURNING</tt> for <tt>INSERT</tt> statements
-
# defaults to true.
-
#
-
# Any further options are used as connection parameters to libpq. See
-
# http://www.postgresql.org/docs/9.1/static/libpq-connect.html for the
-
# list of parameters.
-
#
-
# In addition, default connection parameters of libpq can be set per environment variables.
-
# See http://www.postgresql.org/docs/9.1/static/libpq-envars.html .
-
1
class PostgreSQLAdapter < AbstractAdapter
-
1
class ColumnDefinition < ActiveRecord::ConnectionAdapters::ColumnDefinition
-
1
attr_accessor :array
-
end
-
-
1
module ColumnMethods
-
1
def xml(*args)
-
options = args.extract_options!
-
column(args[0], 'xml', options)
-
end
-
-
1
def tsvector(*args)
-
options = args.extract_options!
-
column(args[0], 'tsvector', options)
-
end
-
-
1
def int4range(name, options = {})
-
column(name, 'int4range', options)
-
end
-
-
1
def int8range(name, options = {})
-
column(name, 'int8range', options)
-
end
-
-
1
def tsrange(name, options = {})
-
column(name, 'tsrange', options)
-
end
-
-
1
def tstzrange(name, options = {})
-
column(name, 'tstzrange', options)
-
end
-
-
1
def numrange(name, options = {})
-
column(name, 'numrange', options)
-
end
-
-
1
def daterange(name, options = {})
-
column(name, 'daterange', options)
-
end
-
-
1
def hstore(name, options = {})
-
column(name, 'hstore', options)
-
end
-
-
1
def ltree(name, options = {})
-
column(name, 'ltree', options)
-
end
-
-
1
def inet(name, options = {})
-
column(name, 'inet', options)
-
end
-
-
1
def cidr(name, options = {})
-
column(name, 'cidr', options)
-
end
-
-
1
def macaddr(name, options = {})
-
column(name, 'macaddr', options)
-
end
-
-
1
def uuid(name, options = {})
-
column(name, 'uuid', options)
-
end
-
-
1
def json(name, options = {})
-
column(name, 'json', options)
-
end
-
end
-
-
1
class TableDefinition < ActiveRecord::ConnectionAdapters::TableDefinition
-
1
include ColumnMethods
-
-
# Defines the primary key field.
-
# Use of the native PostgreSQL UUID type is supported, and can be used
-
# by defining your tables as such:
-
#
-
# create_table :stuffs, id: :uuid do |t|
-
# t.string :content
-
# t.timestamps
-
# end
-
#
-
# By default, this will use the +uuid_generate_v4()+ function from the
-
# +uuid-ossp+ extension, which MUST be enabled on your database. To enable
-
# the +uuid-ossp+ extension, you can use the +enable_extension+ method in your
-
# migrations. To use a UUID primary key without +uuid-ossp+ enabled, you can
-
# set the +:default+ option to +nil+:
-
#
-
# create_table :stuffs, id: false do |t|
-
# t.primary_key :id, :uuid, default: nil
-
# t.uuid :foo_id
-
# t.timestamps
-
# end
-
#
-
# You may also pass a different UUID generation function from +uuid-ossp+
-
# or another library.
-
#
-
# Note that setting the UUID primary key default value to +nil+ will
-
# require you to assure that you always provide a UUID value before saving
-
# a record (as primary keys cannot be +nil+). This might be done via the
-
# +SecureRandom.uuid+ method and a +before_save+ callback, for instance.
-
1
def primary_key(name, type = :primary_key, options = {})
-
return super unless type == :uuid
-
options[:default] = options.fetch(:default, 'uuid_generate_v4()')
-
options[:primary_key] = true
-
column name, type, options
-
end
-
-
1
def column(name, type = nil, options = {})
-
super
-
column = self[name]
-
column.array = options[:array]
-
-
self
-
end
-
-
1
private
-
-
1
def create_column_definition(name, type)
-
ColumnDefinition.new name, type
-
end
-
end
-
-
1
class Table < ActiveRecord::ConnectionAdapters::Table
-
1
include ColumnMethods
-
end
-
-
1
ADAPTER_NAME = 'PostgreSQL'
-
-
1
NATIVE_DATABASE_TYPES = {
-
primary_key: "serial primary key",
-
string: { name: "character varying", limit: 255 },
-
text: { name: "text" },
-
integer: { name: "integer" },
-
float: { name: "float" },
-
decimal: { name: "decimal" },
-
datetime: { name: "timestamp" },
-
timestamp: { name: "timestamp" },
-
time: { name: "time" },
-
date: { name: "date" },
-
daterange: { name: "daterange" },
-
numrange: { name: "numrange" },
-
tsrange: { name: "tsrange" },
-
tstzrange: { name: "tstzrange" },
-
int4range: { name: "int4range" },
-
int8range: { name: "int8range" },
-
binary: { name: "bytea" },
-
boolean: { name: "boolean" },
-
xml: { name: "xml" },
-
tsvector: { name: "tsvector" },
-
hstore: { name: "hstore" },
-
inet: { name: "inet" },
-
cidr: { name: "cidr" },
-
macaddr: { name: "macaddr" },
-
uuid: { name: "uuid" },
-
json: { name: "json" },
-
ltree: { name: "ltree" }
-
}
-
-
1
include Quoting
-
1
include ReferentialIntegrity
-
1
include SchemaStatements
-
1
include DatabaseStatements
-
1
include Savepoints
-
-
# Returns 'PostgreSQL' as adapter name for identification purposes.
-
1
def adapter_name
-
ADAPTER_NAME
-
end
-
-
# Adds `:array` option to the default set provided by the
-
# AbstractAdapter
-
1
def prepare_column_options(column, types)
-
spec = super
-
spec[:array] = 'true' if column.respond_to?(:array) && column.array
-
spec[:default] = "\"#{column.default_function}\"" if column.default_function
-
spec
-
end
-
-
# Adds `:array` as a valid migration key
-
1
def migration_keys
-
super + [:array]
-
end
-
-
# Returns +true+, since this connection adapter supports prepared statement
-
# caching.
-
1
def supports_statement_cache?
-
true
-
end
-
-
1
def supports_index_sort_order?
-
true
-
end
-
-
1
def supports_partial_index?
-
true
-
end
-
-
1
def supports_transaction_isolation?
-
true
-
end
-
-
1
def index_algorithms
-
{ concurrently: 'CONCURRENTLY' }
-
end
-
-
1
class StatementPool < ConnectionAdapters::StatementPool
-
1
def initialize(connection, max)
-
1
super
-
1
@counter = 0
-
1
@cache = Hash.new { |h,pid| h[pid] = {} }
-
end
-
-
1
def each(&block); cache.each(&block); end
-
1
def key?(key); cache.key?(key); end
-
1
def [](key); cache[key]; end
-
1
def length; cache.length; end
-
-
1
def next_key
-
"a#{@counter + 1}"
-
end
-
-
1
def []=(sql, key)
-
while @max <= cache.size
-
dealloc(cache.shift.last)
-
end
-
@counter += 1
-
cache[sql] = key
-
end
-
-
1
def clear
-
cache.each_value do |stmt_key|
-
dealloc stmt_key
-
end
-
cache.clear
-
end
-
-
1
def delete(sql_key)
-
dealloc cache[sql_key]
-
cache.delete sql_key
-
end
-
-
1
private
-
-
1
def cache
-
@cache[Process.pid]
-
end
-
-
1
def dealloc(key)
-
@connection.query "DEALLOCATE #{key}" if connection_active?
-
end
-
-
1
def connection_active?
-
@connection.status == PGconn::CONNECTION_OK
-
rescue PGError
-
false
-
end
-
end
-
-
1
class BindSubstitution < Arel::Visitors::PostgreSQL # :nodoc:
-
1
include Arel::Visitors::BindVisitor
-
end
-
-
# Initializes and connects a PostgreSQL adapter.
-
1
def initialize(connection, logger, connection_parameters, config)
-
1
super(connection, logger)
-
-
2
if self.class.type_cast_config_to_boolean(config.fetch(:prepared_statements) { true })
-
1
@prepared_statements = true
-
1
@visitor = Arel::Visitors::PostgreSQL.new self
-
else
-
@visitor = unprepared_visitor
-
end
-
-
1
@connection_parameters, @config = connection_parameters, config
-
-
# @local_tz is initialized as nil to avoid warnings when connect tries to use it
-
1
@local_tz = nil
-
1
@table_alias_length = nil
-
-
1
connect
-
1
@statements = StatementPool.new @connection,
-
1
self.class.type_cast_config_to_integer(config.fetch(:statement_limit) { 1000 })
-
-
1
if postgresql_version < 80200
-
raise "Your version of PostgreSQL (#{postgresql_version}) is too old, please upgrade!"
-
end
-
-
1
@type_map = OID::TypeMap.new
-
1
initialize_type_map(type_map)
-
1
@local_tz = execute('SHOW TIME ZONE', 'SCHEMA').first["TimeZone"]
-
1
@use_insert_returning = @config.key?(:insert_returning) ? self.class.type_cast_config_to_boolean(@config[:insert_returning]) : true
-
end
-
-
# Clears the prepared statements cache.
-
1
def clear_cache!
-
@statements.clear
-
end
-
-
# Is this connection alive and ready for queries?
-
1
def active?
-
1
@connection.query 'SELECT 1'
-
1
true
-
rescue PGError
-
false
-
end
-
-
1
def active_threadsafe?
-
@connection.connect_poll != PG::PGRES_POLLING_FAILED
-
end
-
-
# Close then reopen the connection.
-
1
def reconnect!
-
super
-
@connection.reset
-
configure_connection
-
end
-
-
1
def reset!
-
clear_cache!
-
super
-
end
-
-
# Disconnects from the database if already connected. Otherwise, this
-
# method does nothing.
-
1
def disconnect!
-
super
-
@connection.close rescue nil
-
end
-
-
1
def native_database_types #:nodoc:
-
NATIVE_DATABASE_TYPES
-
end
-
-
# Returns true, since this connection adapter supports migrations.
-
1
def supports_migrations?
-
true
-
end
-
-
# Does PostgreSQL support finding primary key on non-Active Record tables?
-
1
def supports_primary_key? #:nodoc:
-
true
-
end
-
-
# Enable standard-conforming strings if available.
-
1
def set_standard_conforming_strings
-
1
old, self.client_min_messages = client_min_messages, 'panic'
-
1
execute('SET standard_conforming_strings = on', 'SCHEMA') rescue nil
-
ensure
-
1
self.client_min_messages = old
-
end
-
-
1
def supports_insert_with_returning?
-
true
-
end
-
-
1
def supports_ddl_transactions?
-
true
-
end
-
-
1
def supports_explain?
-
true
-
end
-
-
# Returns true if pg > 9.1
-
1
def supports_extensions?
-
postgresql_version >= 90100
-
end
-
-
# Range datatypes weren't introduced until PostgreSQL 9.2
-
1
def supports_ranges?
-
postgresql_version >= 90200
-
end
-
-
1
def enable_extension(name)
-
exec_query("CREATE EXTENSION IF NOT EXISTS \"#{name}\"").tap {
-
reload_type_map
-
}
-
end
-
-
1
def disable_extension(name)
-
exec_query("DROP EXTENSION IF EXISTS \"#{name}\" CASCADE").tap {
-
reload_type_map
-
}
-
end
-
-
1
def extension_enabled?(name)
-
if supports_extensions?
-
res = exec_query "SELECT EXISTS(SELECT * FROM pg_available_extensions WHERE name = '#{name}' AND installed_version IS NOT NULL) as enabled",
-
'SCHEMA'
-
res.column_types['enabled'].type_cast res.rows.first.first
-
end
-
end
-
-
1
def extensions
-
if supports_extensions?
-
res = exec_query "SELECT extname from pg_extension", "SCHEMA"
-
res.rows.map { |r| res.column_types['extname'].type_cast r.first }
-
else
-
super
-
end
-
end
-
-
# Returns the configured supported identifier length supported by PostgreSQL
-
1
def table_alias_length
-
@table_alias_length ||= query('SHOW max_identifier_length', 'SCHEMA')[0][0].to_i
-
end
-
-
# Set the authorized user for this session
-
1
def session_auth=(user)
-
clear_cache!
-
exec_query "SET SESSION AUTHORIZATION #{user}"
-
end
-
-
1
module Utils
-
1
extend self
-
-
# Returns an array of <tt>[schema_name, table_name]</tt> extracted from +name+.
-
# +schema_name+ is nil if not specified in +name+.
-
# +schema_name+ and +table_name+ exclude surrounding quotes (regardless of whether provided in +name+)
-
# +name+ supports the range of schema/table references understood by PostgreSQL, for example:
-
#
-
# * <tt>table_name</tt>
-
# * <tt>"table.name"</tt>
-
# * <tt>schema_name.table_name</tt>
-
# * <tt>schema_name."table.name"</tt>
-
# * <tt>"schema.name"."table name"</tt>
-
1
def extract_schema_and_table(name)
-
2
table, schema = name.scan(/[^".\s]+|"[^"]*"/)[0..1].collect{|m| m.gsub(/(^"|"$)/,'') }.reverse
-
1
[schema, table]
-
end
-
end
-
-
1
def use_insert_returning?
-
@use_insert_returning
-
end
-
-
1
def valid_type?(type)
-
!native_database_types[type].nil?
-
end
-
-
1
def update_table_definition(table_name, base) #:nodoc:
-
Table.new(table_name, base)
-
end
-
-
1
protected
-
-
# Returns the version of the connected PostgreSQL server.
-
1
def postgresql_version
-
2
@connection.server_version
-
end
-
-
# See http://www.postgresql.org/docs/9.1/static/errcodes-appendix.html
-
1
FOREIGN_KEY_VIOLATION = "23503"
-
1
UNIQUE_VIOLATION = "23505"
-
-
1
def translate_exception(exception, message)
-
return exception unless exception.respond_to?(:result)
-
-
case exception.result.try(:error_field, PGresult::PG_DIAG_SQLSTATE)
-
when UNIQUE_VIOLATION
-
RecordNotUnique.new(message, exception)
-
when FOREIGN_KEY_VIOLATION
-
InvalidForeignKey.new(message, exception)
-
else
-
super
-
end
-
end
-
-
1
private
-
-
1
def type_map
-
2
@type_map
-
end
-
-
1
def reload_type_map
-
type_map.clear
-
initialize_type_map(type_map)
-
end
-
-
1
def add_oid(row, records_by_oid, type_map)
-
7
return type_map if type_map.key? row['type_elem'].to_i
-
-
7
if OID.registered_type? row['typname']
-
# this composite type is explicitly registered
-
1
vector = OID::NAMES[row['typname']]
-
else
-
# use the default for composite types
-
6
unless type_map.key? row['typelem'].to_i
-
add_oid records_by_oid[row['typelem']], records_by_oid, type_map
-
end
-
-
6
vector = OID::Vector.new row['typdelim'], type_map[row['typelem'].to_i]
-
end
-
-
7
type_map[row['oid'].to_i] = vector
-
7
type_map
-
end
-
-
1
def initialize_type_map(type_map)
-
1
result = execute('SELECT oid, typname, typelem, typdelim, typinput FROM pg_type', 'SCHEMA')
-
334
leaves, nodes = result.partition { |row| row['typelem'] == '0' }
-
-
# populate the leaf nodes
-
261
leaves.find_all { |row| OID.registered_type? row['typname'] }.each do |row|
-
37
type_map[row['oid'].to_i] = OID::NAMES[row['typname']]
-
end
-
-
334
records_by_oid = result.group_by { |row| row['oid'] }
-
-
74
arrays, nodes = nodes.partition { |row| row['typinput'] == 'array_in' }
-
-
# populate composite types
-
1
nodes.each do |row|
-
7
add_oid row, records_by_oid, type_map
-
end
-
-
# populate array types
-
67
arrays.find_all { |row| type_map.key? row['typelem'].to_i }.each do |row|
-
44
array = OID::Array.new type_map[row['typelem'].to_i]
-
44
type_map[row['oid'].to_i] = array
-
end
-
end
-
-
1
FEATURE_NOT_SUPPORTED = "0A000" #:nodoc:
-
-
1
def exec_no_cache(sql, name, binds)
-
2
log(sql, name, binds) { @connection.async_exec(sql) }
-
end
-
-
1
def exec_cache(sql, name, binds)
-
stmt_key = prepare_statement(sql)
-
type_casted_binds = binds.map { |col, val|
-
[col, type_cast(val, col)]
-
}
-
-
log(sql, name, type_casted_binds, stmt_key) do
-
@connection.send_query_prepared(stmt_key, type_casted_binds.map { |_, val| val })
-
@connection.block
-
@connection.get_last_result
-
end
-
rescue ActiveRecord::StatementInvalid => e
-
pgerror = e.original_exception
-
-
# Get the PG code for the failure. Annoyingly, the code for
-
# prepared statements whose return value may have changed is
-
# FEATURE_NOT_SUPPORTED. Check here for more details:
-
# http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/cache/plancache.c#l573
-
begin
-
code = pgerror.result.result_error_field(PGresult::PG_DIAG_SQLSTATE)
-
rescue
-
raise e
-
end
-
if FEATURE_NOT_SUPPORTED == code
-
@statements.delete sql_key(sql)
-
retry
-
else
-
raise e
-
end
-
end
-
-
# Returns the statement identifier for the client side cache
-
# of statements
-
1
def sql_key(sql)
-
"#{schema_search_path}-#{sql}"
-
end
-
-
# Prepare the statement if it hasn't been prepared, return
-
# the statement key.
-
1
def prepare_statement(sql)
-
sql_key = sql_key(sql)
-
unless @statements.key? sql_key
-
nextkey = @statements.next_key
-
begin
-
@connection.prepare nextkey, sql
-
rescue => e
-
raise translate_exception_class(e, sql)
-
end
-
# Clear the queue
-
@connection.get_last_result
-
@statements[sql_key] = nextkey
-
end
-
@statements[sql_key]
-
end
-
-
# The internal PostgreSQL identifier of the money data type.
-
1
MONEY_COLUMN_TYPE_OID = 790 #:nodoc:
-
# The internal PostgreSQL identifier of the BYTEA data type.
-
1
BYTEA_COLUMN_TYPE_OID = 17 #:nodoc:
-
-
# Connects to a PostgreSQL server and sets up the adapter depending on the
-
# connected server's characteristics.
-
1
def connect
-
1
@connection = PGconn.connect(@connection_parameters)
-
-
# Money type has a fixed precision of 10 in PostgreSQL 8.2 and below, and as of
-
# PostgreSQL 8.3 it has a fixed precision of 19. PostgreSQLColumn.extract_precision
-
# should know about this but can't detect it there, so deal with it here.
-
1
PostgreSQLColumn.money_precision = (postgresql_version >= 80300) ? 19 : 10
-
-
1
configure_connection
-
rescue ::PG::Error => error
-
if error.message.include?("does not exist")
-
raise ActiveRecord::NoDatabaseError.new(error.message)
-
else
-
raise error
-
end
-
end
-
-
# Configures the encoding, verbosity, schema search path, and time zone of the connection.
-
# This is called by #connect and should not be called manually.
-
1
def configure_connection
-
1
if @config[:encoding]
-
1
@connection.set_client_encoding(@config[:encoding])
-
end
-
1
self.client_min_messages = @config[:min_messages] || 'warning'
-
1
self.schema_search_path = @config[:schema_search_path] || @config[:schema_order]
-
-
# Use standard-conforming strings if available so we don't have to do the E'...' dance.
-
1
set_standard_conforming_strings
-
-
# If using Active Record's time zone support configure the connection to return
-
# TIMESTAMP WITH ZONE types in UTC.
-
# (SET TIME ZONE does not use an equals sign like other SET variables)
-
1
if ActiveRecord::Base.default_timezone == :utc
-
1
execute("SET time zone 'UTC'", 'SCHEMA')
-
elsif @local_tz
-
execute("SET time zone '#{@local_tz}'", 'SCHEMA')
-
end
-
-
# SET statements from :variables config hash
-
# http://www.postgresql.org/docs/8.3/static/sql-set.html
-
1
variables = @config[:variables] || {}
-
1
variables.map do |k, v|
-
if v == ':default' || v == :default
-
# Sets the value to the global or compile default
-
execute("SET SESSION #{k.to_s} TO DEFAULT", 'SCHEMA')
-
elsif !v.nil?
-
execute("SET SESSION #{k.to_s} TO #{quote(v)}", 'SCHEMA')
-
end
-
end
-
end
-
-
# Returns the current ID of a table's sequence.
-
1
def last_insert_id(sequence_name) #:nodoc:
-
Integer(last_insert_id_value(sequence_name))
-
end
-
-
1
def last_insert_id_value(sequence_name)
-
last_insert_id_result(sequence_name).rows.first.first
-
end
-
-
1
def last_insert_id_result(sequence_name) #:nodoc:
-
exec_query("SELECT currval('#{sequence_name}')", 'SQL')
-
end
-
-
# Executes a SELECT query and returns the results, performing any data type
-
# conversions that are required to be performed here instead of in PostgreSQLColumn.
-
1
def select(sql, name = nil, binds = [])
-
exec_query(sql, name, binds)
-
end
-
-
# Returns the list of a table's column names, data types, and default values.
-
#
-
# The underlying query is roughly:
-
# SELECT column.name, column.type, default.value
-
# FROM column LEFT JOIN default
-
# ON column.table_id = default.table_id
-
# AND column.num = default.column_num
-
# WHERE column.table_id = get_table_id('table_name')
-
# AND column.num > 0
-
# AND NOT column.is_dropped
-
# ORDER BY column.num
-
#
-
# If the table name is not prefixed with a schema, the database will
-
# take the first match from the schema search path.
-
#
-
# Query implementation notes:
-
# - format_type includes the column size constraint, e.g. varchar(50)
-
# - ::regclass is a function that gives the id for a table name
-
1
def column_definitions(table_name) #:nodoc:
-
exec_query(<<-end_sql, 'SCHEMA').rows
-
SELECT a.attname, format_type(a.atttypid, a.atttypmod),
-
pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod
-
FROM pg_attribute a LEFT JOIN pg_attrdef d
-
ON a.attrelid = d.adrelid AND a.attnum = d.adnum
-
WHERE a.attrelid = '#{quote_table_name(table_name)}'::regclass
-
AND a.attnum > 0 AND NOT a.attisdropped
-
ORDER BY a.attnum
-
end_sql
-
end
-
-
1
def extract_pg_identifier_from_name(name)
-
match_data = name.start_with?('"') ? name.match(/\"([^\"]+)\"/) : name.match(/([^\.]+)/)
-
-
if match_data
-
rest = name[match_data[0].length, name.length]
-
rest = rest[1, rest.length] if rest.start_with? "."
-
[match_data[1], (rest.length > 0 ? rest : nil)]
-
end
-
end
-
-
1
def extract_table_ref_from_insert_sql(sql)
-
sql[/into\s+([^\(]*).*values\s*\(/im]
-
$1.strip if $1
-
end
-
-
1
def create_table_definition(name, temporary, options, as = nil)
-
TableDefinition.new native_database_types, name, temporary, options, as
-
end
-
end
-
end
-
end
-
-
1
module ActiveRecord
-
1
module ConnectionAdapters
-
1
class SchemaCache
-
1
attr_reader :version
-
1
attr_accessor :connection
-
-
1
def initialize(conn)
-
1
@connection = conn
-
-
1
@columns = {}
-
1
@columns_hash = {}
-
1
@primary_keys = {}
-
1
@tables = {}
-
1
prepare_default_proc
-
end
-
-
1
def primary_keys(table_name)
-
@primary_keys[table_name]
-
end
-
-
# A cached lookup for table existence.
-
1
def table_exists?(name)
-
return @tables[name] if @tables.key? name
-
-
@tables[name] = connection.table_exists?(name)
-
end
-
-
# Add internal cache for table with +table_name+.
-
1
def add(table_name)
-
if table_exists?(table_name)
-
@primary_keys[table_name]
-
@columns[table_name]
-
@columns_hash[table_name]
-
end
-
end
-
-
1
def tables(name)
-
@tables[name]
-
end
-
-
# Get the columns for a table
-
1
def columns(table)
-
@columns[table]
-
end
-
-
# Get the columns for a table as a hash, key is the column name
-
# value is the column object.
-
1
def columns_hash(table)
-
@columns_hash[table]
-
end
-
-
# Clears out internal caches
-
1
def clear!
-
@columns.clear
-
@columns_hash.clear
-
@primary_keys.clear
-
@tables.clear
-
@version = nil
-
end
-
-
1
def size
-
[@columns, @columns_hash, @primary_keys, @tables].map { |x|
-
x.size
-
}.inject :+
-
end
-
-
# Clear out internal caches for table with +table_name+.
-
1
def clear_table_cache!(table_name)
-
@columns.delete table_name
-
@columns_hash.delete table_name
-
@primary_keys.delete table_name
-
@tables.delete table_name
-
end
-
-
1
def marshal_dump
-
# if we get current version during initialization, it happens stack over flow.
-
@version = ActiveRecord::Migrator.current_version
-
[@version] + [@columns, @columns_hash, @primary_keys, @tables].map { |val|
-
Hash[val]
-
}
-
end
-
-
1
def marshal_load(array)
-
@version, @columns, @columns_hash, @primary_keys, @tables = array
-
prepare_default_proc
-
end
-
-
1
private
-
-
1
def prepare_default_proc
-
1
@columns.default_proc = Proc.new do |h, table_name|
-
h[table_name] = connection.columns(table_name)
-
end
-
-
1
@columns_hash.default_proc = Proc.new do |h, table_name|
-
h[table_name] = Hash[columns(table_name).map { |col|
-
[col.name, col]
-
}]
-
end
-
-
1
@primary_keys.default_proc = Proc.new do |h, table_name|
-
h[table_name] = table_exists?(table_name) ? connection.primary_key(table_name) : nil
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ConnectionAdapters
-
1
class StatementPool
-
1
include Enumerable
-
-
1
def initialize(connection, max = 1000)
-
1
@connection = connection
-
1
@max = max
-
end
-
-
1
def each
-
raise NotImplementedError
-
end
-
-
1
def key?(key)
-
raise NotImplementedError
-
end
-
-
1
def [](key)
-
raise NotImplementedError
-
end
-
-
1
def length
-
raise NotImplementedError
-
end
-
-
1
def []=(sql, key)
-
raise NotImplementedError
-
end
-
-
1
def clear
-
raise NotImplementedError
-
end
-
-
1
def delete(key)
-
raise NotImplementedError
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ConnectionHandling
-
4
RAILS_ENV = -> { Rails.env if defined?(Rails) }
-
4
DEFAULT_ENV = -> { RAILS_ENV.call || "default_env" }
-
-
# Establishes the connection to the database. Accepts a hash as input where
-
# the <tt>:adapter</tt> key must be specified with the name of a database adapter (in lower-case)
-
# example for regular databases (MySQL, Postgresql, etc):
-
#
-
# ActiveRecord::Base.establish_connection(
-
# adapter: "mysql",
-
# host: "localhost",
-
# username: "myuser",
-
# password: "mypass",
-
# database: "somedatabase"
-
# )
-
#
-
# Example for SQLite database:
-
#
-
# ActiveRecord::Base.establish_connection(
-
# adapter: "sqlite",
-
# database: "path/to/dbfile"
-
# )
-
#
-
# Also accepts keys as strings (for parsing from YAML for example):
-
#
-
# ActiveRecord::Base.establish_connection(
-
# "adapter" => "sqlite",
-
# "database" => "path/to/dbfile"
-
# )
-
#
-
# Or a URL:
-
#
-
# ActiveRecord::Base.establish_connection(
-
# "postgres://myuser:mypass@localhost/somedatabase"
-
# )
-
#
-
# In case <tt>ActiveRecord::Base.configurations</tt> is set (Rails
-
# automatically loads the contents of config/database.yml into it),
-
# a symbol can also be given as argument, representing a key in the
-
# configuration hash:
-
#
-
# ActiveRecord::Base.establish_connection(:production)
-
#
-
# The exceptions AdapterNotSpecified, AdapterNotFound and ArgumentError
-
# may be returned on an error.
-
1
def establish_connection(spec = nil)
-
1
spec ||= DEFAULT_ENV.call.to_sym
-
1
resolver = ConnectionAdapters::ConnectionSpecification::Resolver.new configurations
-
1
spec = resolver.spec(spec)
-
-
1
unless respond_to?(spec.adapter_method)
-
raise AdapterNotFound, "database configuration specifies nonexistent #{spec.config[:adapter]} adapter"
-
end
-
-
1
remove_connection
-
1
connection_handler.establish_connection self, spec
-
end
-
-
1
class MergeAndResolveDefaultUrlConfig # :nodoc:
-
1
def initialize(raw_configurations)
-
2
@raw_config = raw_configurations.dup
-
2
@env = DEFAULT_ENV.call.to_s
-
end
-
-
# Returns fully resolved connection hashes.
-
# Merges connection information from `ENV['DATABASE_URL']` if available.
-
1
def resolve
-
2
ConnectionAdapters::ConnectionSpecification::Resolver.new(config).resolve_all
-
end
-
-
1
private
-
1
def config
-
2
@raw_config.dup.tap do |cfg|
-
2
if url = ENV['DATABASE_URL']
-
cfg[@env] ||= {}
-
cfg[@env]["url"] ||= url
-
end
-
end
-
end
-
end
-
-
# Returns the connection currently associated with the class. This can
-
# also be used to "borrow" the connection to do database work unrelated
-
# to any of the specific Active Records.
-
1
def connection
-
1
retrieve_connection
-
end
-
-
1
def connection_id
-
2
ActiveRecord::RuntimeRegistry.connection_id
-
end
-
-
1
def connection_id=(connection_id)
-
1
ActiveRecord::RuntimeRegistry.connection_id = connection_id
-
end
-
-
# Returns the configuration of the associated connection as a hash:
-
#
-
# ActiveRecord::Base.connection_config
-
# # => {pool: 5, timeout: 5000, database: "db/development.sqlite3", adapter: "sqlite3"}
-
#
-
# Please use only for reading.
-
1
def connection_config
-
connection_pool.spec.config
-
end
-
-
1
def connection_pool
-
connection_handler.retrieve_connection_pool(self) or raise ConnectionNotEstablished
-
end
-
-
1
def retrieve_connection
-
1
connection_handler.retrieve_connection(self)
-
end
-
-
# Returns +true+ if Active Record is connected.
-
1
def connected?
-
1
connection_handler.connected?(self)
-
end
-
-
1
def remove_connection(klass = self)
-
1
connection_handler.remove_connection(klass)
-
end
-
-
1
def clear_cache! # :nodoc:
-
connection.schema_cache.clear!
-
end
-
-
1
delegate :clear_active_connections!, :clear_reloadable_connections!,
-
:clear_all_connections!, :to => :connection_handler
-
end
-
end
-
1
require 'active_support/core_ext/hash/indifferent_access'
-
1
require 'active_support/core_ext/object/duplicable'
-
1
require 'thread'
-
-
1
module ActiveRecord
-
1
module Core
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
##
-
# :singleton-method:
-
#
-
# Accepts a logger conforming to the interface of Log4r which is then
-
# passed on to any new database connections made and which can be
-
# retrieved on both a class and instance level by calling +logger+.
-
1
mattr_accessor :logger, instance_writer: false
-
-
##
-
# :singleton-method:
-
# Contains the database configuration - as is typically stored in config/database.yml -
-
# as a Hash.
-
#
-
# For example, the following database.yml...
-
#
-
# development:
-
# adapter: sqlite3
-
# database: db/development.sqlite3
-
#
-
# production:
-
# adapter: sqlite3
-
# database: db/production.sqlite3
-
#
-
# ...would result in ActiveRecord::Base.configurations to look like this:
-
#
-
# {
-
# 'development' => {
-
# 'adapter' => 'sqlite3',
-
# 'database' => 'db/development.sqlite3'
-
# },
-
# 'production' => {
-
# 'adapter' => 'sqlite3',
-
# 'database' => 'db/production.sqlite3'
-
# }
-
# }
-
1
def self.configurations=(config)
-
2
@@configurations = ActiveRecord::ConnectionHandling::MergeAndResolveDefaultUrlConfig.new(config).resolve
-
end
-
1
self.configurations = {}
-
-
# Returns fully resolved configurations hash
-
1
def self.configurations
-
1
@@configurations
-
end
-
-
##
-
# :singleton-method:
-
# Determines whether to use Time.utc (using :utc) or Time.local (using :local) when pulling
-
# dates and times from the database. This is set to :utc by default.
-
1
mattr_accessor :default_timezone, instance_writer: false
-
1
self.default_timezone = :utc
-
-
##
-
# :singleton-method:
-
# Specifies the format to use when dumping the database schema with Rails'
-
# Rakefile. If :sql, the schema is dumped as (potentially database-
-
# specific) SQL statements. If :ruby, the schema is dumped as an
-
# ActiveRecord::Schema file which can be loaded into any database that
-
# supports migrations. Use :ruby if you want to have different database
-
# adapters for, e.g., your development and test environments.
-
1
mattr_accessor :schema_format, instance_writer: false
-
1
self.schema_format = :ruby
-
-
##
-
# :singleton-method:
-
# Specify whether or not to use timestamps for migration versions
-
1
mattr_accessor :timestamped_migrations, instance_writer: false
-
1
self.timestamped_migrations = true
-
-
##
-
# :singleton-method:
-
# Specify whether schema dump should happen at the end of the
-
# db:migrate rake task. This is true by default, which is useful for the
-
# development environment. This should ideally be false in the production
-
# environment where dumping schema is rarely needed.
-
1
mattr_accessor :dump_schema_after_migration, instance_writer: false
-
1
self.dump_schema_after_migration = true
-
-
# :nodoc:
-
1
mattr_accessor :maintain_test_schema, instance_accessor: false
-
-
1
def self.disable_implicit_join_references=(value)
-
ActiveSupport::Deprecation.warn("Implicit join references were removed with Rails 4.1." \
-
"Make sure to remove this configuration because it does nothing.")
-
end
-
-
1
class_attribute :default_connection_handler, instance_writer: false
-
-
1
def self.connection_handler
-
4
ActiveRecord::RuntimeRegistry.connection_handler || default_connection_handler
-
end
-
-
1
def self.connection_handler=(handler)
-
ActiveRecord::RuntimeRegistry.connection_handler = handler
-
end
-
-
1
self.default_connection_handler = ConnectionAdapters::ConnectionHandler.new
-
end
-
-
1
module ClassMethods
-
1
def initialize_generated_modules
-
super
-
-
generated_association_methods
-
end
-
-
1
def generated_association_methods
-
@generated_association_methods ||= begin
-
1
mod = const_set(:GeneratedAssociationMethods, Module.new)
-
1
include mod
-
1
mod
-
13
end
-
end
-
-
# Returns a string like 'Post(id:integer, title:string, body:text)'
-
1
def inspect
-
if self == Base
-
super
-
elsif abstract_class?
-
"#{super}(abstract)"
-
elsif !connected?
-
"#{super} (call '#{super}.connection' to establish a connection)"
-
elsif table_exists?
-
attr_list = columns.map { |c| "#{c.name}: #{c.type}" } * ', '
-
"#{super}(#{attr_list})"
-
else
-
"#{super}(Table doesn't exist)"
-
end
-
end
-
-
# Overwrite the default class equality method to provide support for association proxies.
-
1
def ===(object)
-
object.is_a?(self)
-
end
-
-
# Returns an instance of <tt>Arel::Table</tt> loaded with the current table name.
-
#
-
# class Post < ActiveRecord::Base
-
# scope :published_and_commented, -> { published.and(self.arel_table[:comments_count].gt(0)) }
-
# end
-
1
def arel_table # :nodoc:
-
@arel_table ||= Arel::Table.new(table_name, arel_engine)
-
end
-
-
# Returns the Arel engine.
-
1
def arel_engine # :nodoc:
-
@arel_engine ||=
-
if Base == self || connection_handler.retrieve_connection_pool(self)
-
self
-
else
-
superclass.arel_engine
-
end
-
end
-
-
1
private
-
-
1
def relation #:nodoc:
-
relation = Relation.create(self, arel_table)
-
-
if finder_needs_type_condition?
-
relation.where(type_condition).create_with(inheritance_column.to_sym => sti_name)
-
else
-
relation
-
end
-
end
-
end
-
-
# New objects can be instantiated as either empty (pass no construction parameter) or pre-set with
-
# attributes but not yet saved (pass a hash with key names matching the associated table column names).
-
# In both instances, valid attribute keys are determined by the column names of the associated table --
-
# hence you can't have attributes that aren't part of the table columns.
-
#
-
# ==== Example:
-
# # Instantiates a single new object
-
# User.new(first_name: 'Jamie')
-
1
def initialize(attributes = nil, options = {})
-
defaults = self.class.column_defaults.dup
-
defaults.each { |k, v| defaults[k] = v.dup if v.duplicable? }
-
-
@attributes = self.class.initialize_attributes(defaults)
-
@column_types_override = nil
-
@column_types = self.class.column_types
-
-
init_internals
-
initialize_internals_callback
-
-
# +options+ argument is only needed to make protected_attributes gem easier to hook.
-
# Remove it when we drop support to this gem.
-
init_attributes(attributes, options) if attributes
-
-
yield self if block_given?
-
run_callbacks :initialize unless _initialize_callbacks.empty?
-
end
-
-
# Initialize an empty model object from +coder+. +coder+ must contain
-
# the attributes necessary for initializing an empty model object. For
-
# example:
-
#
-
# class Post < ActiveRecord::Base
-
# end
-
#
-
# post = Post.allocate
-
# post.init_with('attributes' => { 'title' => 'hello world' })
-
# post.title # => 'hello world'
-
1
def init_with(coder)
-
@attributes = self.class.initialize_attributes(coder['attributes'])
-
@column_types_override = coder['column_types']
-
@column_types = self.class.column_types
-
-
init_internals
-
-
@new_record = false
-
-
run_callbacks :find
-
run_callbacks :initialize
-
-
self
-
end
-
-
##
-
# :method: clone
-
# Identical to Ruby's clone method. This is a "shallow" copy. Be warned that your attributes are not copied.
-
# That means that modifying attributes of the clone will modify the original, since they will both point to the
-
# same attributes hash. If you need a copy of your attributes hash, please use the #dup method.
-
#
-
# user = User.first
-
# new_user = user.clone
-
# user.name # => "Bob"
-
# new_user.name = "Joe"
-
# user.name # => "Joe"
-
#
-
# user.object_id == new_user.object_id # => false
-
# user.name.object_id == new_user.name.object_id # => true
-
#
-
# user.name.object_id == user.dup.name.object_id # => false
-
-
##
-
# :method: dup
-
# Duped objects have no id assigned and are treated as new records. Note
-
# that this is a "shallow" copy as it copies the object's attributes
-
# only, not its associations. The extent of a "deep" copy is application
-
# specific and is therefore left to the application to implement according
-
# to its need.
-
# The dup method does not preserve the timestamps (created|updated)_(at|on).
-
-
##
-
1
def initialize_dup(other) # :nodoc:
-
cloned_attributes = other.clone_attributes(:read_attribute_before_type_cast)
-
self.class.initialize_attributes(cloned_attributes, :serialized => false)
-
-
@attributes = cloned_attributes
-
@attributes[self.class.primary_key] = nil
-
-
run_callbacks(:initialize) unless _initialize_callbacks.empty?
-
-
@aggregation_cache = {}
-
@association_cache = {}
-
@attributes_cache = {}
-
-
@new_record = true
-
-
super
-
end
-
-
# Populate +coder+ with attributes about this record that should be
-
# serialized. The structure of +coder+ defined in this method is
-
# guaranteed to match the structure of +coder+ passed to the +init_with+
-
# method.
-
#
-
# Example:
-
#
-
# class Post < ActiveRecord::Base
-
# end
-
# coder = {}
-
# Post.new.encode_with(coder)
-
# coder # => {"attributes" => {"id" => nil, ... }}
-
1
def encode_with(coder)
-
coder['attributes'] = attributes_for_coder
-
end
-
-
# Returns true if +comparison_object+ is the same exact object, or +comparison_object+
-
# is of the same type and +self+ has an ID and it is equal to +comparison_object.id+.
-
#
-
# Note that new records are different from any other record by definition, unless the
-
# other record is the receiver itself. Besides, if you fetch existing records with
-
# +select+ and leave the ID out, you're on your own, this predicate will return false.
-
#
-
# Note also that destroying a record preserves its ID in the model instance, so deleted
-
# models are still comparable.
-
1
def ==(comparison_object)
-
super ||
-
comparison_object.instance_of?(self.class) &&
-
!id.nil? &&
-
comparison_object.id == id
-
end
-
1
alias :eql? :==
-
-
# Delegates to id in order to allow two records of the same type and id to work with something like:
-
# [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]
-
1
def hash
-
id.hash
-
end
-
-
# Clone and freeze the attributes hash such that associations are still
-
# accessible, even on destroyed records, but cloned models will not be
-
# frozen.
-
1
def freeze
-
@attributes = @attributes.clone.freeze
-
self
-
end
-
-
# Returns +true+ if the attributes hash has been frozen.
-
1
def frozen?
-
@attributes.frozen?
-
end
-
-
# Allows sort on objects
-
1
def <=>(other_object)
-
if other_object.is_a?(self.class)
-
self.to_key <=> other_object.to_key
-
else
-
super
-
end
-
end
-
-
# Returns +true+ if the record is read only. Records loaded through joins with piggy-back
-
# attributes will be marked as read only since they cannot be saved.
-
1
def readonly?
-
@readonly
-
end
-
-
# Marks this record as read only.
-
1
def readonly!
-
@readonly = true
-
end
-
-
1
def connection_handler
-
self.class.connection_handler
-
end
-
-
# Returns the contents of the record as a nicely formatted string.
-
1
def inspect
-
# We check defined?(@attributes) not to issue warnings if the object is
-
# allocated but not initialized.
-
inspection = if defined?(@attributes) && @attributes
-
self.class.column_names.collect { |name|
-
if has_attribute?(name)
-
"#{name}: #{attribute_for_inspect(name)}"
-
end
-
}.compact.join(", ")
-
else
-
"not initialized"
-
end
-
"#<#{self.class} #{inspection}>"
-
end
-
-
# Returns a hash of the given methods with their names as keys and returned values as values.
-
1
def slice(*methods)
-
Hash[methods.map! { |method| [method, public_send(method)] }].with_indifferent_access
-
end
-
-
1
def set_transaction_state(state) # :nodoc:
-
@transaction_state = state
-
end
-
-
1
def has_transactional_callbacks? # :nodoc:
-
!_rollback_callbacks.empty? || !_commit_callbacks.empty? || !_create_callbacks.empty?
-
end
-
-
1
private
-
-
# Updates the attributes on this particular ActiveRecord object so that
-
# if it is associated with a transaction, then the state of the AR object
-
# will be updated to reflect the current state of the transaction
-
#
-
# The @transaction_state variable stores the states of the associated
-
# transaction. This relies on the fact that a transaction can only be in
-
# one rollback or commit (otherwise a list of states would be required)
-
# Each AR object inside of a transaction carries that transaction's
-
# TransactionState.
-
#
-
# This method checks to see if the ActiveRecord object's state reflects
-
# the TransactionState, and rolls back or commits the ActiveRecord object
-
# as appropriate.
-
#
-
# Since ActiveRecord objects can be inside multiple transactions, this
-
# method recursively goes through the parent of the TransactionState and
-
# checks if the ActiveRecord object reflects the state of the object.
-
1
def sync_with_transaction_state
-
update_attributes_from_transaction_state(@transaction_state, 0)
-
end
-
-
1
def update_attributes_from_transaction_state(transaction_state, depth)
-
if transaction_state && transaction_state.finalized? && !has_transactional_callbacks?
-
unless @reflects_state[depth]
-
restore_transaction_record_state if transaction_state.rolledback?
-
clear_transaction_record_state
-
@reflects_state[depth] = true
-
end
-
-
if transaction_state.parent && !@reflects_state[depth+1]
-
update_attributes_from_transaction_state(transaction_state.parent, depth+1)
-
end
-
end
-
end
-
-
# Under Ruby 1.9, Array#flatten will call #to_ary (recursively) on each of the elements
-
# of the array, and then rescues from the possible NoMethodError. If those elements are
-
# ActiveRecord::Base's, then this triggers the various method_missing's that we have,
-
# which significantly impacts upon performance.
-
#
-
# So we can avoid the method_missing hit by explicitly defining #to_ary as nil here.
-
#
-
# See also http://tenderlovemaking.com/2011/06/28/til-its-ok-to-return-nil-from-to_ary.html
-
1
def to_ary # :nodoc:
-
nil
-
end
-
-
1
def init_internals
-
pk = self.class.primary_key
-
@attributes[pk] = nil unless @attributes.key?(pk)
-
-
@aggregation_cache = {}
-
@association_cache = {}
-
@attributes_cache = {}
-
@readonly = false
-
@destroyed = false
-
@marked_for_destruction = false
-
@destroyed_by_association = nil
-
@new_record = true
-
@txn = nil
-
@_start_transaction_state = {}
-
@transaction_state = nil
-
@reflects_state = [false]
-
end
-
-
1
def initialize_internals_callback
-
end
-
-
# This method is needed to make protected_attributes gem easier to hook.
-
# Remove it when we drop support to this gem.
-
1
def init_attributes(attributes, options)
-
assign_attributes(attributes)
-
end
-
end
-
end
-
1
module ActiveRecord
-
# = Active Record Counter Cache
-
1
module CounterCache
-
1
extend ActiveSupport::Concern
-
-
1
module ClassMethods
-
# Resets one or more counter caches to their correct value using an SQL
-
# count query. This is useful when adding new counter caches, or if the
-
# counter has been corrupted or modified directly by SQL.
-
#
-
# ==== Parameters
-
#
-
# * +id+ - The id of the object you wish to reset a counter on.
-
# * +counters+ - One or more association counters to reset
-
#
-
# ==== Examples
-
#
-
# # For Post with id #1 records reset the comments_count
-
# Post.reset_counters(1, :comments)
-
1
def reset_counters(id, *counters)
-
object = find(id)
-
counters.each do |association|
-
has_many_association = reflect_on_association(association.to_sym)
-
raise ArgumentError, "'#{self.name}' has no association called '#{association}'" unless has_many_association
-
-
if has_many_association.is_a? ActiveRecord::Reflection::ThroughReflection
-
has_many_association = has_many_association.through_reflection
-
end
-
-
foreign_key = has_many_association.foreign_key.to_s
-
child_class = has_many_association.klass
-
belongs_to = child_class.reflect_on_all_associations(:belongs_to)
-
reflection = belongs_to.find { |e| e.foreign_key.to_s == foreign_key && e.options[:counter_cache].present? }
-
counter_name = reflection.counter_cache_column
-
-
stmt = unscoped.where(arel_table[primary_key].eq(object.id)).arel.compile_update({
-
arel_table[counter_name] => object.send(association).count
-
}, primary_key)
-
connection.update stmt
-
end
-
return true
-
end
-
-
# A generic "counter updater" implementation, intended primarily to be
-
# used by increment_counter and decrement_counter, but which may also
-
# be useful on its own. It simply does a direct SQL update for the record
-
# with the given ID, altering the given hash of counters by the amount
-
# given by the corresponding value:
-
#
-
# ==== Parameters
-
#
-
# * +id+ - The id of the object you wish to update a counter on or an Array of ids.
-
# * +counters+ - A Hash containing the names of the fields
-
# to update as keys and the amount to update the field by as values.
-
#
-
# ==== Examples
-
#
-
# # For the Post with id of 5, decrement the comment_count by 1, and
-
# # increment the action_count by 1
-
# Post.update_counters 5, comment_count: -1, action_count: 1
-
# # Executes the following SQL:
-
# # UPDATE posts
-
# # SET comment_count = COALESCE(comment_count, 0) - 1,
-
# # action_count = COALESCE(action_count, 0) + 1
-
# # WHERE id = 5
-
#
-
# # For the Posts with id of 10 and 15, increment the comment_count by 1
-
# Post.update_counters [10, 15], comment_count: 1
-
# # Executes the following SQL:
-
# # UPDATE posts
-
# # SET comment_count = COALESCE(comment_count, 0) + 1
-
# # WHERE id IN (10, 15)
-
1
def update_counters(id, counters)
-
updates = counters.map do |counter_name, value|
-
operator = value < 0 ? '-' : '+'
-
quoted_column = connection.quote_column_name(counter_name)
-
"#{quoted_column} = COALESCE(#{quoted_column}, 0) #{operator} #{value.abs}"
-
end
-
-
unscoped.where(primary_key => id).update_all updates.join(', ')
-
end
-
-
# Increment a numeric field by one, via a direct SQL update.
-
#
-
# This method is used primarily for maintaining counter_cache columns that are
-
# used to store aggregate values. For example, a DiscussionBoard may cache
-
# posts_count and comments_count to avoid running an SQL query to calculate the
-
# number of posts and comments there are, each time it is displayed.
-
#
-
# ==== Parameters
-
#
-
# * +counter_name+ - The name of the field that should be incremented.
-
# * +id+ - The id of the object that should be incremented or an Array of ids.
-
#
-
# ==== Examples
-
#
-
# # Increment the post_count column for the record with an id of 5
-
# DiscussionBoard.increment_counter(:post_count, 5)
-
1
def increment_counter(counter_name, id)
-
update_counters(id, counter_name => 1)
-
end
-
-
# Decrement a numeric field by one, via a direct SQL update.
-
#
-
# This works the same as increment_counter but reduces the column value by
-
# 1 instead of increasing it.
-
#
-
# ==== Parameters
-
#
-
# * +counter_name+ - The name of the field that should be decremented.
-
# * +id+ - The id of the object that should be decremented or an Array of ids.
-
#
-
# ==== Examples
-
#
-
# # Decrement the post_count column for the record with an id of 5
-
# DiscussionBoard.decrement_counter(:post_count, 5)
-
1
def decrement_counter(counter_name, id)
-
update_counters(id, counter_name => -1)
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module DynamicMatchers #:nodoc:
-
# This code in this file seems to have a lot of indirection, but the indirection
-
# is there to provide extension points for the activerecord-deprecated_finders
-
# gem. When we stop supporting activerecord-deprecated_finders (from Rails 5),
-
# then we can remove the indirection.
-
-
1
def respond_to?(name, include_private = false)
-
12
if self == Base
-
5
super
-
else
-
7
match = Method.match(self, name)
-
7
match && match.valid? || super
-
end
-
end
-
-
1
private
-
-
1
def method_missing(name, *arguments, &block)
-
match = Method.match(self, name)
-
-
if match && match.valid?
-
match.define
-
send(name, *arguments, &block)
-
else
-
super
-
end
-
end
-
-
1
class Method
-
1
@matchers = []
-
-
1
class << self
-
1
attr_reader :matchers
-
-
1
def match(model, name)
-
21
klass = matchers.find { |k| name =~ k.pattern }
-
7
klass.new(model, name) if klass
-
end
-
-
1
def pattern
-
14
@pattern ||= /\A#{prefix}_([_a-zA-Z]\w*)#{suffix}\Z/
-
end
-
-
1
def prefix
-
raise NotImplementedError
-
end
-
-
1
def suffix
-
1
''
-
end
-
end
-
-
1
attr_reader :model, :name, :attribute_names
-
-
1
def initialize(model, name)
-
@model = model
-
@name = name.to_s
-
@attribute_names = @name.match(self.class.pattern)[1].split('_and_')
-
@attribute_names.map! { |n| @model.attribute_aliases[n] || n }
-
end
-
-
1
def valid?
-
attribute_names.all? { |name| model.columns_hash[name] || model.reflect_on_aggregation(name.to_sym) }
-
end
-
-
1
def define
-
model.class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def self.#{name}(#{signature})
-
#{body}
-
end
-
CODE
-
end
-
-
1
def body
-
raise NotImplementedError
-
end
-
end
-
-
1
module Finder
-
# Extended in activerecord-deprecated_finders
-
1
def body
-
result
-
end
-
-
# Extended in activerecord-deprecated_finders
-
1
def result
-
"#{finder}(#{attributes_hash})"
-
end
-
-
# The parameters in the signature may have reserved Ruby words, in order
-
# to prevent errors, we start each param name with `_`.
-
#
-
# Extended in activerecord-deprecated_finders
-
1
def signature
-
attribute_names.map { |name| "_#{name}" }.join(', ')
-
end
-
-
# Given that the parameters starts with `_`, the finder needs to use the
-
# same parameter name.
-
1
def attributes_hash
-
"{" + attribute_names.map { |name| ":#{name} => _#{name}" }.join(',') + "}"
-
end
-
-
1
def finder
-
raise NotImplementedError
-
end
-
end
-
-
1
class FindBy < Method
-
1
Method.matchers << self
-
1
include Finder
-
-
1
def self.prefix
-
1
"find_by"
-
end
-
-
1
def finder
-
"find_by"
-
end
-
end
-
-
1
class FindByBang < Method
-
1
Method.matchers << self
-
1
include Finder
-
-
1
def self.prefix
-
1
"find_by"
-
end
-
-
1
def self.suffix
-
1
"!"
-
end
-
-
1
def finder
-
"find_by!"
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/object/deep_dup'
-
-
1
module ActiveRecord
-
# Declare an enum attribute where the values map to integers in the database,
-
# but can be queried by name. Example:
-
#
-
# class Conversation < ActiveRecord::Base
-
# enum status: [ :active, :archived ]
-
# end
-
#
-
# # conversation.update! status: 0
-
# conversation.active!
-
# conversation.active? # => true
-
# conversation.status # => "active"
-
#
-
# # conversation.update! status: 1
-
# conversation.archived!
-
# conversation.archived? # => true
-
# conversation.status # => "archived"
-
#
-
# # conversation.update! status: 1
-
# conversation.status = "archived"
-
#
-
# # conversation.update! status: nil
-
# conversation.status = nil
-
# conversation.status.nil? # => true
-
# conversation.status # => nil
-
#
-
# Scopes based on the allowed values of the enum field will be provided
-
# as well. With the above example, it will create an +active+ and +archived+
-
# scope.
-
#
-
# You can set the default value from the database declaration, like:
-
#
-
# create_table :conversations do |t|
-
# t.column :status, :integer, default: 0
-
# end
-
#
-
# Good practice is to let the first declared status be the default.
-
#
-
# Finally, it's also possible to explicitly map the relation between attribute and
-
# database integer with a +Hash+:
-
#
-
# class Conversation < ActiveRecord::Base
-
# enum status: { active: 0, archived: 1 }
-
# end
-
#
-
# Note that when an +Array+ is used, the implicit mapping from the values to database
-
# integers is derived from the order the values appear in the array. In the example,
-
# <tt>:active</tt> is mapped to +0+ as it's the first element, and <tt>:archived</tt>
-
# is mapped to +1+. In general, the +i+-th element is mapped to <tt>i-1</tt> in the
-
# database.
-
#
-
# Therefore, once a value is added to the enum array, its position in the array must
-
# be maintained, and new values should only be added to the end of the array. To
-
# remove unused values, the explicit +Hash+ syntax should be used.
-
#
-
# In rare circumstances you might need to access the mapping directly.
-
# The mappings are exposed through a class method with the pluralized attribute
-
# name:
-
#
-
# Conversation.statuses # => { "active" => 0, "archived" => 1 }
-
#
-
# Use that class method when you need to know the ordinal value of an enum:
-
#
-
# Conversation.where("status <> ?", Conversation.statuses[:archived])
-
#
-
# Where conditions on an enum attribute must use the ordinal value of an enum.
-
1
module Enum
-
1
def self.extended(base)
-
1
base.class_attribute(:defined_enums)
-
1
base.defined_enums = {}
-
end
-
-
1
def inherited(base)
-
2
base.defined_enums = defined_enums.deep_dup
-
2
super
-
end
-
-
1
def enum(definitions)
-
klass = self
-
definitions.each do |name, values|
-
# statuses = { }
-
enum_values = ActiveSupport::HashWithIndifferentAccess.new
-
name = name.to_sym
-
-
# def self.statuses statuses end
-
detect_enum_conflict!(name, name.to_s.pluralize, true)
-
klass.singleton_class.send(:define_method, name.to_s.pluralize) { enum_values }
-
-
_enum_methods_module.module_eval do
-
# def status=(value) self[:status] = statuses[value] end
-
klass.send(:detect_enum_conflict!, name, "#{name}=")
-
define_method("#{name}=") { |value|
-
if enum_values.has_key?(value) || value.blank?
-
self[name] = enum_values[value]
-
elsif enum_values.has_value?(value)
-
# Assigning a value directly is not a end-user feature, hence it's not documented.
-
# This is used internally to make building objects from the generated scopes work
-
# as expected, i.e. +Conversation.archived.build.archived?+ should be true.
-
self[name] = value
-
else
-
raise ArgumentError, "'#{value}' is not a valid #{name}"
-
end
-
}
-
-
# def status() statuses.key self[:status] end
-
klass.send(:detect_enum_conflict!, name, name)
-
define_method(name) { enum_values.key self[name] }
-
-
# def status_before_type_cast() statuses.key self[:status] end
-
klass.send(:detect_enum_conflict!, name, "#{name}_before_type_cast")
-
define_method("#{name}_before_type_cast") { enum_values.key self[name] }
-
-
pairs = values.respond_to?(:each_pair) ? values.each_pair : values.each_with_index
-
pairs.each do |value, i|
-
enum_values[value] = i
-
-
# def active?() status == 0 end
-
klass.send(:detect_enum_conflict!, name, "#{value}?")
-
define_method("#{value}?") { self[name] == i }
-
-
# def active!() update! status: :active end
-
klass.send(:detect_enum_conflict!, name, "#{value}!")
-
define_method("#{value}!") { update! name => value }
-
-
# scope :active, -> { where status: 0 }
-
klass.send(:detect_enum_conflict!, name, value, true)
-
klass.scope value, -> { klass.where name => i }
-
end
-
end
-
defined_enums[name.to_s] = enum_values
-
end
-
end
-
-
1
private
-
1
def _enum_methods_module
-
@_enum_methods_module ||= begin
-
mod = Module.new do
-
private
-
def save_changed_attribute(attr_name, value)
-
if (mapping = self.class.defined_enums[attr_name.to_s])
-
if attribute_changed?(attr_name)
-
old = changed_attributes[attr_name]
-
-
if mapping[old] == value
-
changed_attributes.delete(attr_name)
-
end
-
else
-
old = clone_attribute_value(:read_attribute, attr_name)
-
-
if old != value
-
changed_attributes[attr_name] = mapping.key old
-
end
-
end
-
else
-
super
-
end
-
end
-
end
-
include mod
-
mod
-
end
-
end
-
-
1
ENUM_CONFLICT_MESSAGE = \
-
"You tried to define an enum named \"%{enum}\" on the model \"%{klass}\", but " \
-
"this will generate a %{type} method \"%{method}\", which is already defined " \
-
"by %{source}."
-
-
1
def detect_enum_conflict!(enum_name, method_name, klass_method = false)
-
if klass_method && dangerous_class_method?(method_name)
-
raise ArgumentError, ENUM_CONFLICT_MESSAGE % {
-
enum: enum_name,
-
klass: self.name,
-
type: 'class',
-
method: method_name,
-
source: 'Active Record'
-
}
-
elsif !klass_method && dangerous_attribute_method?(method_name)
-
raise ArgumentError, ENUM_CONFLICT_MESSAGE % {
-
enum: enum_name,
-
klass: self.name,
-
type: 'instance',
-
method: method_name,
-
source: 'Active Record'
-
}
-
elsif !klass_method && method_defined_within?(method_name, _enum_methods_module, Module)
-
raise ArgumentError, ENUM_CONFLICT_MESSAGE % {
-
enum: enum_name,
-
klass: self.name,
-
type: 'instance',
-
method: method_name,
-
source: 'another enum'
-
}
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
-
# = Active Record Errors
-
#
-
# Generic Active Record exception class.
-
1
class ActiveRecordError < StandardError
-
end
-
-
# Raised when the single-table inheritance mechanism fails to locate the subclass
-
# (for example due to improper usage of column that +inheritance_column+ points to).
-
1
class SubclassNotFound < ActiveRecordError #:nodoc:
-
end
-
-
# Raised when an object assigned to an association has an incorrect type.
-
#
-
# class Ticket < ActiveRecord::Base
-
# has_many :patches
-
# end
-
#
-
# class Patch < ActiveRecord::Base
-
# belongs_to :ticket
-
# end
-
#
-
# # Comments are not patches, this assignment raises AssociationTypeMismatch.
-
# @ticket.patches << Comment.new(content: "Please attach tests to your patch.")
-
1
class AssociationTypeMismatch < ActiveRecordError
-
end
-
-
# Raised when unserialized object's type mismatches one specified for serializable field.
-
1
class SerializationTypeMismatch < ActiveRecordError
-
end
-
-
# Raised when adapter not specified on connection (or configuration file <tt>config/database.yml</tt>
-
# misses adapter field).
-
1
class AdapterNotSpecified < ActiveRecordError
-
end
-
-
# Raised when Active Record cannot find database adapter specified in <tt>config/database.yml</tt> or programmatically.
-
1
class AdapterNotFound < ActiveRecordError
-
end
-
-
# Raised when connection to the database could not been established (for example when <tt>connection=</tt>
-
# is given a nil object).
-
1
class ConnectionNotEstablished < ActiveRecordError
-
end
-
-
# Raised when Active Record cannot find record by given id or set of ids.
-
1
class RecordNotFound < ActiveRecordError
-
end
-
-
# Raised by ActiveRecord::Base.save! and ActiveRecord::Base.create! methods when record cannot be
-
# saved because record is invalid.
-
1
class RecordNotSaved < ActiveRecordError
-
end
-
-
# Raised by ActiveRecord::Base.destroy! when a call to destroy would return false.
-
1
class RecordNotDestroyed < ActiveRecordError
-
end
-
-
# Superclass for all database execution errors.
-
#
-
# Wraps the underlying database error as +original_exception+.
-
1
class StatementInvalid < ActiveRecordError
-
1
attr_reader :original_exception
-
-
1
def initialize(message, original_exception = nil)
-
super(message)
-
@original_exception = original_exception
-
end
-
end
-
-
# Defunct wrapper class kept for compatibility.
-
# +StatementInvalid+ wraps the original exception now.
-
1
class WrappedDatabaseException < StatementInvalid
-
end
-
-
# Raised when a record cannot be inserted because it would violate a uniqueness constraint.
-
1
class RecordNotUnique < WrappedDatabaseException
-
end
-
-
# Raised when a record cannot be inserted or updated because it references a non-existent record.
-
1
class InvalidForeignKey < WrappedDatabaseException
-
end
-
-
# Raised when number of bind variables in statement given to <tt>:condition</tt> key (for example,
-
# when using +find+ method)
-
# does not match number of expected variables.
-
#
-
# For example, in
-
#
-
# Location.where("lat = ? AND lng = ?", 53.7362)
-
#
-
# two placeholders are given but only one variable to fill them.
-
1
class PreparedStatementInvalid < ActiveRecordError
-
end
-
-
# Raised when a given database does not exist
-
1
class NoDatabaseError < ActiveRecordError
-
1
def initialize(message)
-
super extend_message(message)
-
end
-
-
# can be over written to add additional error information.
-
1
def extend_message(message)
-
message
-
end
-
end
-
-
# Raised on attempt to save stale record. Record is stale when it's being saved in another query after
-
# instantiation, for example, when two users edit the same wiki page and one starts editing and saves
-
# the page before the other.
-
#
-
# Read more about optimistic locking in ActiveRecord::Locking module RDoc.
-
1
class StaleObjectError < ActiveRecordError
-
1
attr_reader :record, :attempted_action
-
-
1
def initialize(record, attempted_action)
-
super("Attempted to #{attempted_action} a stale object: #{record.class.name}")
-
@record = record
-
@attempted_action = attempted_action
-
end
-
-
end
-
-
# Raised when association is being configured improperly or
-
# user tries to use offset and limit together with has_many or has_and_belongs_to_many associations.
-
1
class ConfigurationError < ActiveRecordError
-
end
-
-
# Raised on attempt to update record that is instantiated as read only.
-
1
class ReadOnlyRecord < ActiveRecordError
-
end
-
-
# ActiveRecord::Transactions::ClassMethods.transaction uses this exception
-
# to distinguish a deliberate rollback from other exceptional situations.
-
# Normally, raising an exception will cause the +transaction+ method to rollback
-
# the database transaction *and* pass on the exception. But if you raise an
-
# ActiveRecord::Rollback exception, then the database transaction will be rolled back,
-
# without passing on the exception.
-
#
-
# For example, you could do this in your controller to rollback a transaction:
-
#
-
# class BooksController < ActionController::Base
-
# def create
-
# Book.transaction do
-
# book = Book.new(params[:book])
-
# book.save!
-
# if today_is_friday?
-
# # The system must fail on Friday so that our support department
-
# # won't be out of job. We silently rollback this transaction
-
# # without telling the user.
-
# raise ActiveRecord::Rollback, "Call tech support!"
-
# end
-
# end
-
# # ActiveRecord::Rollback is the only exception that won't be passed on
-
# # by ActiveRecord::Base.transaction, so this line will still be reached
-
# # even on Friday.
-
# redirect_to root_url
-
# end
-
# end
-
1
class Rollback < ActiveRecordError
-
end
-
-
# Raised when attribute has a name reserved by Active Record (when attribute has name of one of Active Record instance methods).
-
1
class DangerousAttributeError < ActiveRecordError
-
end
-
-
# Raised when unknown attributes are supplied via mass assignment.
-
1
class UnknownAttributeError < NoMethodError
-
-
1
attr_reader :record, :attribute
-
-
1
def initialize(record, attribute)
-
@record = record
-
@attribute = attribute.to_s
-
super("unknown attribute: #{attribute}")
-
end
-
-
end
-
-
# Raised when an error occurred while doing a mass assignment to an attribute through the
-
# <tt>attributes=</tt> method. The exception has an +attribute+ property that is the name of the
-
# offending attribute.
-
1
class AttributeAssignmentError < ActiveRecordError
-
1
attr_reader :exception, :attribute
-
1
def initialize(message, exception, attribute)
-
super(message)
-
@exception = exception
-
@attribute = attribute
-
end
-
end
-
-
# Raised when there are multiple errors while doing a mass assignment through the +attributes+
-
# method. The exception has an +errors+ property that contains an array of AttributeAssignmentError
-
# objects, each corresponding to the error while assigning to an attribute.
-
1
class MultiparameterAssignmentErrors < ActiveRecordError
-
1
attr_reader :errors
-
1
def initialize(errors)
-
@errors = errors
-
end
-
end
-
-
# Raised when a primary key is needed, but not specified in the schema or model.
-
1
class UnknownPrimaryKey < ActiveRecordError
-
1
attr_reader :model
-
-
1
def initialize(model)
-
super("Unknown primary key for table #{model.table_name} in model #{model}.")
-
@model = model
-
end
-
-
end
-
-
# Raised when a relation cannot be mutated because it's already loaded.
-
#
-
# class Task < ActiveRecord::Base
-
# end
-
#
-
# relation = Task.all
-
# relation.loaded? # => true
-
#
-
# # Methods which try to mutate a loaded relation fail.
-
# relation.where!(title: 'TODO') # => ActiveRecord::ImmutableRelation
-
# relation.limit!(5) # => ActiveRecord::ImmutableRelation
-
1
class ImmutableRelation < ActiveRecordError
-
end
-
-
1
class TransactionIsolationError < ActiveRecordError
-
end
-
end
-
1
require 'active_support/lazy_load_hooks'
-
1
require 'active_record/explain_registry'
-
-
1
module ActiveRecord
-
1
module Explain
-
# Executes the block with the collect flag enabled. Queries are collected
-
# asynchronously by the subscriber and returned.
-
1
def collecting_queries_for_explain # :nodoc:
-
ExplainRegistry.collect = true
-
yield
-
ExplainRegistry.queries
-
ensure
-
ExplainRegistry.reset
-
end
-
-
# Makes the adapter execute EXPLAIN for the tuples of queries and bindings.
-
# Returns a formatted string ready to be logged.
-
1
def exec_explain(queries) # :nodoc:
-
str = queries.map do |sql, bind|
-
[].tap do |msg|
-
msg << "EXPLAIN for: #{sql}"
-
unless bind.empty?
-
bind_msg = bind.map {|col, val| [col.name, val]}.inspect
-
msg.last << " #{bind_msg}"
-
end
-
msg << connection.explain(sql, bind)
-
end.join("\n")
-
end.join("\n")
-
-
# Overriding inspect to be more human readable, specially in the console.
-
def str.inspect
-
self
-
end
-
-
str
-
end
-
end
-
end
-
1
require 'active_support/per_thread_registry'
-
-
1
module ActiveRecord
-
# This is a thread locals registry for EXPLAIN. For example
-
#
-
# ActiveRecord::ExplainRegistry.queries
-
#
-
# returns the collected queries local to the current thread.
-
#
-
# See the documentation of <tt>ActiveSupport::PerThreadRegistry</tt>
-
# for further details.
-
1
class ExplainRegistry # :nodoc:
-
1
extend ActiveSupport::PerThreadRegistry
-
-
1
attr_accessor :queries, :collect
-
-
1
def initialize
-
1
reset
-
end
-
-
1
def collect?
-
9
@collect
-
end
-
-
1
def reset
-
1
@collect = false
-
1
@queries = []
-
end
-
end
-
end
-
1
require 'active_support/notifications'
-
1
require 'active_record/explain_registry'
-
-
1
module ActiveRecord
-
1
class ExplainSubscriber # :nodoc:
-
1
def start(name, id, payload)
-
# unused
-
end
-
-
1
def finish(name, id, payload)
-
9
if ExplainRegistry.collect? && !ignore_payload?(payload)
-
ExplainRegistry.queries << payload.values_at(:sql, :binds)
-
end
-
end
-
-
# SCHEMA queries cannot be EXPLAINed, also we do not want to run EXPLAIN on
-
# our own EXPLAINs now matter how loopingly beautiful that would be.
-
#
-
# On the other hand, we want to monitor the performance of our real database
-
# queries, not the performance of the access to the query cache.
-
1
IGNORED_PAYLOADS = %w(SCHEMA EXPLAIN CACHE)
-
1
EXPLAINED_SQLS = /\A\s*(select|update|delete|insert)\b/i
-
1
def ignore_payload?(payload)
-
payload[:exception] || IGNORED_PAYLOADS.include?(payload[:name]) || payload[:sql] !~ EXPLAINED_SQLS
-
end
-
-
1
ActiveSupport::Notifications.subscribe("sql.active_record", new)
-
end
-
end
-
1
require 'erb'
-
1
require 'yaml'
-
-
1
module ActiveRecord
-
1
class FixtureSet
-
1
class File # :nodoc:
-
1
include Enumerable
-
-
##
-
# Open a fixture file named +file+. When called with a block, the block
-
# is called with the filehandle and the filehandle is automatically closed
-
# when the block finishes.
-
1
def self.open(file)
-
x = new file
-
block_given? ? yield(x) : x
-
end
-
-
1
def initialize(file)
-
@file = file
-
@rows = nil
-
end
-
-
1
def each(&block)
-
rows.each(&block)
-
end
-
-
-
1
private
-
1
def rows
-
return @rows if @rows
-
-
begin
-
data = YAML.load(render(IO.read(@file)))
-
rescue ArgumentError, Psych::SyntaxError => error
-
raise Fixture::FormatError, "a YAML error occurred parsing #{@file}. Please note that YAML must be consistently indented using spaces. Tabs are not allowed. Please have a look at http://www.yaml.org/faq.html\nThe exact error was:\n #{error.class}: #{error}", error.backtrace
-
end
-
@rows = data ? validate(data).to_a : []
-
end
-
-
1
def render(content)
-
context = ActiveRecord::FixtureSet::RenderContext.create_subclass.new
-
ERB.new(content).result(context.get_binding)
-
end
-
-
# Validate our unmarshalled data.
-
1
def validate(data)
-
unless Hash === data || YAML::Omap === data
-
raise Fixture::FormatError, 'fixture is not a hash'
-
end
-
-
raise Fixture::FormatError unless data.all? { |name, row| Hash === row }
-
data
-
end
-
end
-
end
-
end
-
1
require 'erb'
-
1
require 'yaml'
-
1
require 'zlib'
-
1
require 'active_support/dependencies'
-
1
require 'active_record/fixture_set/file'
-
1
require 'active_record/errors'
-
-
1
module ActiveRecord
-
1
class FixtureClassNotFound < ActiveRecord::ActiveRecordError #:nodoc:
-
end
-
-
# \Fixtures are a way of organizing data that you want to test against; in short, sample data.
-
#
-
# They are stored in YAML files, one file per model, which are placed in the directory
-
# appointed by <tt>ActiveSupport::TestCase.fixture_path=(path)</tt> (this is automatically
-
# configured for Rails, so you can just put your files in <tt><your-rails-app>/test/fixtures/</tt>).
-
# The fixture file ends with the <tt>.yml</tt> file extension (Rails example:
-
# <tt><your-rails-app>/test/fixtures/web_sites.yml</tt>). The format of a fixture file looks
-
# like this:
-
#
-
# rubyonrails:
-
# id: 1
-
# name: Ruby on Rails
-
# url: http://www.rubyonrails.org
-
#
-
# google:
-
# id: 2
-
# name: Google
-
# url: http://www.google.com
-
#
-
# This fixture file includes two fixtures. Each YAML fixture (ie. record) is given a name and
-
# is followed by an indented list of key/value pairs in the "key: value" format. Records are
-
# separated by a blank line for your viewing pleasure.
-
#
-
# Note that fixtures are unordered. If you want ordered fixtures, use the omap YAML type.
-
# See http://yaml.org/type/omap.html
-
# for the specification. You will need ordered fixtures when you have foreign key constraints
-
# on keys in the same table. This is commonly needed for tree structures. Example:
-
#
-
# --- !omap
-
# - parent:
-
# id: 1
-
# parent_id: NULL
-
# title: Parent
-
# - child:
-
# id: 2
-
# parent_id: 1
-
# title: Child
-
#
-
# = Using Fixtures in Test Cases
-
#
-
# Since fixtures are a testing construct, we use them in our unit and functional tests. There
-
# are two ways to use the fixtures, but first let's take a look at a sample unit test:
-
#
-
# require 'test_helper'
-
#
-
# class WebSiteTest < ActiveSupport::TestCase
-
# test "web_site_count" do
-
# assert_equal 2, WebSite.count
-
# end
-
# end
-
#
-
# By default, <tt>test_helper.rb</tt> will load all of your fixtures into your test database,
-
# so this test will succeed.
-
#
-
# The testing environment will automatically load the all fixtures into the database before each
-
# test. To ensure consistent data, the environment deletes the fixtures before running the load.
-
#
-
# In addition to being available in the database, the fixture's data may also be accessed by
-
# using a special dynamic method, which has the same name as the model, and accepts the
-
# name of the fixture to instantiate:
-
#
-
# test "find" do
-
# assert_equal "Ruby on Rails", web_sites(:rubyonrails).name
-
# end
-
#
-
# Alternatively, you may enable auto-instantiation of the fixture data. For instance, take the
-
# following tests:
-
#
-
# test "find_alt_method_1" do
-
# assert_equal "Ruby on Rails", @web_sites['rubyonrails']['name']
-
# end
-
#
-
# test "find_alt_method_2" do
-
# assert_equal "Ruby on Rails", @rubyonrails.name
-
# end
-
#
-
# In order to use these methods to access fixtured data within your testcases, you must specify one of the
-
# following in your <tt>ActiveSupport::TestCase</tt>-derived class:
-
#
-
# - to fully enable instantiated fixtures (enable alternate methods #1 and #2 above)
-
# self.use_instantiated_fixtures = true
-
#
-
# - create only the hash for the fixtures, do not 'find' each instance (enable alternate method #1 only)
-
# self.use_instantiated_fixtures = :no_instances
-
#
-
# Using either of these alternate methods incurs a performance hit, as the fixtured data must be fully
-
# traversed in the database to create the fixture hash and/or instance variables. This is expensive for
-
# large sets of fixtured data.
-
#
-
# = Dynamic fixtures with ERB
-
#
-
# Some times you don't care about the content of the fixtures as much as you care about the volume.
-
# In these cases, you can mix ERB in with your YAML fixtures to create a bunch of fixtures for load
-
# testing, like:
-
#
-
# <% 1.upto(1000) do |i| %>
-
# fix_<%= i %>:
-
# id: <%= i %>
-
# name: guy_<%= 1 %>
-
# <% end %>
-
#
-
# This will create 1000 very simple fixtures.
-
#
-
# Using ERB, you can also inject dynamic values into your fixtures with inserts like
-
# <tt><%= Date.today.strftime("%Y-%m-%d") %></tt>.
-
# This is however a feature to be used with some caution. The point of fixtures are that they're
-
# stable units of predictable sample data. If you feel that you need to inject dynamic values, then
-
# perhaps you should reexamine whether your application is properly testable. Hence, dynamic values
-
# in fixtures are to be considered a code smell.
-
#
-
# Helper methods defined in a fixture will not be available in other fixtures, to prevent against
-
# unwanted inter-test dependencies. Methods used by multiple fixtures should be defined in a module
-
# that is included in <tt>ActiveRecord::FixtureSet.context_class</tt>.
-
#
-
# - define a helper method in `test_helper.rb`
-
# class FixtureFileHelpers
-
# def file_sha(path)
-
# Digest::SHA2.hexdigest(File.read(Rails.root.join('test/fixtures', path)))
-
# end
-
# end
-
# ActiveRecord::FixtureSet.context_class.send :include, FixtureFileHelpers
-
#
-
# - use the helper method in a fixture
-
# photo:
-
# name: kitten.png
-
# sha: <%= file_sha 'files/kitten.png' %>
-
#
-
# = Transactional Fixtures
-
#
-
# Test cases can use begin+rollback to isolate their changes to the database instead of having to
-
# delete+insert for every test case.
-
#
-
# class FooTest < ActiveSupport::TestCase
-
# self.use_transactional_fixtures = true
-
#
-
# test "godzilla" do
-
# assert !Foo.all.empty?
-
# Foo.destroy_all
-
# assert Foo.all.empty?
-
# end
-
#
-
# test "godzilla aftermath" do
-
# assert !Foo.all.empty?
-
# end
-
# end
-
#
-
# If you preload your test database with all fixture data (probably in the rake task) and use
-
# transactional fixtures, then you may omit all fixtures declarations in your test cases since
-
# all the data's already there and every case rolls back its changes.
-
#
-
# In order to use instantiated fixtures with preloaded data, set +self.pre_loaded_fixtures+ to
-
# true. This will provide access to fixture data for every table that has been loaded through
-
# fixtures (depending on the value of +use_instantiated_fixtures+).
-
#
-
# When *not* to use transactional fixtures:
-
#
-
# 1. You're testing whether a transaction works correctly. Nested transactions don't commit until
-
# all parent transactions commit, particularly, the fixtures transaction which is begun in setup
-
# and rolled back in teardown. Thus, you won't be able to verify
-
# the results of your transaction until Active Record supports nested transactions or savepoints (in progress).
-
# 2. Your database does not support transactions. Every Active Record database supports transactions except MySQL MyISAM.
-
# Use InnoDB, MaxDB, or NDB instead.
-
#
-
# = Advanced Fixtures
-
#
-
# Fixtures that don't specify an ID get some extra features:
-
#
-
# * Stable, autogenerated IDs
-
# * Label references for associations (belongs_to, has_one, has_many)
-
# * HABTM associations as inline lists
-
# * Autofilled timestamp columns
-
# * Fixture label interpolation
-
# * Support for YAML defaults
-
#
-
# == Stable, Autogenerated IDs
-
#
-
# Here, have a monkey fixture:
-
#
-
# george:
-
# id: 1
-
# name: George the Monkey
-
#
-
# reginald:
-
# id: 2
-
# name: Reginald the Pirate
-
#
-
# Each of these fixtures has two unique identifiers: one for the database
-
# and one for the humans. Why don't we generate the primary key instead?
-
# Hashing each fixture's label yields a consistent ID:
-
#
-
# george: # generated id: 503576764
-
# name: George the Monkey
-
#
-
# reginald: # generated id: 324201669
-
# name: Reginald the Pirate
-
#
-
# Active Record looks at the fixture's model class, discovers the correct
-
# primary key, and generates it right before inserting the fixture
-
# into the database.
-
#
-
# The generated ID for a given label is constant, so we can discover
-
# any fixture's ID without loading anything, as long as we know the label.
-
#
-
# == Label references for associations (belongs_to, has_one, has_many)
-
#
-
# Specifying foreign keys in fixtures can be very fragile, not to
-
# mention difficult to read. Since Active Record can figure out the ID of
-
# any fixture from its label, you can specify FK's by label instead of ID.
-
#
-
# === belongs_to
-
#
-
# Let's break out some more monkeys and pirates.
-
#
-
# ### in pirates.yml
-
#
-
# reginald:
-
# id: 1
-
# name: Reginald the Pirate
-
# monkey_id: 1
-
#
-
# ### in monkeys.yml
-
#
-
# george:
-
# id: 1
-
# name: George the Monkey
-
# pirate_id: 1
-
#
-
# Add a few more monkeys and pirates and break this into multiple files,
-
# and it gets pretty hard to keep track of what's going on. Let's
-
# use labels instead of IDs:
-
#
-
# ### in pirates.yml
-
#
-
# reginald:
-
# name: Reginald the Pirate
-
# monkey: george
-
#
-
# ### in monkeys.yml
-
#
-
# george:
-
# name: George the Monkey
-
# pirate: reginald
-
#
-
# Pow! All is made clear. Active Record reflects on the fixture's model class,
-
# finds all the +belongs_to+ associations, and allows you to specify
-
# a target *label* for the *association* (monkey: george) rather than
-
# a target *id* for the *FK* (<tt>monkey_id: 1</tt>).
-
#
-
# ==== Polymorphic belongs_to
-
#
-
# Supporting polymorphic relationships is a little bit more complicated, since
-
# Active Record needs to know what type your association is pointing at. Something
-
# like this should look familiar:
-
#
-
# ### in fruit.rb
-
#
-
# belongs_to :eater, polymorphic: true
-
#
-
# ### in fruits.yml
-
#
-
# apple:
-
# id: 1
-
# name: apple
-
# eater_id: 1
-
# eater_type: Monkey
-
#
-
# Can we do better? You bet!
-
#
-
# apple:
-
# eater: george (Monkey)
-
#
-
# Just provide the polymorphic target type and Active Record will take care of the rest.
-
#
-
# === has_and_belongs_to_many
-
#
-
# Time to give our monkey some fruit.
-
#
-
# ### in monkeys.yml
-
#
-
# george:
-
# id: 1
-
# name: George the Monkey
-
#
-
# ### in fruits.yml
-
#
-
# apple:
-
# id: 1
-
# name: apple
-
#
-
# orange:
-
# id: 2
-
# name: orange
-
#
-
# grape:
-
# id: 3
-
# name: grape
-
#
-
# ### in fruits_monkeys.yml
-
#
-
# apple_george:
-
# fruit_id: 1
-
# monkey_id: 1
-
#
-
# orange_george:
-
# fruit_id: 2
-
# monkey_id: 1
-
#
-
# grape_george:
-
# fruit_id: 3
-
# monkey_id: 1
-
#
-
# Let's make the HABTM fixture go away.
-
#
-
# ### in monkeys.yml
-
#
-
# george:
-
# id: 1
-
# name: George the Monkey
-
# fruits: apple, orange, grape
-
#
-
# ### in fruits.yml
-
#
-
# apple:
-
# name: apple
-
#
-
# orange:
-
# name: orange
-
#
-
# grape:
-
# name: grape
-
#
-
# Zap! No more fruits_monkeys.yml file. We've specified the list of fruits
-
# on George's fixture, but we could've just as easily specified a list
-
# of monkeys on each fruit. As with +belongs_to+, Active Record reflects on
-
# the fixture's model class and discovers the +has_and_belongs_to_many+
-
# associations.
-
#
-
# == Autofilled Timestamp Columns
-
#
-
# If your table/model specifies any of Active Record's
-
# standard timestamp columns (+created_at+, +created_on+, +updated_at+, +updated_on+),
-
# they will automatically be set to <tt>Time.now</tt>.
-
#
-
# If you've set specific values, they'll be left alone.
-
#
-
# == Fixture label interpolation
-
#
-
# The label of the current fixture is always available as a column value:
-
#
-
# geeksomnia:
-
# name: Geeksomnia's Account
-
# subdomain: $LABEL
-
#
-
# Also, sometimes (like when porting older join table fixtures) you'll need
-
# to be able to get a hold of the identifier for a given label. ERB
-
# to the rescue:
-
#
-
# george_reginald:
-
# monkey_id: <%= ActiveRecord::FixtureSet.identify(:reginald) %>
-
# pirate_id: <%= ActiveRecord::FixtureSet.identify(:george) %>
-
#
-
# == Support for YAML defaults
-
#
-
# You probably already know how to use YAML to set and reuse defaults in
-
# your <tt>database.yml</tt> file. You can use the same technique in your fixtures:
-
#
-
# DEFAULTS: &DEFAULTS
-
# created_on: <%= 3.weeks.ago.to_s(:db) %>
-
#
-
# first:
-
# name: Smurf
-
# <<: *DEFAULTS
-
#
-
# second:
-
# name: Fraggle
-
# <<: *DEFAULTS
-
#
-
# Any fixture labeled "DEFAULTS" is safely ignored.
-
1
class FixtureSet
-
#--
-
# An instance of FixtureSet is normally stored in a single YAML file and possibly in a folder with the same name.
-
#++
-
-
1
MAX_ID = 2 ** 30 - 1
-
-
1
@@all_cached_fixtures = Hash.new { |h,k| h[k] = {} }
-
-
1
def self.default_fixture_model_name(fixture_set_name, config = ActiveRecord::Base) # :nodoc:
-
config.pluralize_table_names ?
-
fixture_set_name.singularize.camelize :
-
fixture_set_name.camelize
-
end
-
-
1
def self.default_fixture_table_name(fixture_set_name, config = ActiveRecord::Base) # :nodoc:
-
"#{ config.table_name_prefix }"\
-
"#{ fixture_set_name.tr('/', '_') }"\
-
"#{ config.table_name_suffix }".to_sym
-
end
-
-
1
def self.reset_cache
-
@@all_cached_fixtures.clear
-
end
-
-
1
def self.cache_for_connection(connection)
-
@@all_cached_fixtures[connection]
-
end
-
-
1
def self.fixture_is_cached?(connection, table_name)
-
cache_for_connection(connection)[table_name]
-
end
-
-
1
def self.cached_fixtures(connection, keys_to_fetch = nil)
-
if keys_to_fetch
-
cache_for_connection(connection).values_at(*keys_to_fetch)
-
else
-
cache_for_connection(connection).values
-
end
-
end
-
-
1
def self.cache_fixtures(connection, fixtures_map)
-
cache_for_connection(connection).update(fixtures_map)
-
end
-
-
1
def self.instantiate_fixtures(object, fixture_set, load_instances = true)
-
if load_instances
-
fixture_set.each do |fixture_name, fixture|
-
begin
-
object.instance_variable_set "@#{fixture_name}", fixture.find
-
rescue FixtureClassNotFound
-
nil
-
end
-
end
-
end
-
end
-
-
1
def self.instantiate_all_loaded_fixtures(object, load_instances = true)
-
all_loaded_fixtures.each_value do |fixture_set|
-
instantiate_fixtures(object, fixture_set, load_instances)
-
end
-
end
-
-
1
cattr_accessor :all_loaded_fixtures
-
1
self.all_loaded_fixtures = {}
-
-
1
class ClassCache
-
1
def initialize(class_names, config)
-
@class_names = class_names.stringify_keys
-
@config = config
-
-
# Remove string values that aren't constants or subclasses of AR
-
@class_names.delete_if { |k,klass|
-
unless klass.is_a? Class
-
klass = klass.safe_constantize
-
ActiveSupport::Deprecation.warn("The ability to pass in strings as a class name to `set_fixture_class` will be removed in Rails 4.2. Use the class itself instead.")
-
end
-
!insert_class(@class_names, k, klass)
-
}
-
end
-
-
1
def [](fs_name)
-
@class_names.fetch(fs_name) {
-
klass = default_fixture_model(fs_name, @config).safe_constantize
-
insert_class(@class_names, fs_name, klass)
-
}
-
end
-
-
1
private
-
-
1
def insert_class(class_names, name, klass)
-
# We only want to deal with AR objects.
-
if klass && klass < ActiveRecord::Base
-
class_names[name] = klass
-
else
-
class_names[name] = nil
-
end
-
end
-
-
1
def default_fixture_model(fs_name, config)
-
ActiveRecord::FixtureSet.default_fixture_model_name(fs_name, config)
-
end
-
end
-
-
1
def self.create_fixtures(fixtures_directory, fixture_set_names, class_names = {}, config = ActiveRecord::Base)
-
fixture_set_names = Array(fixture_set_names).map(&:to_s)
-
class_names = ClassCache.new class_names, config
-
-
# FIXME: Apparently JK uses this.
-
connection = block_given? ? yield : ActiveRecord::Base.connection
-
-
files_to_read = fixture_set_names.reject { |fs_name|
-
fixture_is_cached?(connection, fs_name)
-
}
-
-
unless files_to_read.empty?
-
connection.disable_referential_integrity do
-
fixtures_map = {}
-
-
fixture_sets = files_to_read.map do |fs_name|
-
klass = class_names[fs_name]
-
conn = klass ? klass.connection : connection
-
fixtures_map[fs_name] = new( # ActiveRecord::FixtureSet.new
-
conn,
-
fs_name,
-
klass,
-
::File.join(fixtures_directory, fs_name))
-
end
-
-
all_loaded_fixtures.update(fixtures_map)
-
-
connection.transaction(:requires_new => true) do
-
fixture_sets.each do |fs|
-
conn = fs.model_class.respond_to?(:connection) ? fs.model_class.connection : connection
-
table_rows = fs.table_rows
-
-
table_rows.keys.each do |table|
-
conn.delete "DELETE FROM #{conn.quote_table_name(table)}", 'Fixture Delete'
-
end
-
-
table_rows.each do |fixture_set_name, rows|
-
rows.each do |row|
-
conn.insert_fixture(row, fixture_set_name)
-
end
-
end
-
end
-
-
# Cap primary key sequences to max(pk).
-
if connection.respond_to?(:reset_pk_sequence!)
-
fixture_sets.each do |fs|
-
connection.reset_pk_sequence!(fs.table_name)
-
end
-
end
-
end
-
-
cache_fixtures(connection, fixtures_map)
-
end
-
end
-
cached_fixtures(connection, fixture_set_names)
-
end
-
-
# Returns a consistent, platform-independent identifier for +label+.
-
# Identifiers are positive integers less than 2^32.
-
1
def self.identify(label)
-
Zlib.crc32(label.to_s) % MAX_ID
-
end
-
-
# Superclass for the evaluation contexts used by ERB fixtures.
-
1
def self.context_class
-
@context_class ||= Class.new
-
end
-
-
1
attr_reader :table_name, :name, :fixtures, :model_class, :config
-
-
1
def initialize(connection, name, class_name, path, config = ActiveRecord::Base)
-
@name = name
-
@path = path
-
@config = config
-
@model_class = nil
-
-
if class_name.is_a?(String)
-
ActiveSupport::Deprecation.warn("The ability to pass in strings as a class name to `FixtureSet.new` will be removed in Rails 4.2. Use the class itself instead.")
-
end
-
-
if class_name.is_a?(Class) # TODO: Should be an AR::Base type class, or any?
-
@model_class = class_name
-
else
-
@model_class = class_name.safe_constantize if class_name
-
end
-
-
@connection = connection
-
-
@table_name = ( model_class.respond_to?(:table_name) ?
-
model_class.table_name :
-
self.class.default_fixture_table_name(name, config) )
-
-
@fixtures = read_fixture_files path, @model_class
-
end
-
-
1
def [](x)
-
fixtures[x]
-
end
-
-
1
def []=(k,v)
-
fixtures[k] = v
-
end
-
-
1
def each(&block)
-
fixtures.each(&block)
-
end
-
-
1
def size
-
fixtures.size
-
end
-
-
# Returns a hash of rows to be inserted. The key is the table, the value is
-
# a list of rows to insert to that table.
-
1
def table_rows
-
now = config.default_timezone == :utc ? Time.now.utc : Time.now
-
now = now.to_s(:db)
-
-
# allow a standard key to be used for doing defaults in YAML
-
fixtures.delete('DEFAULTS')
-
-
# track any join tables we need to insert later
-
rows = Hash.new { |h,table| h[table] = [] }
-
-
rows[table_name] = fixtures.map do |label, fixture|
-
row = fixture.to_hash
-
-
if model_class
-
# fill in timestamp columns if they aren't specified and the model is set to record_timestamps
-
if model_class.record_timestamps
-
timestamp_column_names.each do |c_name|
-
row[c_name] = now unless row.key?(c_name)
-
end
-
end
-
-
# interpolate the fixture label
-
row.each do |key, value|
-
row[key] = label if "$LABEL" == value
-
end
-
-
# generate a primary key if necessary
-
if has_primary_key_column? && !row.include?(primary_key_name)
-
row[primary_key_name] = ActiveRecord::FixtureSet.identify(label)
-
end
-
-
# If STI is used, find the correct subclass for association reflection
-
reflection_class =
-
if row.include?(inheritance_column_name)
-
row[inheritance_column_name].constantize rescue model_class
-
else
-
model_class
-
end
-
-
reflection_class.reflect_on_all_associations.each do |association|
-
case association.macro
-
when :belongs_to
-
# Do not replace association name with association foreign key if they are named the same
-
fk_name = (association.options[:foreign_key] || "#{association.name}_id").to_s
-
-
if association.name.to_s != fk_name && value = row.delete(association.name.to_s)
-
if association.options[:polymorphic] && value.sub!(/\s*\(([^\)]*)\)\s*$/, "")
-
# support polymorphic belongs_to as "label (Type)"
-
row[association.foreign_type] = $1
-
end
-
-
row[fk_name] = ActiveRecord::FixtureSet.identify(value)
-
end
-
when :has_many
-
if association.options[:through]
-
add_join_records(rows, row, HasManyThroughProxy.new(association))
-
end
-
end
-
end
-
end
-
-
row
-
end
-
rows
-
end
-
-
1
class ReflectionProxy # :nodoc:
-
1
def initialize(association)
-
@association = association
-
end
-
-
1
def join_table
-
@association.join_table
-
end
-
-
1
def name
-
@association.name
-
end
-
end
-
-
1
class HasManyThroughProxy < ReflectionProxy # :nodoc:
-
1
def rhs_key
-
@association.foreign_key
-
end
-
-
1
def lhs_key
-
@association.through_reflection.foreign_key
-
end
-
end
-
-
1
private
-
1
def primary_key_name
-
@primary_key_name ||= model_class && model_class.primary_key
-
end
-
-
1
def add_join_records(rows, row, association)
-
# This is the case when the join table has no fixtures file
-
if (targets = row.delete(association.name.to_s))
-
table_name = association.join_table
-
lhs_key = association.lhs_key
-
rhs_key = association.rhs_key
-
-
targets = targets.is_a?(Array) ? targets : targets.split(/\s*,\s*/)
-
rows[table_name].concat targets.map { |target|
-
{ lhs_key => row[primary_key_name],
-
rhs_key => ActiveRecord::FixtureSet.identify(target) }
-
}
-
end
-
end
-
-
1
def has_primary_key_column?
-
@has_primary_key_column ||= primary_key_name &&
-
model_class.columns.any? { |c| c.name == primary_key_name }
-
end
-
-
1
def timestamp_column_names
-
@timestamp_column_names ||=
-
%w(created_at created_on updated_at updated_on) & column_names
-
end
-
-
1
def inheritance_column_name
-
@inheritance_column_name ||= model_class && model_class.inheritance_column
-
end
-
-
1
def column_names
-
@column_names ||= @connection.columns(@table_name).collect { |c| c.name }
-
end
-
-
1
def read_fixture_files(path, model_class)
-
yaml_files = Dir["#{path}/{**,*}/*.yml"].select { |f|
-
::File.file?(f)
-
} + [yaml_file_path(path)]
-
-
yaml_files.each_with_object({}) do |file, fixtures|
-
FixtureSet::File.open(file) do |fh|
-
fh.each do |fixture_name, row|
-
fixtures[fixture_name] = ActiveRecord::Fixture.new(row, model_class)
-
end
-
end
-
end
-
end
-
-
1
def yaml_file_path(path)
-
"#{path}.yml"
-
end
-
-
end
-
-
#--
-
# Deprecate 'Fixtures' in favor of 'FixtureSet'.
-
#++
-
# :nodoc:
-
1
Fixtures = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('ActiveRecord::Fixtures', 'ActiveRecord::FixtureSet')
-
-
1
class Fixture #:nodoc:
-
1
include Enumerable
-
-
1
class FixtureError < StandardError #:nodoc:
-
end
-
-
1
class FormatError < FixtureError #:nodoc:
-
end
-
-
1
attr_reader :model_class, :fixture
-
-
1
def initialize(fixture, model_class)
-
@fixture = fixture
-
@model_class = model_class
-
end
-
-
1
def class_name
-
model_class.name if model_class
-
end
-
-
1
def each
-
fixture.each { |item| yield item }
-
end
-
-
1
def [](key)
-
fixture[key]
-
end
-
-
1
alias :to_hash :fixture
-
-
1
def find
-
if model_class
-
model_class.find(fixture[model_class.primary_key])
-
else
-
raise FixtureClassNotFound, "No class attached to find."
-
end
-
end
-
end
-
end
-
-
1
module ActiveRecord
-
1
module TestFixtures
-
1
extend ActiveSupport::Concern
-
-
1
def before_setup
-
setup_fixtures
-
super
-
end
-
-
1
def after_teardown
-
super
-
teardown_fixtures
-
end
-
-
1
included do
-
class_attribute :fixture_path, :instance_writer => false
-
class_attribute :fixture_table_names
-
class_attribute :fixture_class_names
-
class_attribute :use_transactional_fixtures
-
class_attribute :use_instantiated_fixtures # true, false, or :no_instances
-
class_attribute :pre_loaded_fixtures
-
class_attribute :config
-
-
self.fixture_table_names = []
-
self.use_transactional_fixtures = true
-
self.use_instantiated_fixtures = false
-
self.pre_loaded_fixtures = false
-
self.config = ActiveRecord::Base
-
-
self.fixture_class_names = Hash.new do |h, fixture_set_name|
-
h[fixture_set_name] = ActiveRecord::FixtureSet.default_fixture_model_name(fixture_set_name, self.config)
-
end
-
end
-
-
1
module ClassMethods
-
# Sets the model class for a fixture when the class name cannot be inferred from the fixture name.
-
#
-
# Examples:
-
#
-
# set_fixture_class some_fixture: SomeModel,
-
# 'namespaced/fixture' => Another::Model
-
#
-
# The keys must be the fixture names, that coincide with the short paths to the fixture files.
-
1
def set_fixture_class(class_names = {})
-
self.fixture_class_names = self.fixture_class_names.merge(class_names.stringify_keys)
-
end
-
-
1
def fixtures(*fixture_set_names)
-
if fixture_set_names.first == :all
-
fixture_set_names = Dir["#{fixture_path}/{**,*}/*.{yml}"]
-
fixture_set_names.map! { |f| f[(fixture_path.to_s.size + 1)..-5] }
-
else
-
fixture_set_names = fixture_set_names.flatten.map { |n| n.to_s }
-
end
-
-
self.fixture_table_names |= fixture_set_names
-
require_fixture_classes(fixture_set_names, self.config)
-
setup_fixture_accessors(fixture_set_names)
-
end
-
-
1
def try_to_load_dependency(file_name)
-
require_dependency file_name
-
rescue LoadError => e
-
# Let's hope the developer has included it
-
# Let's warn in case this is a subdependency, otherwise
-
# subdependency error messages are totally cryptic
-
if ActiveRecord::Base.logger
-
ActiveRecord::Base.logger.warn("Unable to load #{file_name}, underlying cause #{e.message} \n\n #{e.backtrace.join("\n")}")
-
end
-
end
-
-
1
def require_fixture_classes(fixture_set_names = nil, config = ActiveRecord::Base)
-
if fixture_set_names
-
fixture_set_names = fixture_set_names.map { |n| n.to_s }
-
else
-
fixture_set_names = fixture_table_names
-
end
-
-
fixture_set_names.each do |file_name|
-
file_name = file_name.singularize if config.pluralize_table_names
-
try_to_load_dependency(file_name)
-
end
-
end
-
-
1
def setup_fixture_accessors(fixture_set_names = nil)
-
fixture_set_names = Array(fixture_set_names || fixture_table_names)
-
methods = Module.new do
-
fixture_set_names.each do |fs_name|
-
fs_name = fs_name.to_s
-
accessor_name = fs_name.tr('/', '_').to_sym
-
-
define_method(accessor_name) do |*fixture_names|
-
force_reload = fixture_names.pop if fixture_names.last == true || fixture_names.last == :reload
-
-
@fixture_cache[fs_name] ||= {}
-
-
instances = fixture_names.map do |f_name|
-
f_name = f_name.to_s
-
@fixture_cache[fs_name].delete(f_name) if force_reload
-
-
if @loaded_fixtures[fs_name][f_name]
-
@fixture_cache[fs_name][f_name] ||= @loaded_fixtures[fs_name][f_name].find
-
else
-
raise StandardError, "No fixture named '#{f_name}' found for fixture set '#{fs_name}'"
-
end
-
end
-
-
instances.size == 1 ? instances.first : instances
-
end
-
private accessor_name
-
end
-
end
-
include methods
-
end
-
-
1
def uses_transaction(*methods)
-
@uses_transaction = [] unless defined?(@uses_transaction)
-
@uses_transaction.concat methods.map { |m| m.to_s }
-
end
-
-
1
def uses_transaction?(method)
-
@uses_transaction = [] unless defined?(@uses_transaction)
-
@uses_transaction.include?(method.to_s)
-
end
-
end
-
-
1
def run_in_transaction?
-
use_transactional_fixtures &&
-
!self.class.uses_transaction?(method_name)
-
end
-
-
1
def setup_fixtures(config = ActiveRecord::Base)
-
if pre_loaded_fixtures && !use_transactional_fixtures
-
raise RuntimeError, 'pre_loaded_fixtures requires use_transactional_fixtures'
-
end
-
-
@fixture_cache = {}
-
@fixture_connections = []
-
@@already_loaded_fixtures ||= {}
-
-
# Load fixtures once and begin transaction.
-
if run_in_transaction?
-
if @@already_loaded_fixtures[self.class]
-
@loaded_fixtures = @@already_loaded_fixtures[self.class]
-
else
-
@loaded_fixtures = load_fixtures(config)
-
@@already_loaded_fixtures[self.class] = @loaded_fixtures
-
end
-
@fixture_connections = enlist_fixture_connections
-
@fixture_connections.each do |connection|
-
connection.begin_transaction joinable: false
-
end
-
# Load fixtures for every test.
-
else
-
ActiveRecord::FixtureSet.reset_cache
-
@@already_loaded_fixtures[self.class] = nil
-
@loaded_fixtures = load_fixtures(config)
-
end
-
-
# Instantiate fixtures for every test if requested.
-
instantiate_fixtures(config) if use_instantiated_fixtures
-
end
-
-
1
def teardown_fixtures
-
# Rollback changes if a transaction is active.
-
if run_in_transaction?
-
@fixture_connections.each do |connection|
-
connection.rollback_transaction if connection.transaction_open?
-
end
-
@fixture_connections.clear
-
else
-
ActiveRecord::FixtureSet.reset_cache
-
end
-
-
ActiveRecord::Base.clear_active_connections!
-
end
-
-
1
def enlist_fixture_connections
-
ActiveRecord::Base.connection_handler.connection_pool_list.map(&:connection)
-
end
-
-
1
private
-
1
def load_fixtures(config)
-
fixtures = ActiveRecord::FixtureSet.create_fixtures(fixture_path, fixture_table_names, fixture_class_names, config)
-
Hash[fixtures.map { |f| [f.name, f] }]
-
end
-
-
# for pre_loaded_fixtures, only require the classes once. huge speed improvement
-
1
@@required_fixture_classes = false
-
-
1
def instantiate_fixtures(config)
-
if pre_loaded_fixtures
-
raise RuntimeError, 'Load fixtures before instantiating them.' if ActiveRecord::FixtureSet.all_loaded_fixtures.empty?
-
unless @@required_fixture_classes
-
self.class.require_fixture_classes ActiveRecord::FixtureSet.all_loaded_fixtures.keys, config
-
@@required_fixture_classes = true
-
end
-
ActiveRecord::FixtureSet.instantiate_all_loaded_fixtures(self, load_instances?)
-
else
-
raise RuntimeError, 'Load fixtures before instantiating them.' if @loaded_fixtures.nil?
-
@loaded_fixtures.each_value do |fixture_set|
-
ActiveRecord::FixtureSet.instantiate_fixtures(self, fixture_set, load_instances?)
-
end
-
end
-
end
-
-
1
def load_instances?
-
use_instantiated_fixtures != :no_instances
-
end
-
end
-
end
-
-
1
class ActiveRecord::FixtureSet::RenderContext # :nodoc:
-
1
def self.create_subclass
-
Class.new ActiveRecord::FixtureSet.context_class do
-
def get_binding
-
binding()
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
# Returns the version of the currently loaded ActiveRecord as a <tt>Gem::Version</tt>
-
1
def self.gem_version
-
Gem::Version.new VERSION::STRING
-
end
-
-
1
module VERSION
-
1
MAJOR = 4
-
1
MINOR = 1
-
1
TINY = 0
-
1
PRE = nil
-
-
1
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
-
end
-
end
-
1
require 'active_support/core_ext/hash/indifferent_access'
-
-
1
module ActiveRecord
-
1
module Inheritance
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
# Determines whether to store the full constant name including namespace when using STI.
-
1
class_attribute :store_full_sti_class, instance_writer: false
-
1
self.store_full_sti_class = true
-
end
-
-
1
module ClassMethods
-
# Determines if one of the attributes passed in is the inheritance column,
-
# and if the inheritance column is attr accessible, it initializes an
-
# instance of the given subclass instead of the base class.
-
1
def new(*args, &block)
-
if abstract_class? || self == Base
-
raise NotImplementedError, "#{self} is an abstract class and cannot be instantiated."
-
end
-
-
attrs = args.first
-
if subclass_from_attributes?(attrs)
-
subclass = subclass_from_attributes(attrs)
-
end
-
-
if subclass
-
subclass.new(*args, &block)
-
else
-
super
-
end
-
end
-
-
# Returns +true+ if this does not need STI type condition. Returns
-
# +false+ if STI type condition needs to be applied.
-
1
def descends_from_active_record?
-
if self == Base
-
false
-
elsif superclass.abstract_class?
-
superclass.descends_from_active_record?
-
else
-
superclass == Base || !columns_hash.include?(inheritance_column)
-
end
-
end
-
-
1
def finder_needs_type_condition? #:nodoc:
-
# This is like this because benchmarking justifies the strange :false stuff
-
:true == (@finder_needs_type_condition ||= descends_from_active_record? ? :false : :true)
-
end
-
-
1
def symbolized_base_class
-
ActiveSupport::Deprecation.warn("ActiveRecord::Base.symbolized_base_class is deprecated and will be removed without replacement.")
-
@symbolized_base_class ||= base_class.to_s.to_sym
-
end
-
-
1
def symbolized_sti_name
-
ActiveSupport::Deprecation.warn("ActiveRecord::Base.symbolized_sti_name is deprecated and will be removed without replacement.")
-
@symbolized_sti_name ||= sti_name.present? ? sti_name.to_sym : symbolized_base_class
-
end
-
-
# Returns the class descending directly from ActiveRecord::Base, or
-
# an abstract class, if any, in the inheritance hierarchy.
-
#
-
# If A extends AR::Base, A.base_class will return A. If B descends from A
-
# through some arbitrarily deep hierarchy, B.base_class will return A.
-
#
-
# If B < A and C < B and if A is an abstract_class then both B.base_class
-
# and C.base_class would return B as the answer since A is an abstract_class.
-
1
def base_class
-
unless self < Base
-
raise ActiveRecordError, "#{name} doesn't belong in a hierarchy descending from ActiveRecord"
-
end
-
-
if superclass == Base || superclass.abstract_class?
-
self
-
else
-
superclass.base_class
-
end
-
end
-
-
# Set this to true if this is an abstract class (see <tt>abstract_class?</tt>).
-
# If you are using inheritance with ActiveRecord and don't want child classes
-
# to utilize the implied STI table name of the parent class, this will need to be true.
-
# For example, given the following:
-
#
-
# class SuperClass < ActiveRecord::Base
-
# self.abstract_class = true
-
# end
-
# class Child < SuperClass
-
# self.table_name = 'the_table_i_really_want'
-
# end
-
#
-
#
-
# <tt>self.abstract_class = true</tt> is required to make <tt>Child<.find,.create, or any Arel method></tt> use <tt>the_table_i_really_want</tt> instead of a table called <tt>super_classes</tt>
-
#
-
1
attr_accessor :abstract_class
-
-
# Returns whether this class is an abstract class or not.
-
1
def abstract_class?
-
defined?(@abstract_class) && @abstract_class == true
-
end
-
-
1
def sti_name
-
store_full_sti_class ? name : name.demodulize
-
end
-
-
1
protected
-
-
# Returns the class type of the record using the current module as a prefix. So descendants of
-
# MyApp::Business::Account would appear as MyApp::Business::AccountSubclass.
-
1
def compute_type(type_name)
-
if type_name.match(/^::/)
-
# If the type is prefixed with a scope operator then we assume that
-
# the type_name is an absolute reference.
-
ActiveSupport::Dependencies.constantize(type_name)
-
else
-
# Build a list of candidates to search for
-
candidates = []
-
name.scan(/::|$/) { candidates.unshift "#{$`}::#{type_name}" }
-
candidates << type_name
-
-
candidates.each do |candidate|
-
begin
-
constant = ActiveSupport::Dependencies.constantize(candidate)
-
return constant if candidate == constant.to_s
-
# We don't want to swallow NoMethodError < NameError errors
-
rescue NoMethodError
-
raise
-
rescue NameError
-
end
-
end
-
-
raise NameError.new("uninitialized constant #{candidates.first}", candidates.first)
-
end
-
end
-
-
1
private
-
-
# Called by +instantiate+ to decide which class to use for a new
-
# record instance. For single-table inheritance, we check the record
-
# for a +type+ column and return the corresponding class.
-
1
def discriminate_class_for_record(record)
-
if using_single_table_inheritance?(record)
-
find_sti_class(record[inheritance_column])
-
else
-
super
-
end
-
end
-
-
1
def using_single_table_inheritance?(record)
-
record[inheritance_column].present? && columns_hash.include?(inheritance_column)
-
end
-
-
1
def find_sti_class(type_name)
-
if store_full_sti_class
-
ActiveSupport::Dependencies.constantize(type_name)
-
else
-
compute_type(type_name)
-
end
-
rescue NameError
-
raise SubclassNotFound,
-
"The single-table inheritance mechanism failed to locate the subclass: '#{type_name}'. " +
-
"This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " +
-
"Please rename this column if you didn't intend it to be used for storing the inheritance class " +
-
"or overwrite #{name}.inheritance_column to use another column for that information."
-
end
-
-
1
def type_condition(table = arel_table)
-
sti_column = table[inheritance_column]
-
sti_names = ([self] + descendants).map { |model| model.sti_name }
-
-
sti_column.in(sti_names)
-
end
-
-
# Detect the subclass from the inheritance column of attrs. If the inheritance column value
-
# is not self or a valid subclass, raises ActiveRecord::SubclassNotFound
-
# If this is a StrongParameters hash, and access to inheritance_column is not permitted,
-
# this will ignore the inheritance column and return nil
-
1
def subclass_from_attributes?(attrs)
-
columns_hash.include?(inheritance_column) && attrs.is_a?(Hash)
-
end
-
-
1
def subclass_from_attributes(attrs)
-
subclass_name = attrs.with_indifferent_access[inheritance_column]
-
-
if subclass_name.present? && subclass_name != self.name
-
subclass = subclass_name.safe_constantize
-
-
unless descendants.include?(subclass)
-
raise ActiveRecord::SubclassNotFound.new("Invalid single-table inheritance type: #{subclass_name} is not a subclass of #{name}")
-
end
-
-
subclass
-
end
-
end
-
end
-
-
1
def initialize_dup(other)
-
super
-
ensure_proper_type
-
end
-
-
1
private
-
-
1
def initialize_internals_callback
-
super
-
ensure_proper_type
-
end
-
-
# Sets the attribute used for single table inheritance to this class name if this is not the
-
# ActiveRecord::Base descendant.
-
# Considering the hierarchy Reply < Message < ActiveRecord::Base, this makes it possible to
-
# do Reply.new without having to set <tt>Reply[Reply.inheritance_column] = "Reply"</tt> yourself.
-
# No such attribute would be set for objects of the Message class in that example.
-
1
def ensure_proper_type
-
klass = self.class
-
if klass.finder_needs_type_condition?
-
write_attribute(klass.inheritance_column, klass.sti_name)
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/string/filters'
-
-
1
module ActiveRecord
-
1
module Integration
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
##
-
# :singleton-method:
-
# Indicates the format used to generate the timestamp in the cache key.
-
# Accepts any of the symbols in <tt>Time::DATE_FORMATS</tt>.
-
#
-
# This is +:nsec+, by default.
-
1
class_attribute :cache_timestamp_format, :instance_writer => false
-
1
self.cache_timestamp_format = :nsec
-
end
-
-
# Returns a String, which Action Pack uses for constructing an URL to this
-
# object. The default implementation returns this record's id as a String,
-
# or nil if this record's unsaved.
-
#
-
# For example, suppose that you have a User model, and that you have a
-
# <tt>resources :users</tt> route. Normally, +user_path+ will
-
# construct a path with the user object's 'id' in it:
-
#
-
# user = User.find_by(name: 'Phusion')
-
# user_path(user) # => "/users/1"
-
#
-
# You can override +to_param+ in your model to make +user_path+ construct
-
# a path using the user's name instead of the user's id:
-
#
-
# class User < ActiveRecord::Base
-
# def to_param # overridden
-
# name
-
# end
-
# end
-
#
-
# user = User.find_by(name: 'Phusion')
-
# user_path(user) # => "/users/Phusion"
-
1
def to_param
-
# We can't use alias_method here, because method 'id' optimizes itself on the fly.
-
id && id.to_s # Be sure to stringify the id for routes
-
end
-
-
# Returns a cache key that can be used to identify this record.
-
#
-
# Product.new.cache_key # => "products/new"
-
# Product.find(5).cache_key # => "products/5" (updated_at not available)
-
# Person.find(5).cache_key # => "people/5-20071224150000" (updated_at available)
-
#
-
# You can also pass a list of named timestamps, and the newest in the list will be
-
# used to generate the key:
-
#
-
# Person.find(5).cache_key(:updated_at, :last_reviewed_at)
-
1
def cache_key(*timestamp_names)
-
case
-
when new_record?
-
"#{self.class.model_name.cache_key}/new"
-
when timestamp_names.any?
-
timestamp = max_updated_column_timestamp(timestamp_names)
-
timestamp = timestamp.utc.to_s(cache_timestamp_format)
-
"#{self.class.model_name.cache_key}/#{id}-#{timestamp}"
-
when timestamp = max_updated_column_timestamp
-
timestamp = timestamp.utc.to_s(cache_timestamp_format)
-
"#{self.class.model_name.cache_key}/#{id}-#{timestamp}"
-
else
-
"#{self.class.model_name.cache_key}/#{id}"
-
end
-
end
-
-
1
module ClassMethods
-
# Defines your model's +to_param+ method to generate "pretty" URLs
-
# using +method_name+, which can be any attribute or method that
-
# responds to +to_s+.
-
#
-
# class User < ActiveRecord::Base
-
# to_param :name
-
# end
-
#
-
# user = User.find_by(name: 'Fancy Pants')
-
# user.id # => 123
-
# user_path(user) # => "/users/123-fancy-pants"
-
#
-
# Values longer than 20 characters will be truncated. The value
-
# is truncated word by word.
-
#
-
# user = User.find_by(name: 'David HeinemeierHansson')
-
# user.id # => 125
-
# user_path(user) # => "/users/125-david"
-
#
-
# Because the generated param begins with the record's +id+, it is
-
# suitable for passing to +find+. In a controller, for example:
-
#
-
# params[:id] # => "123-fancy-pants"
-
# User.find(params[:id]).id # => 123
-
1
def to_param(method_name = nil)
-
if method_name.nil?
-
super()
-
else
-
define_method :to_param do
-
if (default = super()) &&
-
(result = send(method_name).to_s).present? &&
-
(param = result.squish.truncate(20, separator: /\s/, omission: nil).parameterize).present?
-
"#{default}-#{param}"
-
else
-
default
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Locking
-
# == What is Optimistic Locking
-
#
-
# Optimistic locking allows multiple users to access the same record for edits, and assumes a minimum of
-
# conflicts with the data. It does this by checking whether another process has made changes to a record since
-
# it was opened, an <tt>ActiveRecord::StaleObjectError</tt> exception is thrown if that has occurred
-
# and the update is ignored.
-
#
-
# Check out <tt>ActiveRecord::Locking::Pessimistic</tt> for an alternative.
-
#
-
# == Usage
-
#
-
# Active Records support optimistic locking if the field +lock_version+ is present. Each update to the
-
# record increments the +lock_version+ column and the locking facilities ensure that records instantiated twice
-
# will let the last one saved raise a +StaleObjectError+ if the first was also updated. Example:
-
#
-
# p1 = Person.find(1)
-
# p2 = Person.find(1)
-
#
-
# p1.first_name = "Michael"
-
# p1.save
-
#
-
# p2.first_name = "should fail"
-
# p2.save # Raises a ActiveRecord::StaleObjectError
-
#
-
# Optimistic locking will also check for stale data when objects are destroyed. Example:
-
#
-
# p1 = Person.find(1)
-
# p2 = Person.find(1)
-
#
-
# p1.first_name = "Michael"
-
# p1.save
-
#
-
# p2.destroy # Raises a ActiveRecord::StaleObjectError
-
#
-
# You're then responsible for dealing with the conflict by rescuing the exception and either rolling back, merging,
-
# or otherwise apply the business logic needed to resolve the conflict.
-
#
-
# This locking mechanism will function inside a single Ruby process. To make it work across all
-
# web requests, the recommended approach is to add +lock_version+ as a hidden field to your form.
-
#
-
# This behavior can be turned off by setting <tt>ActiveRecord::Base.lock_optimistically = false</tt>.
-
# To override the name of the +lock_version+ column, set the <tt>locking_column</tt> class attribute:
-
#
-
# class Person < ActiveRecord::Base
-
# self.locking_column = :lock_person
-
# end
-
#
-
1
module Optimistic
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
class_attribute :lock_optimistically, instance_writer: false
-
1
self.lock_optimistically = true
-
end
-
-
1
def locking_enabled? #:nodoc:
-
self.class.locking_enabled?
-
end
-
-
1
private
-
1
def increment_lock
-
lock_col = self.class.locking_column
-
previous_lock_value = send(lock_col).to_i
-
send(lock_col + '=', previous_lock_value + 1)
-
end
-
-
1
def update_record(attribute_names = @attributes.keys) #:nodoc:
-
return super unless locking_enabled?
-
return 0 if attribute_names.empty?
-
-
lock_col = self.class.locking_column
-
previous_lock_value = send(lock_col).to_i
-
increment_lock
-
-
attribute_names += [lock_col]
-
attribute_names.uniq!
-
-
begin
-
relation = self.class.unscoped
-
-
stmt = relation.where(
-
relation.table[self.class.primary_key].eq(id).and(
-
relation.table[lock_col].eq(self.class.quote_value(previous_lock_value, column_for_attribute(lock_col)))
-
)
-
).arel.compile_update(
-
arel_attributes_with_values_for_update(attribute_names),
-
self.class.primary_key
-
)
-
-
affected_rows = self.class.connection.update stmt
-
-
unless affected_rows == 1
-
raise ActiveRecord::StaleObjectError.new(self, "update")
-
end
-
-
affected_rows
-
-
# If something went wrong, revert the version.
-
rescue Exception
-
send(lock_col + '=', previous_lock_value)
-
raise
-
end
-
end
-
-
1
def destroy_row
-
affected_rows = super
-
-
if locking_enabled? && affected_rows != 1
-
raise ActiveRecord::StaleObjectError.new(self, "destroy")
-
end
-
-
affected_rows
-
end
-
-
1
def relation_for_destroy
-
relation = super
-
-
if locking_enabled?
-
column_name = self.class.locking_column
-
column = self.class.columns_hash[column_name]
-
substitute = self.class.connection.substitute_at(column, relation.bind_values.length)
-
-
relation = relation.where(self.class.arel_table[column_name].eq(substitute))
-
relation.bind_values << [column, self[column_name].to_i]
-
end
-
-
relation
-
end
-
-
1
module ClassMethods
-
1
DEFAULT_LOCKING_COLUMN = 'lock_version'
-
-
# Returns true if the +lock_optimistically+ flag is set to true
-
# (which it is, by default) and the table includes the
-
# +locking_column+ column (defaults to +lock_version+).
-
1
def locking_enabled?
-
lock_optimistically && columns_hash[locking_column]
-
end
-
-
# Set the column to use for optimistic locking. Defaults to +lock_version+.
-
1
def locking_column=(value)
-
@column_defaults = nil
-
@locking_column = value.to_s
-
end
-
-
# The version column used for optimistic locking. Defaults to +lock_version+.
-
1
def locking_column
-
reset_locking_column unless defined?(@locking_column)
-
@locking_column
-
end
-
-
# Quote the column name used for optimistic locking.
-
1
def quoted_locking_column
-
ActiveSupport::Deprecation.warn "ActiveRecord::Base.quoted_locking_column is deprecated and will be removed in Rails 4.2 or later."
-
connection.quote_column_name(locking_column)
-
end
-
-
# Reset the column used for optimistic locking back to the +lock_version+ default.
-
1
def reset_locking_column
-
self.locking_column = DEFAULT_LOCKING_COLUMN
-
end
-
-
# Make sure the lock version column gets updated when counters are
-
# updated.
-
1
def update_counters(id, counters)
-
counters = counters.merge(locking_column => 1) if locking_enabled?
-
super
-
end
-
-
1
def column_defaults
-
@column_defaults ||= begin
-
defaults = super
-
-
if defaults.key?(locking_column) && lock_optimistically
-
defaults[locking_column] ||= 0
-
end
-
-
defaults
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Locking
-
# Locking::Pessimistic provides support for row-level locking using
-
# SELECT ... FOR UPDATE and other lock types.
-
#
-
# Chain <tt>ActiveRecord::Base#find</tt> to <tt>ActiveRecord::QueryMethods#lock</tt> to obtain an exclusive
-
# lock on the selected rows:
-
# # select * from accounts where id=1 for update
-
# Account.lock.find(1)
-
#
-
# Call <tt>lock('some locking clause')</tt> to use a database-specific locking clause
-
# of your own such as 'LOCK IN SHARE MODE' or 'FOR UPDATE NOWAIT'. Example:
-
#
-
# Account.transaction do
-
# # select * from accounts where name = 'shugo' limit 1 for update
-
# shugo = Account.where("name = 'shugo'").lock(true).first
-
# yuko = Account.where("name = 'yuko'").lock(true).first
-
# shugo.balance -= 100
-
# shugo.save!
-
# yuko.balance += 100
-
# yuko.save!
-
# end
-
#
-
# You can also use <tt>ActiveRecord::Base#lock!</tt> method to lock one record by id.
-
# This may be better if you don't need to lock every row. Example:
-
#
-
# Account.transaction do
-
# # select * from accounts where ...
-
# accounts = Account.where(...)
-
# account1 = accounts.detect { |account| ... }
-
# account2 = accounts.detect { |account| ... }
-
# # select * from accounts where id=? for update
-
# account1.lock!
-
# account2.lock!
-
# account1.balance -= 100
-
# account1.save!
-
# account2.balance += 100
-
# account2.save!
-
# end
-
#
-
# You can start a transaction and acquire the lock in one go by calling
-
# <tt>with_lock</tt> with a block. The block is called from within
-
# a transaction, the object is already locked. Example:
-
#
-
# account = Account.first
-
# account.with_lock do
-
# # This block is called within a transaction,
-
# # account is already locked.
-
# account.balance -= 100
-
# account.save!
-
# end
-
#
-
# Database-specific information on row locking:
-
# MySQL: http://dev.mysql.com/doc/refman/5.1/en/innodb-locking-reads.html
-
# PostgreSQL: http://www.postgresql.org/docs/current/interactive/sql-select.html#SQL-FOR-UPDATE-SHARE
-
1
module Pessimistic
-
# Obtain a row lock on this record. Reloads the record to obtain the requested
-
# lock. Pass an SQL locking clause to append the end of the SELECT statement
-
# or pass true for "FOR UPDATE" (the default, an exclusive row lock). Returns
-
# the locked record.
-
1
def lock!(lock = true)
-
reload(:lock => lock) if persisted?
-
self
-
end
-
-
# Wraps the passed block in a transaction, locking the object
-
# before yielding. You can pass the SQL locking clause
-
# as argument (see <tt>lock!</tt>).
-
1
def with_lock(lock = true)
-
transaction do
-
lock!(lock)
-
yield
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
class LogSubscriber < ActiveSupport::LogSubscriber
-
1
IGNORE_PAYLOAD_NAMES = ["SCHEMA", "EXPLAIN"]
-
-
1
def self.runtime=(value)
-
9
ActiveRecord::RuntimeRegistry.sql_runtime = value
-
end
-
-
1
def self.runtime
-
9
ActiveRecord::RuntimeRegistry.sql_runtime ||= 0
-
end
-
-
1
def self.reset_runtime
-
rt, self.runtime = runtime, 0
-
rt
-
end
-
-
1
def initialize
-
1
super
-
1
@odd = false
-
end
-
-
1
def render_bind(column, value)
-
if column
-
if column.binary?
-
# This specifically deals with the PG adapter that casts bytea columns into a Hash.
-
value = value[:value] if value.is_a?(Hash)
-
value = "<#{value.bytesize} bytes of binary data>"
-
end
-
-
[column.name, value]
-
else
-
[nil, value]
-
end
-
end
-
-
1
def sql(event)
-
9
self.class.runtime += event.duration
-
9
return unless logger.debug?
-
-
9
payload = event.payload
-
-
9
return if IGNORE_PAYLOAD_NAMES.include?(payload[:name])
-
-
name = "#{payload[:name]} (#{event.duration.round(1)}ms)"
-
sql = payload[:sql]
-
binds = nil
-
-
unless (payload[:binds] || []).empty?
-
binds = " " + payload[:binds].map { |col,v|
-
render_bind(col, v)
-
}.inspect
-
end
-
-
if odd?
-
name = color(name, CYAN, true)
-
sql = color(sql, nil, true)
-
else
-
name = color(name, MAGENTA, true)
-
end
-
-
debug " #{name} #{sql}#{binds}"
-
end
-
-
1
def odd?
-
@odd = !@odd
-
end
-
-
1
def logger
-
27
ActiveRecord::Base.logger
-
end
-
end
-
end
-
-
1
ActiveRecord::LogSubscriber.attach_to :active_record
-
1
require "active_support/core_ext/module/attribute_accessors"
-
1
require 'set'
-
-
1
module ActiveRecord
-
1
class MigrationError < ActiveRecordError#:nodoc:
-
1
def initialize(message = nil)
-
1
message = "\n\n#{message}\n\n" if message
-
1
super
-
end
-
end
-
-
# Exception that can be raised to stop migrations from going backwards.
-
1
class IrreversibleMigration < MigrationError
-
end
-
-
1
class DuplicateMigrationVersionError < MigrationError#:nodoc:
-
1
def initialize(version)
-
super("Multiple migrations have the version number #{version}")
-
end
-
end
-
-
1
class DuplicateMigrationNameError < MigrationError#:nodoc:
-
1
def initialize(name)
-
super("Multiple migrations have the name #{name}")
-
end
-
end
-
-
1
class UnknownMigrationVersionError < MigrationError #:nodoc:
-
1
def initialize(version)
-
super("No migration with version number #{version}")
-
end
-
end
-
-
1
class IllegalMigrationNameError < MigrationError#:nodoc:
-
1
def initialize(name)
-
super("Illegal name for migration file: #{name}\n\t(only lower case letters, numbers, and '_' allowed)")
-
end
-
end
-
-
1
class PendingMigrationError < MigrationError#:nodoc:
-
1
def initialize
-
1
if defined?(Rails)
-
1
super("Migrations are pending. To resolve this issue, run:\n\n\tbin/rake db:migrate RAILS_ENV=#{::Rails.env}")
-
else
-
super("Migrations are pending. To resolve this issue, run:\n\n\tbin/rake db:migrate")
-
end
-
end
-
end
-
-
# = Active Record Migrations
-
#
-
# Migrations can manage the evolution of a schema used by several physical
-
# databases. It's a solution to the common problem of adding a field to make
-
# a new feature work in your local database, but being unsure of how to
-
# push that change to other developers and to the production server. With
-
# migrations, you can describe the transformations in self-contained classes
-
# that can be checked into version control systems and executed against
-
# another database that might be one, two, or five versions behind.
-
#
-
# Example of a simple migration:
-
#
-
# class AddSsl < ActiveRecord::Migration
-
# def up
-
# add_column :accounts, :ssl_enabled, :boolean, default: true
-
# end
-
#
-
# def down
-
# remove_column :accounts, :ssl_enabled
-
# end
-
# end
-
#
-
# This migration will add a boolean flag to the accounts table and remove it
-
# if you're backing out of the migration. It shows how all migrations have
-
# two methods +up+ and +down+ that describes the transformations
-
# required to implement or remove the migration. These methods can consist
-
# of both the migration specific methods like +add_column+ and +remove_column+,
-
# but may also contain regular Ruby code for generating data needed for the
-
# transformations.
-
#
-
# Example of a more complex migration that also needs to initialize data:
-
#
-
# class AddSystemSettings < ActiveRecord::Migration
-
# def up
-
# create_table :system_settings do |t|
-
# t.string :name
-
# t.string :label
-
# t.text :value
-
# t.string :type
-
# t.integer :position
-
# end
-
#
-
# SystemSetting.create name: 'notice',
-
# label: 'Use notice?',
-
# value: 1
-
# end
-
#
-
# def down
-
# drop_table :system_settings
-
# end
-
# end
-
#
-
# This migration first adds the +system_settings+ table, then creates the very
-
# first row in it using the Active Record model that relies on the table. It
-
# also uses the more advanced +create_table+ syntax where you can specify a
-
# complete table schema in one block call.
-
#
-
# == Available transformations
-
#
-
# * <tt>create_table(name, options)</tt>: Creates a table called +name+ and
-
# makes the table object available to a block that can then add columns to it,
-
# following the same format as +add_column+. See example above. The options hash
-
# is for fragments like "DEFAULT CHARSET=UTF-8" that are appended to the create
-
# table definition.
-
# * <tt>drop_table(name)</tt>: Drops the table called +name+.
-
# * <tt>change_table(name, options)</tt>: Allows to make column alterations to
-
# the table called +name+. It makes the table object available to a block that
-
# can then add/remove columns, indexes or foreign keys to it.
-
# * <tt>rename_table(old_name, new_name)</tt>: Renames the table called +old_name+
-
# to +new_name+.
-
# * <tt>add_column(table_name, column_name, type, options)</tt>: Adds a new column
-
# to the table called +table_name+
-
# named +column_name+ specified to be one of the following types:
-
# <tt>:string</tt>, <tt>:text</tt>, <tt>:integer</tt>, <tt>:float</tt>,
-
# <tt>:decimal</tt>, <tt>:datetime</tt>, <tt>:timestamp</tt>, <tt>:time</tt>,
-
# <tt>:date</tt>, <tt>:binary</tt>, <tt>:boolean</tt>. A default value can be
-
# specified by passing an +options+ hash like <tt>{ default: 11 }</tt>.
-
# Other options include <tt>:limit</tt> and <tt>:null</tt> (e.g.
-
# <tt>{ limit: 50, null: false }</tt>) -- see
-
# ActiveRecord::ConnectionAdapters::TableDefinition#column for details.
-
# * <tt>rename_column(table_name, column_name, new_column_name)</tt>: Renames
-
# a column but keeps the type and content.
-
# * <tt>change_column(table_name, column_name, type, options)</tt>: Changes
-
# the column to a different type using the same parameters as add_column.
-
# * <tt>remove_column(table_name, column_name, type, options)</tt>: Removes the column
-
# named +column_name+ from the table called +table_name+.
-
# * <tt>add_index(table_name, column_names, options)</tt>: Adds a new index
-
# with the name of the column. Other options include
-
# <tt>:name</tt>, <tt>:unique</tt> (e.g.
-
# <tt>{ name: 'users_name_index', unique: true }</tt>) and <tt>:order</tt>
-
# (e.g. <tt>{ order: { name: :desc } }</tt>).
-
# * <tt>remove_index(table_name, column: column_name)</tt>: Removes the index
-
# specified by +column_name+.
-
# * <tt>remove_index(table_name, name: index_name)</tt>: Removes the index
-
# specified by +index_name+.
-
#
-
# == Irreversible transformations
-
#
-
# Some transformations are destructive in a manner that cannot be reversed.
-
# Migrations of that kind should raise an <tt>ActiveRecord::IrreversibleMigration</tt>
-
# exception in their +down+ method.
-
#
-
# == Running migrations from within Rails
-
#
-
# The Rails package has several tools to help create and apply migrations.
-
#
-
# To generate a new migration, you can use
-
# rails generate migration MyNewMigration
-
#
-
# where MyNewMigration is the name of your migration. The generator will
-
# create an empty migration file <tt>timestamp_my_new_migration.rb</tt>
-
# in the <tt>db/migrate/</tt> directory where <tt>timestamp</tt> is the
-
# UTC formatted date and time that the migration was generated.
-
#
-
# You may then edit the <tt>up</tt> and <tt>down</tt> methods of
-
# MyNewMigration.
-
#
-
# There is a special syntactic shortcut to generate migrations that add fields to a table.
-
#
-
# rails generate migration add_fieldname_to_tablename fieldname:string
-
#
-
# This will generate the file <tt>timestamp_add_fieldname_to_tablename</tt>, which will look like this:
-
# class AddFieldnameToTablename < ActiveRecord::Migration
-
# def up
-
# add_column :tablenames, :fieldname, :string
-
# end
-
#
-
# def down
-
# remove_column :tablenames, :fieldname
-
# end
-
# end
-
#
-
# To run migrations against the currently configured database, use
-
# <tt>rake db:migrate</tt>. This will update the database by running all of the
-
# pending migrations, creating the <tt>schema_migrations</tt> table
-
# (see "About the schema_migrations table" section below) if missing. It will also
-
# invoke the db:schema:dump task, which will update your db/schema.rb file
-
# to match the structure of your database.
-
#
-
# To roll the database back to a previous migration version, use
-
# <tt>rake db:migrate VERSION=X</tt> where <tt>X</tt> is the version to which
-
# you wish to downgrade. If any of the migrations throw an
-
# <tt>ActiveRecord::IrreversibleMigration</tt> exception, that step will fail and you'll
-
# have some manual work to do.
-
#
-
# == Database support
-
#
-
# Migrations are currently supported in MySQL, PostgreSQL, SQLite,
-
# SQL Server, Sybase, and Oracle (all supported databases except DB2).
-
#
-
# == More examples
-
#
-
# Not all migrations change the schema. Some just fix the data:
-
#
-
# class RemoveEmptyTags < ActiveRecord::Migration
-
# def up
-
# Tag.all.each { |tag| tag.destroy if tag.pages.empty? }
-
# end
-
#
-
# def down
-
# # not much we can do to restore deleted data
-
# raise ActiveRecord::IrreversibleMigration, "Can't recover the deleted tags"
-
# end
-
# end
-
#
-
# Others remove columns when they migrate up instead of down:
-
#
-
# class RemoveUnnecessaryItemAttributes < ActiveRecord::Migration
-
# def up
-
# remove_column :items, :incomplete_items_count
-
# remove_column :items, :completed_items_count
-
# end
-
#
-
# def down
-
# add_column :items, :incomplete_items_count
-
# add_column :items, :completed_items_count
-
# end
-
# end
-
#
-
# And sometimes you need to do something in SQL not abstracted directly by migrations:
-
#
-
# class MakeJoinUnique < ActiveRecord::Migration
-
# def up
-
# execute "ALTER TABLE `pages_linked_pages` ADD UNIQUE `page_id_linked_page_id` (`page_id`,`linked_page_id`)"
-
# end
-
#
-
# def down
-
# execute "ALTER TABLE `pages_linked_pages` DROP INDEX `page_id_linked_page_id`"
-
# end
-
# end
-
#
-
# == Using a model after changing its table
-
#
-
# Sometimes you'll want to add a column in a migration and populate it
-
# immediately after. In that case, you'll need to make a call to
-
# <tt>Base#reset_column_information</tt> in order to ensure that the model has the
-
# latest column data from after the new column was added. Example:
-
#
-
# class AddPeopleSalary < ActiveRecord::Migration
-
# def up
-
# add_column :people, :salary, :integer
-
# Person.reset_column_information
-
# Person.all.each do |p|
-
# p.update_attribute :salary, SalaryCalculator.compute(p)
-
# end
-
# end
-
# end
-
#
-
# == Controlling verbosity
-
#
-
# By default, migrations will describe the actions they are taking, writing
-
# them to the console as they happen, along with benchmarks describing how
-
# long each step took.
-
#
-
# You can quiet them down by setting ActiveRecord::Migration.verbose = false.
-
#
-
# You can also insert your own messages and benchmarks by using the +say_with_time+
-
# method:
-
#
-
# def up
-
# ...
-
# say_with_time "Updating salaries..." do
-
# Person.all.each do |p|
-
# p.update_attribute :salary, SalaryCalculator.compute(p)
-
# end
-
# end
-
# ...
-
# end
-
#
-
# The phrase "Updating salaries..." would then be printed, along with the
-
# benchmark for the block when the block completes.
-
#
-
# == About the schema_migrations table
-
#
-
# Rails versions 2.0 and prior used to create a table called
-
# <tt>schema_info</tt> when using migrations. This table contained the
-
# version of the schema as of the last applied migration.
-
#
-
# Starting with Rails 2.1, the <tt>schema_info</tt> table is
-
# (automatically) replaced by the <tt>schema_migrations</tt> table, which
-
# contains the version numbers of all the migrations applied.
-
#
-
# As a result, it is now possible to add migration files that are numbered
-
# lower than the current schema version: when migrating up, those
-
# never-applied "interleaved" migrations will be automatically applied, and
-
# when migrating down, never-applied "interleaved" migrations will be skipped.
-
#
-
# == Timestamped Migrations
-
#
-
# By default, Rails generates migrations that look like:
-
#
-
# 20080717013526_your_migration_name.rb
-
#
-
# The prefix is a generation timestamp (in UTC).
-
#
-
# If you'd prefer to use numeric prefixes, you can turn timestamped migrations
-
# off by setting:
-
#
-
# config.active_record.timestamped_migrations = false
-
#
-
# In application.rb.
-
#
-
# == Reversible Migrations
-
#
-
# Starting with Rails 3.1, you will be able to define reversible migrations.
-
# Reversible migrations are migrations that know how to go +down+ for you.
-
# You simply supply the +up+ logic, and the Migration system will figure out
-
# how to execute the down commands for you.
-
#
-
# To define a reversible migration, define the +change+ method in your
-
# migration like this:
-
#
-
# class TenderloveMigration < ActiveRecord::Migration
-
# def change
-
# create_table(:horses) do |t|
-
# t.column :content, :text
-
# t.column :remind_at, :datetime
-
# end
-
# end
-
# end
-
#
-
# This migration will create the horses table for you on the way up, and
-
# automatically figure out how to drop the table on the way down.
-
#
-
# Some commands like +remove_column+ cannot be reversed. If you care to
-
# define how to move up and down in these cases, you should define the +up+
-
# and +down+ methods as before.
-
#
-
# If a command cannot be reversed, an
-
# <tt>ActiveRecord::IrreversibleMigration</tt> exception will be raised when
-
# the migration is moving down.
-
#
-
# For a list of commands that are reversible, please see
-
# <tt>ActiveRecord::Migration::CommandRecorder</tt>.
-
#
-
# == Transactional Migrations
-
#
-
# If the database adapter supports DDL transactions, all migrations will
-
# automatically be wrapped in a transaction. There are queries that you
-
# can't execute inside a transaction though, and for these situations
-
# you can turn the automatic transactions off.
-
#
-
# class ChangeEnum < ActiveRecord::Migration
-
# disable_ddl_transaction!
-
#
-
# def up
-
# execute "ALTER TYPE model_size ADD VALUE 'new_value'"
-
# end
-
# end
-
#
-
# Remember that you can still open your own transactions, even if you
-
# are in a Migration with <tt>self.disable_ddl_transaction!</tt>.
-
1
class Migration
-
1
autoload :CommandRecorder, 'active_record/migration/command_recorder'
-
-
-
# This class is used to verify that all migrations have been run before
-
# loading a web page if config.active_record.migration_error is set to :page_load
-
1
class CheckPending
-
1
def initialize(app)
-
@app = app
-
@last_check = 0
-
end
-
-
1
def call(env)
-
mtime = ActiveRecord::Migrator.last_migration.mtime.to_i
-
if @last_check < mtime
-
ActiveRecord::Migration.check_pending!
-
@last_check = mtime
-
end
-
@app.call(env)
-
end
-
end
-
-
1
class << self
-
1
attr_accessor :delegate # :nodoc:
-
1
attr_accessor :disable_ddl_transaction # :nodoc:
-
-
1
def check_pending!(connection = Base.connection)
-
1
raise ActiveRecord::PendingMigrationError if ActiveRecord::Migrator.needs_migration?(connection)
-
end
-
-
1
def load_schema_if_pending!
-
if ActiveRecord::Migrator.needs_migration?
-
ActiveRecord::Tasks::DatabaseTasks.load_schema
-
check_pending!
-
end
-
end
-
-
1
def maintain_test_schema! # :nodoc:
-
if ActiveRecord::Base.maintain_test_schema
-
suppress_messages { load_schema_if_pending! }
-
end
-
end
-
-
1
def method_missing(name, *args, &block) # :nodoc:
-
(delegate || superclass.delegate).send(name, *args, &block)
-
end
-
-
1
def migrate(direction)
-
new.migrate direction
-
end
-
-
# Disable DDL transactions for this migration.
-
1
def disable_ddl_transaction!
-
@disable_ddl_transaction = true
-
end
-
end
-
-
1
def disable_ddl_transaction # :nodoc:
-
self.class.disable_ddl_transaction
-
end
-
-
1
cattr_accessor :verbose
-
1
attr_accessor :name, :version
-
-
1
def initialize(name = self.class.name, version = nil)
-
1
@name = name
-
1
@version = version
-
1
@connection = nil
-
end
-
-
1
self.verbose = true
-
# instantiate the delegate object after initialize is defined
-
1
self.delegate = new
-
-
# Reverses the migration commands for the given block and
-
# the given migrations.
-
#
-
# The following migration will remove the table 'horses'
-
# and create the table 'apples' on the way up, and the reverse
-
# on the way down.
-
#
-
# class FixTLMigration < ActiveRecord::Migration
-
# def change
-
# revert do
-
# create_table(:horses) do |t|
-
# t.text :content
-
# t.datetime :remind_at
-
# end
-
# end
-
# create_table(:apples) do |t|
-
# t.string :variety
-
# end
-
# end
-
# end
-
#
-
# Or equivalently, if +TenderloveMigration+ is defined as in the
-
# documentation for Migration:
-
#
-
# require_relative '2012121212_tenderlove_migration'
-
#
-
# class FixupTLMigration < ActiveRecord::Migration
-
# def change
-
# revert TenderloveMigration
-
#
-
# create_table(:apples) do |t|
-
# t.string :variety
-
# end
-
# end
-
# end
-
#
-
# This command can be nested.
-
1
def revert(*migration_classes)
-
run(*migration_classes.reverse, revert: true) unless migration_classes.empty?
-
if block_given?
-
if @connection.respond_to? :revert
-
@connection.revert { yield }
-
else
-
recorder = CommandRecorder.new(@connection)
-
@connection = recorder
-
suppress_messages do
-
@connection.revert { yield }
-
end
-
@connection = recorder.delegate
-
recorder.commands.each do |cmd, args, block|
-
send(cmd, *args, &block)
-
end
-
end
-
end
-
end
-
-
1
def reverting?
-
@connection.respond_to?(:reverting) && @connection.reverting
-
end
-
-
1
class ReversibleBlockHelper < Struct.new(:reverting) # :nodoc:
-
1
def up
-
yield unless reverting
-
end
-
-
1
def down
-
yield if reverting
-
end
-
end
-
-
# Used to specify an operation that can be run in one direction or another.
-
# Call the methods +up+ and +down+ of the yielded object to run a block
-
# only in one given direction.
-
# The whole block will be called in the right order within the migration.
-
#
-
# In the following example, the looping on users will always be done
-
# when the three columns 'first_name', 'last_name' and 'full_name' exist,
-
# even when migrating down:
-
#
-
# class SplitNameMigration < ActiveRecord::Migration
-
# def change
-
# add_column :users, :first_name, :string
-
# add_column :users, :last_name, :string
-
#
-
# reversible do |dir|
-
# User.reset_column_information
-
# User.all.each do |u|
-
# dir.up { u.first_name, u.last_name = u.full_name.split(' ') }
-
# dir.down { u.full_name = "#{u.first_name} #{u.last_name}" }
-
# u.save
-
# end
-
# end
-
#
-
# revert { add_column :users, :full_name, :string }
-
# end
-
# end
-
1
def reversible
-
helper = ReversibleBlockHelper.new(reverting?)
-
execute_block{ yield helper }
-
end
-
-
# Runs the given migration classes.
-
# Last argument can specify options:
-
# - :direction (default is :up)
-
# - :revert (default is false)
-
1
def run(*migration_classes)
-
opts = migration_classes.extract_options!
-
dir = opts[:direction] || :up
-
dir = (dir == :down ? :up : :down) if opts[:revert]
-
if reverting?
-
# If in revert and going :up, say, we want to execute :down without reverting, so
-
revert { run(*migration_classes, direction: dir, revert: true) }
-
else
-
migration_classes.each do |migration_class|
-
migration_class.new.exec_migration(@connection, dir)
-
end
-
end
-
end
-
-
1
def up
-
self.class.delegate = self
-
return unless self.class.respond_to?(:up)
-
self.class.up
-
end
-
-
1
def down
-
self.class.delegate = self
-
return unless self.class.respond_to?(:down)
-
self.class.down
-
end
-
-
# Execute this migration in the named direction
-
1
def migrate(direction)
-
return unless respond_to?(direction)
-
-
case direction
-
when :up then announce "migrating"
-
when :down then announce "reverting"
-
end
-
-
time = nil
-
ActiveRecord::Base.connection_pool.with_connection do |conn|
-
time = Benchmark.measure do
-
exec_migration(conn, direction)
-
end
-
end
-
-
case direction
-
when :up then announce "migrated (%.4fs)" % time.real; write
-
when :down then announce "reverted (%.4fs)" % time.real; write
-
end
-
end
-
-
1
def exec_migration(conn, direction)
-
@connection = conn
-
if respond_to?(:change)
-
if direction == :down
-
revert { change }
-
else
-
change
-
end
-
else
-
send(direction)
-
end
-
ensure
-
@connection = nil
-
end
-
-
1
def write(text="")
-
puts(text) if verbose
-
end
-
-
1
def announce(message)
-
text = "#{version} #{name}: #{message}"
-
length = [0, 75 - text.length].max
-
write "== %s %s" % [text, "=" * length]
-
end
-
-
1
def say(message, subitem=false)
-
write "#{subitem ? " ->" : "--"} #{message}"
-
end
-
-
1
def say_with_time(message)
-
say(message)
-
result = nil
-
time = Benchmark.measure { result = yield }
-
say "%.4fs" % time.real, :subitem
-
say("#{result} rows", :subitem) if result.is_a?(Integer)
-
result
-
end
-
-
1
def suppress_messages
-
save, self.verbose = verbose, false
-
yield
-
ensure
-
self.verbose = save
-
end
-
-
1
def connection
-
@connection || ActiveRecord::Base.connection
-
end
-
-
1
def method_missing(method, *arguments, &block)
-
arg_list = arguments.map{ |a| a.inspect } * ', '
-
-
say_with_time "#{method}(#{arg_list})" do
-
unless @connection.respond_to? :revert
-
unless arguments.empty? || method == :execute
-
arguments[0] = proper_table_name(arguments.first, table_name_options)
-
arguments[1] = proper_table_name(arguments.second, table_name_options) if method == :rename_table
-
end
-
end
-
return super unless connection.respond_to?(method)
-
connection.send(method, *arguments, &block)
-
end
-
end
-
-
1
def copy(destination, sources, options = {})
-
copied = []
-
-
FileUtils.mkdir_p(destination) unless File.exist?(destination)
-
-
destination_migrations = ActiveRecord::Migrator.migrations(destination)
-
last = destination_migrations.last
-
sources.each do |scope, path|
-
source_migrations = ActiveRecord::Migrator.migrations(path)
-
-
source_migrations.each do |migration|
-
source = File.binread(migration.filename)
-
inserted_comment = "# This migration comes from #{scope} (originally #{migration.version})\n"
-
if /\A#.*\b(?:en)?coding:\s*\S+/ =~ source
-
# If we have a magic comment in the original migration,
-
# insert our comment after the first newline(end of the magic comment line)
-
# so the magic keep working.
-
# Note that magic comments must be at the first line(except sh-bang).
-
source[/\n/] = "\n#{inserted_comment}"
-
else
-
source = "#{inserted_comment}#{source}"
-
end
-
-
if duplicate = destination_migrations.detect { |m| m.name == migration.name }
-
if options[:on_skip] && duplicate.scope != scope.to_s
-
options[:on_skip].call(scope, migration)
-
end
-
next
-
end
-
-
migration.version = next_migration_number(last ? last.version + 1 : 0).to_i
-
new_path = File.join(destination, "#{migration.version}_#{migration.name.underscore}.#{scope}.rb")
-
old_path, migration.filename = migration.filename, new_path
-
last = migration
-
-
File.binwrite(migration.filename, source)
-
copied << migration
-
options[:on_copy].call(scope, migration, old_path) if options[:on_copy]
-
destination_migrations << migration
-
end
-
end
-
-
copied
-
end
-
-
# Finds the correct table name given an Active Record object.
-
# Uses the Active Record object's own table_name, or pre/suffix from the
-
# options passed in.
-
1
def proper_table_name(name, options = {})
-
if name.respond_to? :table_name
-
name.table_name
-
else
-
"#{options[:table_name_prefix]}#{name}#{options[:table_name_suffix]}"
-
end
-
end
-
-
# Determines the version number of the next migration.
-
1
def next_migration_number(number)
-
if ActiveRecord::Base.timestamped_migrations
-
[Time.now.utc.strftime("%Y%m%d%H%M%S"), "%.14d" % number].max
-
else
-
"%.3d" % number
-
end
-
end
-
-
1
def table_name_options(config = ActiveRecord::Base)
-
{
-
table_name_prefix: config.table_name_prefix,
-
table_name_suffix: config.table_name_suffix
-
}
-
end
-
-
1
private
-
1
def execute_block
-
if connection.respond_to? :execute_block
-
super # use normal delegation to record the block
-
else
-
yield
-
end
-
end
-
end
-
-
# MigrationProxy is used to defer loading of the actual migration classes
-
# until they are needed
-
1
class MigrationProxy < Struct.new(:name, :version, :filename, :scope)
-
-
1
def initialize(name, version, filename, scope)
-
19
super
-
19
@migration = nil
-
end
-
-
1
def basename
-
File.basename(filename)
-
end
-
-
1
def mtime
-
File.mtime filename
-
end
-
-
1
delegate :migrate, :announce, :write, :disable_ddl_transaction, to: :migration
-
-
1
private
-
-
1
def migration
-
@migration ||= load_migration
-
end
-
-
1
def load_migration
-
require(File.expand_path(filename))
-
name.constantize.new(name, version)
-
end
-
-
end
-
-
1
class NullMigration < MigrationProxy #:nodoc:
-
1
def initialize
-
super(nil, 0, nil, nil)
-
end
-
-
1
def mtime
-
0
-
end
-
end
-
-
1
class Migrator#:nodoc:
-
1
class << self
-
1
attr_writer :migrations_paths
-
1
alias :migrations_path= :migrations_paths=
-
-
1
def migrate(migrations_paths, target_version = nil, &block)
-
case
-
when target_version.nil?
-
up(migrations_paths, target_version, &block)
-
when current_version == 0 && target_version == 0
-
[]
-
when current_version > target_version
-
down(migrations_paths, target_version, &block)
-
else
-
up(migrations_paths, target_version, &block)
-
end
-
end
-
-
1
def rollback(migrations_paths, steps=1)
-
move(:down, migrations_paths, steps)
-
end
-
-
1
def forward(migrations_paths, steps=1)
-
move(:up, migrations_paths, steps)
-
end
-
-
1
def up(migrations_paths, target_version = nil)
-
migrations = migrations(migrations_paths)
-
migrations.select! { |m| yield m } if block_given?
-
-
self.new(:up, migrations, target_version).migrate
-
end
-
-
1
def down(migrations_paths, target_version = nil, &block)
-
migrations = migrations(migrations_paths)
-
migrations.select! { |m| yield m } if block_given?
-
-
self.new(:down, migrations, target_version).migrate
-
end
-
-
1
def run(direction, migrations_paths, target_version)
-
self.new(direction, migrations(migrations_paths), target_version).run
-
end
-
-
1
def open(migrations_paths)
-
self.new(:up, migrations(migrations_paths), nil)
-
end
-
-
1
def schema_migrations_table_name
-
1
SchemaMigration.table_name
-
end
-
-
1
def get_all_versions
-
SchemaMigration.all.map { |x| x.version.to_i }.sort
-
end
-
-
1
def current_version(connection = Base.connection)
-
1
sm_table = schema_migrations_table_name
-
1
if connection.table_exists?(sm_table)
-
get_all_versions.max || 0
-
else
-
1
0
-
end
-
end
-
-
1
def needs_migration?(connection = Base.connection)
-
1
current_version(connection) < last_version
-
end
-
-
1
def last_version
-
1
last_migration.version
-
end
-
-
1
def last_migration #:nodoc:
-
1
migrations(migrations_paths).last || NullMigration.new
-
end
-
-
1
def proper_table_name(name, options = {})
-
ActiveSupport::Deprecation.warn "ActiveRecord::Migrator.proper_table_name is deprecated and will be removed in Rails 4.2. Use the proper_table_name instance method on ActiveRecord::Migration instead"
-
options = {
-
table_name_prefix: ActiveRecord::Base.table_name_prefix,
-
table_name_suffix: ActiveRecord::Base.table_name_suffix
-
}.merge(options)
-
if name.respond_to? :table_name
-
name.table_name
-
else
-
"#{options[:table_name_prefix]}#{name}#{options[:table_name_suffix]}"
-
end
-
end
-
-
1
def migrations_paths
-
1
@migrations_paths ||= ['db/migrate']
-
# just to not break things if someone uses: migration_path = some_string
-
1
Array(@migrations_paths)
-
end
-
-
1
def migrations_path
-
migrations_paths.first
-
end
-
-
1
def migrations(paths)
-
1
paths = Array(paths)
-
-
2
files = Dir[*paths.map { |p| "#{p}/**/[0-9]*_*.rb" }]
-
-
1
migrations = files.map do |file|
-
19
version, name, scope = file.scan(/([0-9]+)_([_a-z0-9]*)\.?([_a-z0-9]*)?\.rb\z/).first
-
-
19
raise IllegalMigrationNameError.new(file) unless version
-
19
version = version.to_i
-
19
name = name.camelize
-
-
19
MigrationProxy.new(name, version, file, scope)
-
end
-
-
1
migrations.sort_by(&:version)
-
end
-
-
1
private
-
-
1
def move(direction, migrations_paths, steps)
-
migrator = self.new(direction, migrations(migrations_paths))
-
start_index = migrator.migrations.index(migrator.current_migration)
-
-
if start_index
-
finish = migrator.migrations[start_index + steps]
-
version = finish ? finish.version : 0
-
send(direction, migrations_paths, version)
-
end
-
end
-
end
-
-
1
def initialize(direction, migrations, target_version = nil)
-
raise StandardError.new("This database does not yet support migrations") unless Base.connection.supports_migrations?
-
-
@direction = direction
-
@target_version = target_version
-
@migrated_versions = nil
-
@migrations = migrations
-
-
validate(@migrations)
-
-
Base.connection.initialize_schema_migrations_table
-
end
-
-
1
def current_version
-
migrated.max || 0
-
end
-
-
1
def current_migration
-
migrations.detect { |m| m.version == current_version }
-
end
-
1
alias :current :current_migration
-
-
1
def run
-
migration = migrations.detect { |m| m.version == @target_version }
-
raise UnknownMigrationVersionError.new(@target_version) if migration.nil?
-
unless (up? && migrated.include?(migration.version.to_i)) || (down? && !migrated.include?(migration.version.to_i))
-
begin
-
execute_migration_in_transaction(migration, @direction)
-
rescue => e
-
canceled_msg = use_transaction?(migration) ? ", this migration was canceled" : ""
-
raise StandardError, "An error has occurred#{canceled_msg}:\n\n#{e}", e.backtrace
-
end
-
end
-
end
-
-
1
def migrate
-
if !target && @target_version && @target_version > 0
-
raise UnknownMigrationVersionError.new(@target_version)
-
end
-
-
runnable.each do |migration|
-
Base.logger.info "Migrating to #{migration.name} (#{migration.version})" if Base.logger
-
-
begin
-
execute_migration_in_transaction(migration, @direction)
-
rescue => e
-
canceled_msg = use_transaction?(migration) ? "this and " : ""
-
raise StandardError, "An error has occurred, #{canceled_msg}all later migrations canceled:\n\n#{e}", e.backtrace
-
end
-
end
-
end
-
-
1
def runnable
-
runnable = migrations[start..finish]
-
if up?
-
runnable.reject { |m| ran?(m) }
-
else
-
# skip the last migration if we're headed down, but not ALL the way down
-
runnable.pop if target
-
runnable.find_all { |m| ran?(m) }
-
end
-
end
-
-
1
def migrations
-
down? ? @migrations.reverse : @migrations.sort_by(&:version)
-
end
-
-
1
def pending_migrations
-
already_migrated = migrated
-
migrations.reject { |m| already_migrated.include?(m.version) }
-
end
-
-
1
def migrated
-
@migrated_versions ||= Set.new(self.class.get_all_versions)
-
end
-
-
1
private
-
1
def ran?(migration)
-
migrated.include?(migration.version.to_i)
-
end
-
-
1
def execute_migration_in_transaction(migration, direction)
-
ddl_transaction(migration) do
-
migration.migrate(direction)
-
record_version_state_after_migrating(migration.version)
-
end
-
end
-
-
1
def target
-
migrations.detect { |m| m.version == @target_version }
-
end
-
-
1
def finish
-
migrations.index(target) || migrations.size - 1
-
end
-
-
1
def start
-
up? ? 0 : (migrations.index(current) || 0)
-
end
-
-
1
def validate(migrations)
-
name ,= migrations.group_by(&:name).find { |_,v| v.length > 1 }
-
raise DuplicateMigrationNameError.new(name) if name
-
-
version ,= migrations.group_by(&:version).find { |_,v| v.length > 1 }
-
raise DuplicateMigrationVersionError.new(version) if version
-
end
-
-
1
def record_version_state_after_migrating(version)
-
if down?
-
migrated.delete(version)
-
ActiveRecord::SchemaMigration.where(:version => version.to_s).delete_all
-
else
-
migrated << version
-
ActiveRecord::SchemaMigration.create!(:version => version.to_s)
-
end
-
end
-
-
1
def up?
-
@direction == :up
-
end
-
-
1
def down?
-
@direction == :down
-
end
-
-
# Wrap the migration in a transaction only if supported by the adapter.
-
1
def ddl_transaction(migration)
-
if use_transaction?(migration)
-
Base.transaction { yield }
-
else
-
yield
-
end
-
end
-
-
1
def use_transaction?(migration)
-
!migration.disable_ddl_transaction && Base.connection.supports_ddl_transactions?
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
class Migration
-
1
module JoinTable #:nodoc:
-
1
private
-
-
1
def find_join_table_name(table_1, table_2, options = {})
-
options.delete(:table_name) || join_table_name(table_1, table_2)
-
end
-
-
1
def join_table_name(table_1, table_2)
-
[table_1.to_s, table_2.to_s].sort.join("_").to_sym
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ModelSchema
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
##
-
# :singleton-method:
-
# Accessor for the prefix type that will be prepended to every primary key column name.
-
# The options are :table_name and :table_name_with_underscore. If the first is specified,
-
# the Product class will look for "productid" instead of "id" as the primary column. If the
-
# latter is specified, the Product class will look for "product_id" instead of "id". Remember
-
# that this is a global setting for all Active Records.
-
1
mattr_accessor :primary_key_prefix_type, instance_writer: false
-
-
##
-
# :singleton-method:
-
# Accessor for the name of the prefix string to prepend to every table name. So if set
-
# to "basecamp_", all table names will be named like "basecamp_projects", "basecamp_people",
-
# etc. This is a convenient way of creating a namespace for tables in a shared database.
-
# By default, the prefix is the empty string.
-
#
-
# If you are organising your models within modules you can add a prefix to the models within
-
# a namespace by defining a singleton method in the parent module called table_name_prefix which
-
# returns your chosen prefix.
-
1
class_attribute :table_name_prefix, instance_writer: false
-
1
self.table_name_prefix = ""
-
-
##
-
# :singleton-method:
-
# Works like +table_name_prefix+, but appends instead of prepends (set to "_basecamp" gives "projects_basecamp",
-
# "people_basecamp"). By default, the suffix is the empty string.
-
1
class_attribute :table_name_suffix, instance_writer: false
-
1
self.table_name_suffix = ""
-
-
##
-
# :singleton-method:
-
# Accessor for the name of the schema migrations table. By default, the value is "schema_migrations"
-
1
class_attribute :schema_migrations_table_name, instance_accessor: false
-
1
self.schema_migrations_table_name = "schema_migrations"
-
-
##
-
# :singleton-method:
-
# Indicates whether table names should be the pluralized versions of the corresponding class names.
-
# If true, the default table name for a Product class will be +products+. If false, it would just be +product+.
-
# See table_name for the full rules on table/class naming. This is true, by default.
-
1
class_attribute :pluralize_table_names, instance_writer: false
-
1
self.pluralize_table_names = true
-
-
1
self.inheritance_column = 'type'
-
end
-
-
1
module ClassMethods
-
# Guesses the table name (in forced lower-case) based on the name of the class in the
-
# inheritance hierarchy descending directly from ActiveRecord::Base. So if the hierarchy
-
# looks like: Reply < Message < ActiveRecord::Base, then Message is used
-
# to guess the table name even when called on Reply. The rules used to do the guess
-
# are handled by the Inflector class in Active Support, which knows almost all common
-
# English inflections. You can add new inflections in config/initializers/inflections.rb.
-
#
-
# Nested classes are given table names prefixed by the singular form of
-
# the parent's table name. Enclosing modules are not considered.
-
#
-
# ==== Examples
-
#
-
# class Invoice < ActiveRecord::Base
-
# end
-
#
-
# file class table_name
-
# invoice.rb Invoice invoices
-
#
-
# class Invoice < ActiveRecord::Base
-
# class Lineitem < ActiveRecord::Base
-
# end
-
# end
-
#
-
# file class table_name
-
# invoice.rb Invoice::Lineitem invoice_lineitems
-
#
-
# module Invoice
-
# class Lineitem < ActiveRecord::Base
-
# end
-
# end
-
#
-
# file class table_name
-
# invoice/lineitem.rb Invoice::Lineitem lineitems
-
#
-
# Additionally, the class-level +table_name_prefix+ is prepended and the
-
# +table_name_suffix+ is appended. So if you have "myapp_" as a prefix,
-
# the table name guess for an Invoice class becomes "myapp_invoices".
-
# Invoice::Lineitem becomes "myapp_invoice_lineitems".
-
#
-
# You can also set your own table name explicitly:
-
#
-
# class Mouse < ActiveRecord::Base
-
# self.table_name = "mice"
-
# end
-
#
-
# Alternatively, you can override the table_name method to define your
-
# own computation. (Possibly using <tt>super</tt> to manipulate the default
-
# table name.) Example:
-
#
-
# class Post < ActiveRecord::Base
-
# def self.table_name
-
# "special_" + super
-
# end
-
# end
-
# Post.table_name # => "special_posts"
-
1
def table_name
-
reset_table_name unless defined?(@table_name)
-
@table_name
-
end
-
-
# Sets the table name explicitly. Example:
-
#
-
# class Project < ActiveRecord::Base
-
# self.table_name = "project"
-
# end
-
#
-
# You can also just define your own <tt>self.table_name</tt> method; see
-
# the documentation for ActiveRecord::Base#table_name.
-
1
def table_name=(value)
-
value = value && value.to_s
-
-
if defined?(@table_name)
-
return if value == @table_name
-
reset_column_information if connected?
-
end
-
-
@table_name = value
-
@quoted_table_name = nil
-
@arel_table = nil
-
@sequence_name = nil unless defined?(@explicit_sequence_name) && @explicit_sequence_name
-
@relation = Relation.create(self, arel_table)
-
end
-
-
# Returns a quoted version of the table name, used to construct SQL statements.
-
1
def quoted_table_name
-
@quoted_table_name ||= connection.quote_table_name(table_name)
-
end
-
-
# Computes the table name, (re)sets it internally, and returns it.
-
1
def reset_table_name #:nodoc:
-
self.table_name = if abstract_class?
-
superclass == Base ? nil : superclass.table_name
-
elsif superclass.abstract_class?
-
superclass.table_name || compute_table_name
-
else
-
compute_table_name
-
end
-
end
-
-
1
def full_table_name_prefix #:nodoc:
-
(parents.detect{ |p| p.respond_to?(:table_name_prefix) } || self).table_name_prefix
-
end
-
-
# Defines the name of the table column which will store the class name on single-table
-
# inheritance situations.
-
#
-
# The default inheritance column name is +type+, which means it's a
-
# reserved word inside Active Record. To be able to use single-table
-
# inheritance with another column name, or to use the column +type+ in
-
# your own model for something else, you can set +inheritance_column+:
-
#
-
# self.inheritance_column = 'zoink'
-
1
def inheritance_column
-
(@inheritance_column ||= nil) || superclass.inheritance_column
-
end
-
-
# Sets the value of inheritance_column
-
1
def inheritance_column=(value)
-
1
@inheritance_column = value.to_s
-
1
@explicit_inheritance_column = true
-
end
-
-
1
def sequence_name
-
if base_class == self
-
@sequence_name ||= reset_sequence_name
-
else
-
(@sequence_name ||= nil) || base_class.sequence_name
-
end
-
end
-
-
1
def reset_sequence_name #:nodoc:
-
@explicit_sequence_name = false
-
@sequence_name = connection.default_sequence_name(table_name, primary_key)
-
end
-
-
# Sets the name of the sequence to use when generating ids to the given
-
# value, or (if the value is nil or false) to the value returned by the
-
# given block. This is required for Oracle and is useful for any
-
# database which relies on sequences for primary key generation.
-
#
-
# If a sequence name is not explicitly set when using Oracle or Firebird,
-
# it will default to the commonly used pattern of: #{table_name}_seq
-
#
-
# If a sequence name is not explicitly set when using PostgreSQL, it
-
# will discover the sequence corresponding to your primary key for you.
-
#
-
# class Project < ActiveRecord::Base
-
# self.sequence_name = "projectseq" # default would have been "project_seq"
-
# end
-
1
def sequence_name=(value)
-
@sequence_name = value.to_s
-
@explicit_sequence_name = true
-
end
-
-
# Indicates whether the table associated with this class exists
-
1
def table_exists?
-
connection.schema_cache.table_exists?(table_name)
-
end
-
-
# Returns an array of column objects for the table associated with this class.
-
1
def columns
-
@columns ||= connection.schema_cache.columns(table_name).map do |col|
-
col = col.dup
-
col.primary = (col.name == primary_key)
-
col
-
end
-
end
-
-
# Returns a hash of column objects for the table associated with this class.
-
1
def columns_hash
-
@columns_hash ||= Hash[columns.map { |c| [c.name, c] }]
-
end
-
-
1
def column_types # :nodoc:
-
@column_types ||= decorate_columns(columns_hash.dup)
-
end
-
-
1
def decorate_columns(columns_hash) # :nodoc:
-
return if columns_hash.empty?
-
-
@serialized_column_names ||= self.columns_hash.keys.find_all do |name|
-
serialized_attributes.key?(name)
-
end
-
-
@serialized_column_names.each do |name|
-
columns_hash[name] = AttributeMethods::Serialization::Type.new(columns_hash[name])
-
end
-
-
@time_zone_column_names ||= self.columns_hash.find_all do |name, col|
-
create_time_zone_conversion_attribute?(name, col)
-
end.map!(&:first)
-
-
@time_zone_column_names.each do |name|
-
columns_hash[name] = AttributeMethods::TimeZoneConversion::Type.new(columns_hash[name])
-
end
-
-
columns_hash
-
end
-
-
# Returns a hash where the keys are column names and the values are
-
# default values when instantiating the AR object for this table.
-
1
def column_defaults
-
@column_defaults ||= Hash[columns.map { |c| [c.name, c.default] }]
-
end
-
-
# Returns an array of column names as strings.
-
1
def column_names
-
@column_names ||= columns.map { |column| column.name }
-
end
-
-
# Returns an array of column objects where the primary id, all columns ending in "_id" or "_count",
-
# and columns used for single table inheritance have been removed.
-
1
def content_columns
-
@content_columns ||= columns.reject { |c| c.primary || c.name =~ /(_id|_count)$/ || c.name == inheritance_column }
-
end
-
-
# Resets all the cached information about columns, which will cause them
-
# to be reloaded on the next request.
-
#
-
# The most common usage pattern for this method is probably in a migration,
-
# when just after creating a table you want to populate it with some default
-
# values, eg:
-
#
-
# class CreateJobLevels < ActiveRecord::Migration
-
# def up
-
# create_table :job_levels do |t|
-
# t.integer :id
-
# t.string :name
-
#
-
# t.timestamps
-
# end
-
#
-
# JobLevel.reset_column_information
-
# %w{assistant executive manager director}.each do |type|
-
# JobLevel.create(name: type)
-
# end
-
# end
-
#
-
# def down
-
# drop_table :job_levels
-
# end
-
# end
-
1
def reset_column_information
-
connection.clear_cache!
-
undefine_attribute_methods
-
connection.schema_cache.clear_table_cache!(table_name) if table_exists?
-
-
@arel_engine = nil
-
@column_defaults = nil
-
@column_names = nil
-
@columns = nil
-
@columns_hash = nil
-
@column_types = nil
-
@content_columns = nil
-
@dynamic_methods_hash = nil
-
@inheritance_column = nil unless defined?(@explicit_inheritance_column) && @explicit_inheritance_column
-
@relation = nil
-
@serialized_column_names = nil
-
@time_zone_column_names = nil
-
@cached_time_zone = nil
-
end
-
-
# This is a hook for use by modules that need to do extra stuff to
-
# attributes when they are initialized. (e.g. attribute
-
# serialization)
-
1
def initialize_attributes(attributes, options = {}) #:nodoc:
-
attributes
-
end
-
-
1
private
-
-
# Guesses the table name, but does not decorate it with prefix and suffix information.
-
1
def undecorated_table_name(class_name = base_class.name)
-
table_name = class_name.to_s.demodulize.underscore
-
pluralize_table_names ? table_name.pluralize : table_name
-
end
-
-
# Computes and returns a table name according to default conventions.
-
1
def compute_table_name
-
base = base_class
-
if self == base
-
# Nested classes are prefixed with singular parent table name.
-
if parent < Base && !parent.abstract_class?
-
contained = parent.table_name
-
contained = contained.singularize if parent.pluralize_table_names
-
contained += '_'
-
end
-
"#{full_table_name_prefix}#{contained}#{undecorated_table_name(name)}#{table_name_suffix}"
-
else
-
# STI subclasses always use their superclass' table.
-
base.table_name
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/object/try'
-
1
require 'active_support/core_ext/hash/indifferent_access'
-
-
1
module ActiveRecord
-
1
module NestedAttributes #:nodoc:
-
1
class TooManyRecords < ActiveRecordError
-
end
-
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
class_attribute :nested_attributes_options, instance_writer: false
-
1
self.nested_attributes_options = {}
-
end
-
-
# = Active Record Nested Attributes
-
#
-
# Nested attributes allow you to save attributes on associated records
-
# through the parent. By default nested attribute updating is turned off
-
# and you can enable it using the accepts_nested_attributes_for class
-
# method. When you enable nested attributes an attribute writer is
-
# defined on the model.
-
#
-
# The attribute writer is named after the association, which means that
-
# in the following example, two new methods are added to your model:
-
#
-
# <tt>author_attributes=(attributes)</tt> and
-
# <tt>pages_attributes=(attributes)</tt>.
-
#
-
# class Book < ActiveRecord::Base
-
# has_one :author
-
# has_many :pages
-
#
-
# accepts_nested_attributes_for :author, :pages
-
# end
-
#
-
# Note that the <tt>:autosave</tt> option is automatically enabled on every
-
# association that accepts_nested_attributes_for is used for.
-
#
-
# === One-to-one
-
#
-
# Consider a Member model that has one Avatar:
-
#
-
# class Member < ActiveRecord::Base
-
# has_one :avatar
-
# accepts_nested_attributes_for :avatar
-
# end
-
#
-
# Enabling nested attributes on a one-to-one association allows you to
-
# create the member and avatar in one go:
-
#
-
# params = { member: { name: 'Jack', avatar_attributes: { icon: 'smiling' } } }
-
# member = Member.create(params[:member])
-
# member.avatar.id # => 2
-
# member.avatar.icon # => 'smiling'
-
#
-
# It also allows you to update the avatar through the member:
-
#
-
# params = { member: { avatar_attributes: { id: '2', icon: 'sad' } } }
-
# member.update params[:member]
-
# member.avatar.icon # => 'sad'
-
#
-
# By default you will only be able to set and update attributes on the
-
# associated model. If you want to destroy the associated model through the
-
# attributes hash, you have to enable it first using the
-
# <tt>:allow_destroy</tt> option.
-
#
-
# class Member < ActiveRecord::Base
-
# has_one :avatar
-
# accepts_nested_attributes_for :avatar, allow_destroy: true
-
# end
-
#
-
# Now, when you add the <tt>_destroy</tt> key to the attributes hash, with a
-
# value that evaluates to +true+, you will destroy the associated model:
-
#
-
# member.avatar_attributes = { id: '2', _destroy: '1' }
-
# member.avatar.marked_for_destruction? # => true
-
# member.save
-
# member.reload.avatar # => nil
-
#
-
# Note that the model will _not_ be destroyed until the parent is saved.
-
#
-
# === One-to-many
-
#
-
# Consider a member that has a number of posts:
-
#
-
# class Member < ActiveRecord::Base
-
# has_many :posts
-
# accepts_nested_attributes_for :posts
-
# end
-
#
-
# You can now set or update attributes on the associated posts through
-
# an attribute hash for a member: include the key +:posts_attributes+
-
# with an array of hashes of post attributes as a value.
-
#
-
# For each hash that does _not_ have an <tt>id</tt> key a new record will
-
# be instantiated, unless the hash also contains a <tt>_destroy</tt> key
-
# that evaluates to +true+.
-
#
-
# params = { member: {
-
# name: 'joe', posts_attributes: [
-
# { title: 'Kari, the awesome Ruby documentation browser!' },
-
# { title: 'The egalitarian assumption of the modern citizen' },
-
# { title: '', _destroy: '1' } # this will be ignored
-
# ]
-
# }}
-
#
-
# member = Member.create(params[:member])
-
# member.posts.length # => 2
-
# member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'
-
# member.posts.second.title # => 'The egalitarian assumption of the modern citizen'
-
#
-
# You may also set a :reject_if proc to silently ignore any new record
-
# hashes if they fail to pass your criteria. For example, the previous
-
# example could be rewritten as:
-
#
-
# class Member < ActiveRecord::Base
-
# has_many :posts
-
# accepts_nested_attributes_for :posts, reject_if: proc { |attributes| attributes['title'].blank? }
-
# end
-
#
-
# params = { member: {
-
# name: 'joe', posts_attributes: [
-
# { title: 'Kari, the awesome Ruby documentation browser!' },
-
# { title: 'The egalitarian assumption of the modern citizen' },
-
# { title: '' } # this will be ignored because of the :reject_if proc
-
# ]
-
# }}
-
#
-
# member = Member.create(params[:member])
-
# member.posts.length # => 2
-
# member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'
-
# member.posts.second.title # => 'The egalitarian assumption of the modern citizen'
-
#
-
# Alternatively, :reject_if also accepts a symbol for using methods:
-
#
-
# class Member < ActiveRecord::Base
-
# has_many :posts
-
# accepts_nested_attributes_for :posts, reject_if: :new_record?
-
# end
-
#
-
# class Member < ActiveRecord::Base
-
# has_many :posts
-
# accepts_nested_attributes_for :posts, reject_if: :reject_posts
-
#
-
# def reject_posts(attributed)
-
# attributed['title'].blank?
-
# end
-
# end
-
#
-
# If the hash contains an <tt>id</tt> key that matches an already
-
# associated record, the matching record will be modified:
-
#
-
# member.attributes = {
-
# name: 'Joe',
-
# posts_attributes: [
-
# { id: 1, title: '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!' },
-
# { id: 2, title: '[UPDATED] other post' }
-
# ]
-
# }
-
#
-
# member.posts.first.title # => '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!'
-
# member.posts.second.title # => '[UPDATED] other post'
-
#
-
# By default the associated records are protected from being destroyed. If
-
# you want to destroy any of the associated records through the attributes
-
# hash, you have to enable it first using the <tt>:allow_destroy</tt>
-
# option. This will allow you to also use the <tt>_destroy</tt> key to
-
# destroy existing records:
-
#
-
# class Member < ActiveRecord::Base
-
# has_many :posts
-
# accepts_nested_attributes_for :posts, allow_destroy: true
-
# end
-
#
-
# params = { member: {
-
# posts_attributes: [{ id: '2', _destroy: '1' }]
-
# }}
-
#
-
# member.attributes = params[:member]
-
# member.posts.detect { |p| p.id == 2 }.marked_for_destruction? # => true
-
# member.posts.length # => 2
-
# member.save
-
# member.reload.posts.length # => 1
-
#
-
# Nested attributes for an associated collection can also be passed in
-
# the form of a hash of hashes instead of an array of hashes:
-
#
-
# Member.create(name: 'joe',
-
# posts_attributes: { first: { title: 'Foo' },
-
# second: { title: 'Bar' } })
-
#
-
# has the same effect as
-
#
-
# Member.create(name: 'joe',
-
# posts_attributes: [ { title: 'Foo' },
-
# { title: 'Bar' } ])
-
#
-
# The keys of the hash which is the value for +:posts_attributes+ are
-
# ignored in this case.
-
# However, it is not allowed to use +'id'+ or +:id+ for one of
-
# such keys, otherwise the hash will be wrapped in an array and
-
# interpreted as an attribute hash for a single post.
-
#
-
# Passing attributes for an associated collection in the form of a hash
-
# of hashes can be used with hashes generated from HTTP/HTML parameters,
-
# where there maybe no natural way to submit an array of hashes.
-
#
-
# === Saving
-
#
-
# All changes to models, including the destruction of those marked for
-
# destruction, are saved and destroyed automatically and atomically when
-
# the parent model is saved. This happens inside the transaction initiated
-
# by the parents save method. See ActiveRecord::AutosaveAssociation.
-
#
-
# === Validating the presence of a parent model
-
#
-
# If you want to validate that a child record is associated with a parent
-
# record, you can use <tt>validates_presence_of</tt> and
-
# <tt>inverse_of</tt> as this example illustrates:
-
#
-
# class Member < ActiveRecord::Base
-
# has_many :posts, inverse_of: :member
-
# accepts_nested_attributes_for :posts
-
# end
-
#
-
# class Post < ActiveRecord::Base
-
# belongs_to :member, inverse_of: :posts
-
# validates_presence_of :member
-
# end
-
#
-
# Note that if you do not specify the <tt>inverse_of</tt> option, then
-
# Active Record will try to automatically guess the inverse association
-
# based on heuristics.
-
#
-
# For one-to-one nested associations, if you build the new (in-memory)
-
# child object yourself before assignment, then this module will not
-
# overwrite it, e.g.:
-
#
-
# class Member < ActiveRecord::Base
-
# has_one :avatar
-
# accepts_nested_attributes_for :avatar
-
#
-
# def avatar
-
# super || build_avatar(width: 200)
-
# end
-
# end
-
#
-
# member = Member.new
-
# member.avatar_attributes = {icon: 'sad'}
-
# member.avatar.width # => 200
-
1
module ClassMethods
-
1
REJECT_ALL_BLANK_PROC = proc { |attributes| attributes.all? { |key, value| key == '_destroy' || value.blank? } }
-
-
# Defines an attributes writer for the specified association(s).
-
#
-
# Supported options:
-
# [:allow_destroy]
-
# If true, destroys any members from the attributes hash with a
-
# <tt>_destroy</tt> key and a value that evaluates to +true+
-
# (eg. 1, '1', true, or 'true'). This option is off by default.
-
# [:reject_if]
-
# Allows you to specify a Proc or a Symbol pointing to a method
-
# that checks whether a record should be built for a certain attribute
-
# hash. The hash is passed to the supplied Proc or the method
-
# and it should return either +true+ or +false+. When no :reject_if
-
# is specified, a record will be built for all attribute hashes that
-
# do not have a <tt>_destroy</tt> value that evaluates to true.
-
# Passing <tt>:all_blank</tt> instead of a Proc will create a proc
-
# that will reject a record where all the attributes are blank excluding
-
# any value for _destroy.
-
# [:limit]
-
# Allows you to specify the maximum number of the associated records that
-
# can be processed with the nested attributes. Limit also can be specified as a
-
# Proc or a Symbol pointing to a method that should return number. If the size of the
-
# nested attributes array exceeds the specified limit, NestedAttributes::TooManyRecords
-
# exception is raised. If omitted, any number associations can be processed.
-
# Note that the :limit option is only applicable to one-to-many associations.
-
# [:update_only]
-
# For a one-to-one association, this option allows you to specify how
-
# nested attributes are to be used when an associated record already
-
# exists. In general, an existing record may either be updated with the
-
# new set of attribute values or be replaced by a wholly new record
-
# containing those values. By default the :update_only option is +false+
-
# and the nested attributes are used to update the existing record only
-
# if they include the record's <tt>:id</tt> value. Otherwise a new
-
# record will be instantiated and used to replace the existing one.
-
# However if the :update_only option is +true+, the nested attributes
-
# are used to update the record's attributes always, regardless of
-
# whether the <tt>:id</tt> is present. The option is ignored for collection
-
# associations.
-
#
-
# Examples:
-
# # creates avatar_attributes=
-
# accepts_nested_attributes_for :avatar, reject_if: proc { |attributes| attributes['name'].blank? }
-
# # creates avatar_attributes=
-
# accepts_nested_attributes_for :avatar, reject_if: :all_blank
-
# # creates avatar_attributes= and posts_attributes=
-
# accepts_nested_attributes_for :avatar, :posts, allow_destroy: true
-
1
def accepts_nested_attributes_for(*attr_names)
-
5
options = { :allow_destroy => false, :update_only => false }
-
5
options.update(attr_names.extract_options!)
-
5
options.assert_valid_keys(:allow_destroy, :reject_if, :limit, :update_only)
-
5
options[:reject_if] = REJECT_ALL_BLANK_PROC if options[:reject_if] == :all_blank
-
-
5
attr_names.each do |association_name|
-
5
if reflection = reflect_on_association(association_name)
-
5
reflection.autosave = true
-
5
add_autosave_association_callbacks(reflection)
-
-
5
nested_attributes_options = self.nested_attributes_options.dup
-
5
nested_attributes_options[association_name.to_sym] = options
-
5
self.nested_attributes_options = nested_attributes_options
-
-
5
type = (reflection.collection? ? :collection : :one_to_one)
-
5
generate_association_writer(association_name, type)
-
else
-
raise ArgumentError, "No association found for name `#{association_name}'. Has it been defined yet?"
-
end
-
end
-
end
-
-
1
private
-
-
# Generates a writer method for this association. Serves as a point for
-
# accessing the objects in the association. For example, this method
-
# could generate the following:
-
#
-
# def pirate_attributes=(attributes)
-
# assign_nested_attributes_for_one_to_one_association(:pirate, attributes)
-
# end
-
#
-
# This redirects the attempts to write objects in an association through
-
# the helper methods defined below. Makes it seem like the nested
-
# associations are just regular associations.
-
1
def generate_association_writer(association_name, type)
-
5
generated_association_methods.module_eval <<-eoruby, __FILE__, __LINE__ + 1
-
if method_defined?(:#{association_name}_attributes=)
-
remove_method(:#{association_name}_attributes=)
-
end
-
def #{association_name}_attributes=(attributes)
-
assign_nested_attributes_for_#{type}_association(:#{association_name}, attributes)
-
end
-
eoruby
-
end
-
end
-
-
# Returns ActiveRecord::AutosaveAssociation::marked_for_destruction? It's
-
# used in conjunction with fields_for to build a form element for the
-
# destruction of this association.
-
#
-
# See ActionView::Helpers::FormHelper::fields_for for more info.
-
1
def _destroy
-
marked_for_destruction?
-
end
-
-
1
private
-
-
# Attribute hash keys that should not be assigned as normal attributes.
-
# These hash keys are nested attributes implementation details.
-
1
UNASSIGNABLE_KEYS = %w( id _destroy )
-
-
# Assigns the given attributes to the association.
-
#
-
# If an associated record does not yet exist, one will be instantiated. If
-
# an associated record already exists, the method's behavior depends on
-
# the value of the update_only option. If update_only is +false+ and the
-
# given attributes include an <tt>:id</tt> that matches the existing record's
-
# id, then the existing record will be modified. If no <tt>:id</tt> is provided
-
# it will be replaced with a new record. If update_only is +true+ the existing
-
# record will be modified regardless of whether an <tt>:id</tt> is provided.
-
#
-
# If the given attributes include a matching <tt>:id</tt> attribute, or
-
# update_only is true, and a <tt>:_destroy</tt> key set to a truthy value,
-
# then the existing record will be marked for destruction.
-
1
def assign_nested_attributes_for_one_to_one_association(association_name, attributes)
-
options = self.nested_attributes_options[association_name]
-
attributes = attributes.with_indifferent_access
-
existing_record = send(association_name)
-
-
if (options[:update_only] || !attributes['id'].blank?) && existing_record &&
-
(options[:update_only] || existing_record.id.to_s == attributes['id'].to_s)
-
assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy]) unless call_reject_if(association_name, attributes)
-
-
elsif attributes['id'].present?
-
raise_nested_attributes_record_not_found!(association_name, attributes['id'])
-
-
elsif !reject_new_record?(association_name, attributes)
-
assignable_attributes = attributes.except(*UNASSIGNABLE_KEYS)
-
-
if existing_record && existing_record.new_record?
-
existing_record.assign_attributes(assignable_attributes)
-
association(association_name).initialize_attributes(existing_record)
-
else
-
method = "build_#{association_name}"
-
if respond_to?(method)
-
send(method, assignable_attributes)
-
else
-
raise ArgumentError, "Cannot build association `#{association_name}'. Are you trying to build a polymorphic one-to-one association?"
-
end
-
end
-
end
-
end
-
-
# Assigns the given attributes to the collection association.
-
#
-
# Hashes with an <tt>:id</tt> value matching an existing associated record
-
# will update that record. Hashes without an <tt>:id</tt> value will build
-
# a new record for the association. Hashes with a matching <tt>:id</tt>
-
# value and a <tt>:_destroy</tt> key set to a truthy value will mark the
-
# matched record for destruction.
-
#
-
# For example:
-
#
-
# assign_nested_attributes_for_collection_association(:people, {
-
# '1' => { id: '1', name: 'Peter' },
-
# '2' => { name: 'John' },
-
# '3' => { id: '2', _destroy: true }
-
# })
-
#
-
# Will update the name of the Person with ID 1, build a new associated
-
# person with the name 'John', and mark the associated Person with ID 2
-
# for destruction.
-
#
-
# Also accepts an Array of attribute hashes:
-
#
-
# assign_nested_attributes_for_collection_association(:people, [
-
# { id: '1', name: 'Peter' },
-
# { name: 'John' },
-
# { id: '2', _destroy: true }
-
# ])
-
1
def assign_nested_attributes_for_collection_association(association_name, attributes_collection)
-
options = self.nested_attributes_options[association_name]
-
-
unless attributes_collection.is_a?(Hash) || attributes_collection.is_a?(Array)
-
raise ArgumentError, "Hash or Array expected, got #{attributes_collection.class.name} (#{attributes_collection.inspect})"
-
end
-
-
check_record_limit!(options[:limit], attributes_collection)
-
-
if attributes_collection.is_a? Hash
-
keys = attributes_collection.keys
-
attributes_collection = if keys.include?('id') || keys.include?(:id)
-
[attributes_collection]
-
else
-
attributes_collection.values
-
end
-
end
-
-
association = association(association_name)
-
-
existing_records = if association.loaded?
-
association.target
-
else
-
attribute_ids = attributes_collection.map {|a| a['id'] || a[:id] }.compact
-
attribute_ids.empty? ? [] : association.scope.where(association.klass.primary_key => attribute_ids)
-
end
-
-
attributes_collection.each do |attributes|
-
attributes = attributes.with_indifferent_access
-
-
if attributes['id'].blank?
-
unless reject_new_record?(association_name, attributes)
-
association.build(attributes.except(*UNASSIGNABLE_KEYS))
-
end
-
elsif existing_record = existing_records.detect { |record| record.id.to_s == attributes['id'].to_s }
-
unless call_reject_if(association_name, attributes)
-
# Make sure we are operating on the actual object which is in the association's
-
# proxy_target array (either by finding it, or adding it if not found)
-
# Take into account that the proxy_target may have changed due to callbacks
-
target_record = association.target.detect { |record| record.id.to_s == attributes['id'].to_s }
-
if target_record
-
existing_record = target_record
-
else
-
association.add_to_target(existing_record, :skip_callbacks)
-
end
-
-
assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy])
-
end
-
else
-
raise_nested_attributes_record_not_found!(association_name, attributes['id'])
-
end
-
end
-
end
-
-
# Takes in a limit and checks if the attributes_collection has too many
-
# records. The method will take limits in the form of symbols, procs, and
-
# number-like objects (anything that can be compared with an integer).
-
#
-
# Will raise an TooManyRecords error if the attributes_collection is
-
# larger than the limit.
-
1
def check_record_limit!(limit, attributes_collection)
-
if limit
-
limit = case limit
-
when Symbol
-
send(limit)
-
when Proc
-
limit.call
-
else
-
limit
-
end
-
-
if limit && attributes_collection.size > limit
-
raise TooManyRecords, "Maximum #{limit} records are allowed. Got #{attributes_collection.size} records instead."
-
end
-
end
-
end
-
-
# Updates a record with the +attributes+ or marks it for destruction if
-
# +allow_destroy+ is +true+ and has_destroy_flag? returns +true+.
-
1
def assign_to_or_mark_for_destruction(record, attributes, allow_destroy)
-
record.assign_attributes(attributes.except(*UNASSIGNABLE_KEYS))
-
record.mark_for_destruction if has_destroy_flag?(attributes) && allow_destroy
-
end
-
-
# Determines if a hash contains a truthy _destroy key.
-
1
def has_destroy_flag?(hash)
-
ConnectionAdapters::Column.value_to_boolean(hash['_destroy'])
-
end
-
-
# Determines if a new record should be build by checking for
-
# has_destroy_flag? or if a <tt>:reject_if</tt> proc exists for this
-
# association and evaluates to +true+.
-
1
def reject_new_record?(association_name, attributes)
-
has_destroy_flag?(attributes) || call_reject_if(association_name, attributes)
-
end
-
-
# Determines if a record with the particular +attributes+ should be
-
# rejected by calling the reject_if Symbol or Proc (if defined).
-
# The reject_if option is defined by +accepts_nested_attributes_for+.
-
#
-
# Returns false if there is a +destroy_flag+ on the attributes.
-
1
def call_reject_if(association_name, attributes)
-
return false if has_destroy_flag?(attributes)
-
case callback = self.nested_attributes_options[association_name][:reject_if]
-
when Symbol
-
method(callback).arity == 0 ? send(callback) : send(callback, attributes)
-
when Proc
-
callback.call(attributes)
-
end
-
end
-
-
1
def raise_nested_attributes_record_not_found!(association_name, record_id)
-
raise RecordNotFound, "Couldn't find #{self.class.reflect_on_association(association_name).klass.name} with ID=#{record_id} for #{self.class.name} with ID=#{id}"
-
end
-
end
-
end
-
1
module ActiveRecord
-
# = Active Record No Touching
-
1
module NoTouching
-
1
extend ActiveSupport::Concern
-
-
1
module ClassMethods
-
# Lets you selectively disable calls to `touch` for the
-
# duration of a block.
-
#
-
# ==== Examples
-
# ActiveRecord::Base.no_touching do
-
# Project.first.touch # does nothing
-
# Message.first.touch # does nothing
-
# end
-
#
-
# Project.no_touching do
-
# Project.first.touch # does nothing
-
# Message.first.touch # works, but does not touch the associated project
-
# end
-
#
-
1
def no_touching(&block)
-
NoTouching.apply_to(self, &block)
-
end
-
end
-
-
1
class << self
-
1
def apply_to(klass) #:nodoc:
-
klasses.push(klass)
-
yield
-
ensure
-
klasses.pop
-
end
-
-
1
def applied_to?(klass) #:nodoc:
-
klasses.any? { |k| k >= klass }
-
end
-
-
1
private
-
1
def klasses
-
Thread.current[:no_touching_classes] ||= []
-
end
-
end
-
-
1
def no_touching?
-
NoTouching.applied_to?(self.class)
-
end
-
-
1
def touch(*)
-
super unless no_touching?
-
end
-
end
-
end
-
1
module ActiveRecord
-
# = Active Record Persistence
-
1
module Persistence
-
1
extend ActiveSupport::Concern
-
-
1
module ClassMethods
-
# Creates an object (or multiple objects) and saves it to the database, if validations pass.
-
# The resulting object is returned whether the object was saved successfully to the database or not.
-
#
-
# The +attributes+ parameter can be either a Hash or an Array of Hashes. These Hashes describe the
-
# attributes on the objects that are to be created.
-
#
-
# ==== Examples
-
# # Create a single new object
-
# User.create(first_name: 'Jamie')
-
#
-
# # Create an Array of new objects
-
# User.create([{ first_name: 'Jamie' }, { first_name: 'Jeremy' }])
-
#
-
# # Create a single object and pass it into a block to set other attributes.
-
# User.create(first_name: 'Jamie') do |u|
-
# u.is_admin = false
-
# end
-
#
-
# # Creating an Array of new objects using a block, where the block is executed for each object:
-
# User.create([{ first_name: 'Jamie' }, { first_name: 'Jeremy' }]) do |u|
-
# u.is_admin = false
-
# end
-
1
def create(attributes = nil, &block)
-
if attributes.is_a?(Array)
-
attributes.collect { |attr| create(attr, &block) }
-
else
-
object = new(attributes, &block)
-
object.save
-
object
-
end
-
end
-
-
# Given an attributes hash, +instantiate+ returns a new instance of
-
# the appropriate class.
-
#
-
# For example, +Post.all+ may return Comments, Messages, and Emails
-
# by storing the record's subclass in a +type+ attribute. By calling
-
# +instantiate+ instead of +new+, finder methods ensure they get new
-
# instances of the appropriate class for each record.
-
#
-
# See +ActiveRecord::Inheritance#discriminate_class_for_record+ to see
-
# how this "single-table" inheritance mapping is implemented.
-
1
def instantiate(record, column_types = {})
-
klass = discriminate_class_for_record(record)
-
column_types = klass.decorate_columns(column_types.dup)
-
klass.allocate.init_with('attributes' => record, 'column_types' => column_types)
-
end
-
-
1
private
-
# Called by +instantiate+ to decide which class to use for a new
-
# record instance.
-
#
-
# See +ActiveRecord::Inheritance#discriminate_class_for_record+ for
-
# the single-table inheritance discriminator.
-
1
def discriminate_class_for_record(record)
-
self
-
end
-
end
-
-
# Returns true if this object hasn't been saved yet -- that is, a record
-
# for the object doesn't exist in the database yet; otherwise, returns false.
-
1
def new_record?
-
sync_with_transaction_state
-
@new_record
-
end
-
-
# Returns true if this object has been destroyed, otherwise returns false.
-
1
def destroyed?
-
sync_with_transaction_state
-
@destroyed
-
end
-
-
# Returns true if the record is persisted, i.e. it's not a new record and it was
-
# not destroyed, otherwise returns false.
-
1
def persisted?
-
!(new_record? || destroyed?)
-
end
-
-
# Saves the model.
-
#
-
# If the model is new a record gets created in the database, otherwise
-
# the existing record gets updated.
-
#
-
# By default, save always run validations. If any of them fail the action
-
# is cancelled and +save+ returns +false+. However, if you supply
-
# validate: false, validations are bypassed altogether. See
-
# ActiveRecord::Validations for more information.
-
#
-
# There's a series of callbacks associated with +save+. If any of the
-
# <tt>before_*</tt> callbacks return +false+ the action is cancelled and
-
# +save+ returns +false+. See ActiveRecord::Callbacks for further
-
# details.
-
#
-
# Attributes marked as readonly are silently ignored if the record is
-
# being updated.
-
1
def save(*)
-
create_or_update
-
rescue ActiveRecord::RecordInvalid
-
false
-
end
-
-
# Saves the model.
-
#
-
# If the model is new a record gets created in the database, otherwise
-
# the existing record gets updated.
-
#
-
# With <tt>save!</tt> validations always run. If any of them fail
-
# ActiveRecord::RecordInvalid gets raised. See ActiveRecord::Validations
-
# for more information.
-
#
-
# There's a series of callbacks associated with <tt>save!</tt>. If any of
-
# the <tt>before_*</tt> callbacks return +false+ the action is cancelled
-
# and <tt>save!</tt> raises ActiveRecord::RecordNotSaved. See
-
# ActiveRecord::Callbacks for further details.
-
#
-
# Attributes marked as readonly are silently ignored if the record is
-
# being updated.
-
1
def save!(*)
-
create_or_update || raise(RecordNotSaved)
-
end
-
-
# Deletes the record in the database and freezes this instance to
-
# reflect that no changes should be made (since they can't be
-
# persisted). Returns the frozen instance.
-
#
-
# The row is simply removed with an SQL +DELETE+ statement on the
-
# record's primary key, and no callbacks are executed.
-
#
-
# To enforce the object's +before_destroy+ and +after_destroy+
-
# callbacks or any <tt>:dependent</tt> association
-
# options, use <tt>#destroy</tt>.
-
1
def delete
-
self.class.delete(id) if persisted?
-
@destroyed = true
-
freeze
-
end
-
-
# Deletes the record in the database and freezes this instance to reflect
-
# that no changes should be made (since they can't be persisted).
-
#
-
# There's a series of callbacks associated with <tt>destroy</tt>. If
-
# the <tt>before_destroy</tt> callback return +false+ the action is cancelled
-
# and <tt>destroy</tt> returns +false+. See
-
# ActiveRecord::Callbacks for further details.
-
1
def destroy
-
raise ReadOnlyRecord if readonly?
-
destroy_associations
-
destroy_row if persisted?
-
@destroyed = true
-
freeze
-
end
-
-
# Deletes the record in the database and freezes this instance to reflect
-
# that no changes should be made (since they can't be persisted).
-
#
-
# There's a series of callbacks associated with <tt>destroy!</tt>. If
-
# the <tt>before_destroy</tt> callback return +false+ the action is cancelled
-
# and <tt>destroy!</tt> raises ActiveRecord::RecordNotDestroyed. See
-
# ActiveRecord::Callbacks for further details.
-
1
def destroy!
-
destroy || raise(ActiveRecord::RecordNotDestroyed)
-
end
-
-
# Returns an instance of the specified +klass+ with the attributes of the
-
# current record. This is mostly useful in relation to single-table
-
# inheritance structures where you want a subclass to appear as the
-
# superclass. This can be used along with record identification in
-
# Action Pack to allow, say, <tt>Client < Company</tt> to do something
-
# like render <tt>partial: @client.becomes(Company)</tt> to render that
-
# instance using the companies/company partial instead of clients/client.
-
#
-
# Note: The new instance will share a link to the same attributes as the original class.
-
# So any change to the attributes in either instance will affect the other.
-
1
def becomes(klass)
-
became = klass.new
-
became.instance_variable_set("@attributes", @attributes)
-
became.instance_variable_set("@attributes_cache", @attributes_cache)
-
became.instance_variable_set("@changed_attributes", @changed_attributes) if defined?(@changed_attributes)
-
became.instance_variable_set("@new_record", new_record?)
-
became.instance_variable_set("@destroyed", destroyed?)
-
became.instance_variable_set("@errors", errors)
-
became
-
end
-
-
# Wrapper around +becomes+ that also changes the instance's sti column value.
-
# This is especially useful if you want to persist the changed class in your
-
# database.
-
#
-
# Note: The old instance's sti column value will be changed too, as both objects
-
# share the same set of attributes.
-
1
def becomes!(klass)
-
became = becomes(klass)
-
sti_type = nil
-
if !klass.descends_from_active_record?
-
sti_type = klass.sti_name
-
end
-
became.public_send("#{klass.inheritance_column}=", sti_type)
-
became
-
end
-
-
# Updates a single attribute and saves the record.
-
# This is especially useful for boolean flags on existing records. Also note that
-
#
-
# * Validation is skipped.
-
# * Callbacks are invoked.
-
# * updated_at/updated_on column is updated if that column is available.
-
# * Updates all the attributes that are dirty in this object.
-
#
-
# This method raises an +ActiveRecord::ActiveRecordError+ if the
-
# attribute is marked as readonly.
-
1
def update_attribute(name, value)
-
name = name.to_s
-
verify_readonly_attribute(name)
-
send("#{name}=", value)
-
save(validate: false)
-
end
-
-
# Updates the attributes of the model from the passed-in hash and saves the
-
# record, all wrapped in a transaction. If the object is invalid, the saving
-
# will fail and false will be returned.
-
1
def update(attributes)
-
# The following transaction covers any possible database side-effects of the
-
# attributes assignment. For example, setting the IDs of a child collection.
-
with_transaction_returning_status do
-
assign_attributes(attributes)
-
save
-
end
-
end
-
-
1
alias update_attributes update
-
-
# Updates its receiver just like +update+ but calls <tt>save!</tt> instead
-
# of +save+, so an exception is raised if the record is invalid.
-
1
def update!(attributes)
-
# The following transaction covers any possible database side-effects of the
-
# attributes assignment. For example, setting the IDs of a child collection.
-
with_transaction_returning_status do
-
assign_attributes(attributes)
-
save!
-
end
-
end
-
-
1
alias update_attributes! update!
-
-
# Equivalent to <code>update_columns(name => value)</code>.
-
1
def update_column(name, value)
-
update_columns(name => value)
-
end
-
-
# Updates the attributes directly in the database issuing an UPDATE SQL
-
# statement and sets them in the receiver:
-
#
-
# user.update_columns(last_request_at: Time.current)
-
#
-
# This is the fastest way to update attributes because it goes straight to
-
# the database, but take into account that in consequence the regular update
-
# procedures are totally bypassed. In particular:
-
#
-
# * Validations are skipped.
-
# * Callbacks are skipped.
-
# * +updated_at+/+updated_on+ are not updated.
-
#
-
# This method raises an +ActiveRecord::ActiveRecordError+ when called on new
-
# objects, or when at least one of the attributes is marked as readonly.
-
1
def update_columns(attributes)
-
raise ActiveRecordError, "cannot update on a new record object" unless persisted?
-
-
attributes.each_key do |key|
-
verify_readonly_attribute(key.to_s)
-
end
-
-
updated_count = self.class.unscoped.where(self.class.primary_key => id).update_all(attributes)
-
-
attributes.each do |k, v|
-
raw_write_attribute(k, v)
-
end
-
-
updated_count == 1
-
end
-
-
# Initializes +attribute+ to zero if +nil+ and adds the value passed as +by+ (default is 1).
-
# The increment is performed directly on the underlying attribute, no setter is invoked.
-
# Only makes sense for number-based attributes. Returns +self+.
-
1
def increment(attribute, by = 1)
-
self[attribute] ||= 0
-
self[attribute] += by
-
self
-
end
-
-
# Wrapper around +increment+ that saves the record. This method differs from
-
# its non-bang version in that it passes through the attribute setter.
-
# Saving is not subjected to validation checks. Returns +true+ if the
-
# record could be saved.
-
1
def increment!(attribute, by = 1)
-
increment(attribute, by).update_attribute(attribute, self[attribute])
-
end
-
-
# Initializes +attribute+ to zero if +nil+ and subtracts the value passed as +by+ (default is 1).
-
# The decrement is performed directly on the underlying attribute, no setter is invoked.
-
# Only makes sense for number-based attributes. Returns +self+.
-
1
def decrement(attribute, by = 1)
-
self[attribute] ||= 0
-
self[attribute] -= by
-
self
-
end
-
-
# Wrapper around +decrement+ that saves the record. This method differs from
-
# its non-bang version in that it passes through the attribute setter.
-
# Saving is not subjected to validation checks. Returns +true+ if the
-
# record could be saved.
-
1
def decrement!(attribute, by = 1)
-
decrement(attribute, by).update_attribute(attribute, self[attribute])
-
end
-
-
# Assigns to +attribute+ the boolean opposite of <tt>attribute?</tt>. So
-
# if the predicate returns +true+ the attribute will become +false+. This
-
# method toggles directly the underlying value without calling any setter.
-
# Returns +self+.
-
1
def toggle(attribute)
-
self[attribute] = !send("#{attribute}?")
-
self
-
end
-
-
# Wrapper around +toggle+ that saves the record. This method differs from
-
# its non-bang version in that it passes through the attribute setter.
-
# Saving is not subjected to validation checks. Returns +true+ if the
-
# record could be saved.
-
1
def toggle!(attribute)
-
toggle(attribute).update_attribute(attribute, self[attribute])
-
end
-
-
# Reloads the record from the database.
-
#
-
# This method finds record by its primary key (which could be assigned manually) and
-
# modifies the receiver in-place:
-
#
-
# account = Account.new
-
# # => #<Account id: nil, email: nil>
-
# account.id = 1
-
# account.reload
-
# # Account Load (1.2ms) SELECT "accounts".* FROM "accounts" WHERE "accounts"."id" = $1 LIMIT 1 [["id", 1]]
-
# # => #<Account id: 1, email: 'account@example.com'>
-
#
-
# Attributes are reloaded from the database, and caches busted, in
-
# particular the associations cache.
-
#
-
# If the record no longer exists in the database <tt>ActiveRecord::RecordNotFound</tt>
-
# is raised. Otherwise, in addition to the in-place modification the method
-
# returns +self+ for convenience.
-
#
-
# The optional <tt>:lock</tt> flag option allows you to lock the reloaded record:
-
#
-
# reload(lock: true) # reload with pessimistic locking
-
#
-
# Reloading is commonly used in test suites to test something is actually
-
# written to the database, or when some action modifies the corresponding
-
# row in the database but not the object in memory:
-
#
-
# assert account.deposit!(25)
-
# assert_equal 25, account.credit # check it is updated in memory
-
# assert_equal 25, account.reload.credit # check it is also persisted
-
#
-
# Another common use case is optimistic locking handling:
-
#
-
# def with_optimistic_retry
-
# begin
-
# yield
-
# rescue ActiveRecord::StaleObjectError
-
# begin
-
# # Reload lock_version in particular.
-
# reload
-
# rescue ActiveRecord::RecordNotFound
-
# # If the record is gone there is nothing to do.
-
# else
-
# retry
-
# end
-
# end
-
# end
-
#
-
1
def reload(options = nil)
-
clear_aggregation_cache
-
clear_association_cache
-
-
fresh_object =
-
if options && options[:lock]
-
self.class.unscoped { self.class.lock(options[:lock]).find(id) }
-
else
-
self.class.unscoped { self.class.find(id) }
-
end
-
-
@attributes.update(fresh_object.instance_variable_get('@attributes'))
-
-
@column_types = self.class.column_types
-
@column_types_override = fresh_object.instance_variable_get('@column_types_override')
-
@attributes_cache = {}
-
self
-
end
-
-
# Saves the record with the updated_at/on attributes set to the current time.
-
# Please note that no validation is performed and only the +after_touch+
-
# callback is executed.
-
# If an attribute name is passed, that attribute is updated along with
-
# updated_at/on attributes.
-
#
-
# product.touch # updates updated_at/on
-
# product.touch(:designed_at) # updates the designed_at attribute and updated_at/on
-
#
-
# If used along with +belongs_to+ then +touch+ will invoke +touch+ method on associated object.
-
#
-
# class Brake < ActiveRecord::Base
-
# belongs_to :car, touch: true
-
# end
-
#
-
# class Car < ActiveRecord::Base
-
# belongs_to :corporation, touch: true
-
# end
-
#
-
# # triggers @brake.car.touch and @brake.car.corporation.touch
-
# @brake.touch
-
#
-
# Note that +touch+ must be used on a persisted object, or else an
-
# ActiveRecordError will be thrown. For example:
-
#
-
# ball = Ball.new
-
# ball.touch(:updated_at) # => raises ActiveRecordError
-
#
-
1
def touch(name = nil)
-
raise ActiveRecordError, "cannot touch on a new record object" unless persisted?
-
-
attributes = timestamp_attributes_for_update_in_model
-
attributes << name if name
-
-
unless attributes.empty?
-
current_time = current_time_from_proper_timezone
-
changes = {}
-
-
attributes.each do |column|
-
column = column.to_s
-
changes[column] = write_attribute(column, current_time)
-
end
-
-
changes[self.class.locking_column] = increment_lock if locking_enabled?
-
-
changed_attributes.except!(*changes.keys)
-
primary_key = self.class.primary_key
-
self.class.unscoped.where(primary_key => self[primary_key]).update_all(changes) == 1
-
else
-
true
-
end
-
end
-
-
1
private
-
-
# A hook to be overridden by association modules.
-
1
def destroy_associations
-
end
-
-
1
def destroy_row
-
relation_for_destroy.delete_all
-
end
-
-
1
def relation_for_destroy
-
pk = self.class.primary_key
-
column = self.class.columns_hash[pk]
-
substitute = self.class.connection.substitute_at(column, 0)
-
-
relation = self.class.unscoped.where(
-
self.class.arel_table[pk].eq(substitute))
-
-
relation.bind_values = [[column, id]]
-
relation
-
end
-
-
1
def create_or_update
-
raise ReadOnlyRecord if readonly?
-
result = new_record? ? create_record : update_record
-
result != false
-
end
-
-
# Updates the associated record with values matching those of the instance attributes.
-
# Returns the number of affected rows.
-
1
def update_record(attribute_names = @attributes.keys)
-
attributes_values = arel_attributes_with_values_for_update(attribute_names)
-
if attributes_values.empty?
-
0
-
else
-
self.class.unscoped.update_record attributes_values, id, id_was
-
end
-
end
-
-
# Creates a record with values matching those of the instance attributes
-
# and returns its id.
-
1
def create_record(attribute_names = @attributes.keys)
-
attributes_values = arel_attributes_with_values_for_create(attribute_names)
-
-
new_id = self.class.unscoped.insert attributes_values
-
self.id ||= new_id if self.class.primary_key
-
-
@new_record = false
-
id
-
end
-
-
1
def verify_readonly_attribute(name)
-
raise ActiveRecordError, "#{name} is marked as readonly" if self.class.readonly_attributes.include?(name)
-
end
-
end
-
end
-
-
1
module ActiveRecord
-
# = Active Record Query Cache
-
1
class QueryCache
-
1
module ClassMethods
-
# Enable the query cache within the block if Active Record is configured.
-
# If it's not, it will execute the given block.
-
1
def cache(&block)
-
if ActiveRecord::Base.connected?
-
connection.cache(&block)
-
else
-
yield
-
end
-
end
-
-
# Disable the query cache within the block if Active Record is configured.
-
# If it's not, it will execute the given block.
-
1
def uncached(&block)
-
if ActiveRecord::Base.connected?
-
connection.uncached(&block)
-
else
-
yield
-
end
-
end
-
end
-
-
1
def initialize(app)
-
1
@app = app
-
end
-
-
1
def call(env)
-
enabled = ActiveRecord::Base.connection.query_cache_enabled
-
connection_id = ActiveRecord::Base.connection_id
-
ActiveRecord::Base.connection.enable_query_cache!
-
-
response = @app.call(env)
-
response[2] = Rack::BodyProxy.new(response[2]) do
-
restore_query_cache_settings(connection_id, enabled)
-
end
-
-
response
-
rescue Exception => e
-
restore_query_cache_settings(connection_id, enabled)
-
raise e
-
end
-
-
1
private
-
-
1
def restore_query_cache_settings(connection_id, enabled)
-
ActiveRecord::Base.connection_id = connection_id
-
ActiveRecord::Base.connection.clear_query_cache
-
ActiveRecord::Base.connection.disable_query_cache! unless enabled
-
end
-
-
end
-
end
-
1
module ActiveRecord
-
1
module Querying
-
1
delegate :find, :take, :take!, :first, :first!, :last, :last!, :exists?, :any?, :many?, to: :all
-
1
delegate :second, :second!, :third, :third!, :fourth, :fourth!, :fifth, :fifth!, :forty_two, :forty_two!, to: :all
-
1
delegate :first_or_create, :first_or_create!, :first_or_initialize, to: :all
-
1
delegate :find_or_create_by, :find_or_create_by!, :find_or_initialize_by, to: :all
-
1
delegate :find_by, :find_by!, to: :all
-
1
delegate :destroy, :destroy_all, :delete, :delete_all, :update, :update_all, to: :all
-
1
delegate :find_each, :find_in_batches, to: :all
-
1
delegate :select, :group, :order, :except, :reorder, :limit, :offset, :joins,
-
:where, :rewhere, :preload, :eager_load, :includes, :from, :lock, :readonly,
-
:having, :create_with, :uniq, :distinct, :references, :none, :unscope, to: :all
-
1
delegate :count, :average, :minimum, :maximum, :sum, :calculate, to: :all
-
1
delegate :pluck, :ids, to: :all
-
-
# Executes a custom SQL query against your database and returns all the results. The results will
-
# be returned as an array with columns requested encapsulated as attributes of the model you call
-
# this method from. If you call <tt>Product.find_by_sql</tt> then the results will be returned in
-
# a +Product+ object with the attributes you specified in the SQL query.
-
#
-
# If you call a complicated SQL query which spans multiple tables the columns specified by the
-
# SELECT will be attributes of the model, whether or not they are columns of the corresponding
-
# table.
-
#
-
# The +sql+ parameter is a full SQL query as a string. It will be called as is, there will be
-
# no database agnostic conversions performed. This should be a last resort because using, for example,
-
# MySQL specific terms will lock you to using that particular database engine or require you to
-
# change your call if you switch engines.
-
#
-
# # A simple SQL query spanning multiple tables
-
# Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
-
# # => [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]
-
#
-
# You can use the same string replacement techniques as you can with <tt>ActiveRecord::QueryMethods#where</tt>:
-
#
-
# Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date]
-
# Post.find_by_sql ["SELECT body FROM comments WHERE author = :user_id OR approved_by = :user_id", { :user_id => user_id }]
-
1
def find_by_sql(sql, binds = [])
-
result_set = connection.select_all(sanitize_sql(sql), "#{name} Load", binds)
-
column_types = {}
-
-
if result_set.respond_to? :column_types
-
column_types = result_set.column_types
-
else
-
ActiveSupport::Deprecation.warn "the object returned from `select_all` must respond to `column_types`"
-
end
-
-
result_set.map { |record| instantiate(record, column_types) }
-
end
-
-
# Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part.
-
# The use of this method should be restricted to complicated SQL queries that can't be executed
-
# using the ActiveRecord::Calculations class methods. Look into those before using this.
-
#
-
# ==== Parameters
-
#
-
# * +sql+ - An SQL statement which should return a count query from the database, see the example below.
-
#
-
# Product.count_by_sql "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id"
-
1
def count_by_sql(sql)
-
sql = sanitize_conditions(sql)
-
connection.select_value(sql, "#{name} Count").to_i
-
end
-
end
-
end
-
1
require "active_record"
-
1
require "rails"
-
1
require "active_model/railtie"
-
-
# For now, action_controller must always be present with
-
# rails, so let's make sure that it gets required before
-
# here. This is needed for correctly setting up the middleware.
-
# In the future, this might become an optional require.
-
1
require "action_controller/railtie"
-
-
1
module ActiveRecord
-
# = Active Record Railtie
-
1
class Railtie < Rails::Railtie # :nodoc:
-
1
config.active_record = ActiveSupport::OrderedOptions.new
-
-
1
config.app_generators.orm :active_record, :migration => true,
-
:timestamps => true
-
-
1
config.app_middleware.insert_after "::ActionDispatch::Callbacks",
-
"ActiveRecord::QueryCache"
-
-
1
config.app_middleware.insert_after "::ActionDispatch::Callbacks",
-
"ActiveRecord::ConnectionAdapters::ConnectionManagement"
-
-
1
config.action_dispatch.rescue_responses.merge!(
-
'ActiveRecord::RecordNotFound' => :not_found,
-
'ActiveRecord::StaleObjectError' => :conflict,
-
'ActiveRecord::RecordInvalid' => :unprocessable_entity,
-
'ActiveRecord::RecordNotSaved' => :unprocessable_entity
-
)
-
-
-
1
config.active_record.use_schema_cache_dump = true
-
1
config.active_record.maintain_test_schema = true
-
-
1
config.eager_load_namespaces << ActiveRecord
-
-
1
rake_tasks do
-
require "active_record/base"
-
-
namespace :db do
-
task :load_config do
-
ActiveRecord::Tasks::DatabaseTasks.database_configuration = Rails.application.config.database_configuration
-
-
if defined?(ENGINE_PATH) && engine = Rails::Engine.find(ENGINE_PATH)
-
if engine.paths['db/migrate'].existent
-
ActiveRecord::Tasks::DatabaseTasks.migrations_paths += engine.paths['db/migrate'].to_a
-
end
-
end
-
end
-
end
-
-
load "active_record/railties/databases.rake"
-
end
-
-
# When loading console, force ActiveRecord::Base to be loaded
-
# to avoid cross references when loading a constant for the
-
# first time. Also, make it output to STDERR.
-
1
console do |app|
-
require "active_record/railties/console_sandbox" if app.sandbox?
-
require "active_record/base"
-
console = ActiveSupport::Logger.new(STDERR)
-
Rails.logger.extend ActiveSupport::Logger.broadcast console
-
end
-
-
1
runner do
-
require "active_record/base"
-
end
-
-
1
initializer "active_record.initialize_timezone" do
-
1
ActiveSupport.on_load(:active_record) do
-
1
self.time_zone_aware_attributes = true
-
1
self.default_timezone = :utc
-
end
-
end
-
-
1
initializer "active_record.logger" do
-
2
ActiveSupport.on_load(:active_record) { self.logger ||= ::Rails.logger }
-
end
-
-
1
initializer "active_record.migration_error" do
-
1
if config.active_record.delete(:migration_error) == :page_load
-
config.app_middleware.insert_after "::ActionDispatch::Callbacks",
-
"ActiveRecord::Migration::CheckPending"
-
end
-
end
-
-
1
initializer "active_record.check_schema_cache_dump" do
-
1
if config.active_record.delete(:use_schema_cache_dump)
-
1
config.after_initialize do |app|
-
1
ActiveSupport.on_load(:active_record) do
-
1
filename = File.join(app.config.paths["db"].first, "schema_cache.dump")
-
-
1
if File.file?(filename)
-
cache = Marshal.load File.binread filename
-
if cache.version == ActiveRecord::Migrator.current_version
-
self.connection.schema_cache = cache
-
else
-
warn "Ignoring db/schema_cache.dump because it has expired. The current schema version is #{ActiveRecord::Migrator.current_version}, but the one in the cache is #{cache.version}."
-
end
-
end
-
end
-
end
-
end
-
end
-
-
1
initializer "active_record.set_configs" do |app|
-
1
ActiveSupport.on_load(:active_record) do
-
1
app.config.active_record.each do |k,v|
-
1
send "#{k}=", v
-
end
-
end
-
end
-
-
# This sets the database configuration from Configuration#database_configuration
-
# and then establishes the connection.
-
1
initializer "active_record.initialize_database" do |app|
-
1
ActiveSupport.on_load(:active_record) do
-
-
1
class ActiveRecord::NoDatabaseError
-
1
remove_possible_method :extend_message
-
1
def extend_message(message)
-
message << "Run `$ bin/rake db:create db:migrate` to create your database"
-
message
-
end
-
end
-
-
1
self.configurations = Rails.application.config.database_configuration
-
1
establish_connection
-
end
-
end
-
-
# Expose database runtime to controller for logging.
-
1
initializer "active_record.log_runtime" do
-
1
require "active_record/railties/controller_runtime"
-
1
ActiveSupport.on_load(:action_controller) do
-
1
include ActiveRecord::Railties::ControllerRuntime
-
end
-
end
-
-
1
initializer "active_record.set_reloader_hooks" do |app|
-
1
hook = app.config.reload_classes_only_on_change ? :to_prepare : :to_cleanup
-
-
1
ActiveSupport.on_load(:active_record) do
-
1
ActionDispatch::Reloader.send(hook) do
-
1
if ActiveRecord::Base.connected?
-
ActiveRecord::Base.clear_reloadable_connections!
-
ActiveRecord::Base.clear_cache!
-
end
-
end
-
end
-
end
-
-
1
initializer "active_record.add_watchable_files" do |app|
-
1
path = app.paths["db"].first
-
1
config.watchable_files.concat ["#{path}/schema.rb", "#{path}/structure.sql"]
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/attr_internal'
-
1
require 'active_record/log_subscriber'
-
-
1
module ActiveRecord
-
1
module Railties # :nodoc:
-
1
module ControllerRuntime #:nodoc:
-
1
extend ActiveSupport::Concern
-
-
1
protected
-
-
1
attr_internal :db_runtime
-
-
1
def process_action(action, *args)
-
# We also need to reset the runtime before each action
-
# because of queries in middleware or in cases we are streaming
-
# and it won't be cleaned up by the method below.
-
ActiveRecord::LogSubscriber.reset_runtime
-
super
-
end
-
-
1
def cleanup_view_runtime
-
if ActiveRecord::Base.connected?
-
db_rt_before_render = ActiveRecord::LogSubscriber.reset_runtime
-
self.db_runtime = (db_runtime || 0) + db_rt_before_render
-
runtime = super
-
db_rt_after_render = ActiveRecord::LogSubscriber.reset_runtime
-
self.db_runtime += db_rt_after_render
-
runtime - db_rt_after_render
-
else
-
super
-
end
-
end
-
-
1
def append_info_to_payload(payload)
-
super
-
if ActiveRecord::Base.connected?
-
payload[:db_runtime] = (db_runtime || 0) + ActiveRecord::LogSubscriber.reset_runtime
-
end
-
end
-
-
1
module ClassMethods # :nodoc:
-
1
def log_process_action(payload)
-
messages, db_runtime = super, payload[:db_runtime]
-
messages << ("ActiveRecord: %.1fms" % db_runtime.to_f) if db_runtime
-
messages
-
end
-
end
-
end
-
end
-
end
-
-
1
module ActiveRecord
-
1
module ReadonlyAttributes
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
class_attribute :_attr_readonly, instance_accessor: false
-
1
self._attr_readonly = []
-
end
-
-
1
module ClassMethods
-
# Attributes listed as readonly will be used to create a new record but update operations will
-
# ignore these fields.
-
1
def attr_readonly(*attributes)
-
self._attr_readonly = Set.new(attributes.map { |a| a.to_s }) + (self._attr_readonly || [])
-
end
-
-
# Returns an array of all the attributes that have been specified as readonly.
-
1
def readonly_attributes
-
self._attr_readonly
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
# = Active Record Reflection
-
1
module Reflection # :nodoc:
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
class_attribute :reflections
-
1
class_attribute :aggregate_reflections
-
1
self.reflections = {}
-
1
self.aggregate_reflections = {}
-
end
-
-
1
def self.create(macro, name, scope, options, ar)
-
8
case macro
-
when :has_many, :belongs_to, :has_one
-
8
klass = options[:through] ? ThroughReflection : AssociationReflection
-
when :composed_of
-
klass = AggregateReflection
-
end
-
-
8
klass.new(macro, name, scope, options, ar)
-
end
-
-
1
def self.add_reflection(ar, name, reflection)
-
8
ar.reflections = ar.reflections.merge(name => reflection)
-
end
-
-
1
def self.add_aggregate_reflection(ar, name, reflection)
-
ar.aggregate_reflections = ar.aggregate_reflections.merge(name => reflection)
-
end
-
-
# \Reflection enables to interrogate Active Record classes and objects
-
# about their associations and aggregations. This information can,
-
# for example, be used in a form builder that takes an Active Record object
-
# and creates input fields for all of the attributes depending on their type
-
# and displays the associations to other objects.
-
#
-
# MacroReflection class has info for AggregateReflection and AssociationReflection
-
# classes.
-
1
module ClassMethods
-
# Returns an array of AggregateReflection objects for all the aggregations in the class.
-
1
def reflect_on_all_aggregations
-
aggregate_reflections.values
-
end
-
-
# Returns the AggregateReflection object for the named +aggregation+ (use the symbol).
-
#
-
# Account.reflect_on_aggregation(:balance) # => the balance AggregateReflection
-
#
-
1
def reflect_on_aggregation(aggregation)
-
aggregate_reflections[aggregation]
-
end
-
-
# Returns an array of AssociationReflection objects for all the
-
# associations in the class. If you only want to reflect on a certain
-
# association type, pass in the symbol (<tt>:has_many</tt>, <tt>:has_one</tt>,
-
# <tt>:belongs_to</tt>) as the first parameter.
-
#
-
# Example:
-
#
-
# Account.reflect_on_all_associations # returns an array of all associations
-
# Account.reflect_on_all_associations(:has_many) # returns an array of all has_many associations
-
#
-
1
def reflect_on_all_associations(macro = nil)
-
association_reflections = reflections.values
-
macro ? association_reflections.select { |reflection| reflection.macro == macro } : association_reflections
-
end
-
-
# Returns the AssociationReflection object for the +association+ (use the symbol).
-
#
-
# Account.reflect_on_association(:owner) # returns the owner AssociationReflection
-
# Invoice.reflect_on_association(:line_items).macro # returns :has_many
-
#
-
1
def reflect_on_association(association)
-
5
reflections[association]
-
end
-
-
# Returns an array of AssociationReflection objects for all associations which have <tt>:autosave</tt> enabled.
-
1
def reflect_on_all_autosave_associations
-
reflections.values.select { |reflection| reflection.options[:autosave] }
-
end
-
end
-
-
# Base class for AggregateReflection and AssociationReflection. Objects of
-
# AggregateReflection and AssociationReflection are returned by the Reflection::ClassMethods.
-
#
-
# MacroReflection
-
# AggregateReflection
-
# AssociationReflection
-
# ThroughReflection
-
1
class MacroReflection
-
# Returns the name of the macro.
-
#
-
# <tt>composed_of :balance, class_name: 'Money'</tt> returns <tt>:balance</tt>
-
# <tt>has_many :clients</tt> returns <tt>:clients</tt>
-
1
attr_reader :name
-
-
# Returns the macro type.
-
#
-
# <tt>composed_of :balance, class_name: 'Money'</tt> returns <tt>:composed_of</tt>
-
# <tt>has_many :clients</tt> returns <tt>:has_many</tt>
-
1
attr_reader :macro
-
-
1
attr_reader :scope
-
-
# Returns the hash of options used for the macro.
-
#
-
# <tt>composed_of :balance, class_name: 'Money'</tt> returns <tt>{ class_name: "Money" }</tt>
-
# <tt>has_many :clients</tt> returns <tt>{}</tt>
-
1
attr_reader :options
-
-
1
attr_reader :active_record
-
-
1
attr_reader :plural_name # :nodoc:
-
-
1
def initialize(macro, name, scope, options, active_record)
-
8
@macro = macro
-
8
@name = name
-
8
@scope = scope
-
8
@options = options
-
8
@active_record = active_record
-
8
@klass = options[:class]
-
8
@plural_name = active_record.pluralize_table_names ?
-
name.to_s.pluralize : name.to_s
-
end
-
-
1
def autosave=(autosave)
-
5
@automatic_inverse_of = false
-
5
@options[:autosave] = autosave
-
end
-
-
# Returns the class for the macro.
-
#
-
# <tt>composed_of :balance, class_name: 'Money'</tt> returns the Money class
-
# <tt>has_many :clients</tt> returns the Client class
-
1
def klass
-
@klass ||= class_name.constantize
-
end
-
-
# Returns the class name for the macro.
-
#
-
# <tt>composed_of :balance, class_name: 'Money'</tt> returns <tt>'Money'</tt>
-
# <tt>has_many :clients</tt> returns <tt>'Client'</tt>
-
1
def class_name
-
@class_name ||= (options[:class_name] || derive_class_name).to_s
-
end
-
-
# Returns +true+ if +self+ and +other_aggregation+ have the same +name+ attribute, +active_record+ attribute,
-
# and +other_aggregation+ has an options hash assigned to it.
-
1
def ==(other_aggregation)
-
super ||
-
other_aggregation.kind_of?(self.class) &&
-
name == other_aggregation.name &&
-
!other_aggregation.options.nil? &&
-
active_record == other_aggregation.active_record
-
end
-
-
1
private
-
1
def derive_class_name
-
name.to_s.camelize
-
end
-
end
-
-
-
# Holds all the meta-data about an aggregation as it was specified in the
-
# Active Record class.
-
1
class AggregateReflection < MacroReflection #:nodoc:
-
1
def mapping
-
mapping = options[:mapping] || [name, name]
-
mapping.first.is_a?(Array) ? mapping : [mapping]
-
end
-
end
-
-
# Holds all the meta-data about an association as it was specified in the
-
# Active Record class.
-
1
class AssociationReflection < MacroReflection #:nodoc:
-
# Returns the target association's class.
-
#
-
# class Author < ActiveRecord::Base
-
# has_many :books
-
# end
-
#
-
# Author.reflect_on_association(:books).klass
-
# # => Book
-
#
-
# <b>Note:</b> Do not call +klass.new+ or +klass.create+ to instantiate
-
# a new association object. Use +build_association+ or +create_association+
-
# instead. This allows plugins to hook into association object creation.
-
1
def klass
-
@klass ||= active_record.send(:compute_type, class_name)
-
end
-
-
1
attr_reader :type, :foreign_type
-
-
1
def initialize(macro, name, scope, options, active_record)
-
8
super
-
8
@collection = :has_many == macro
-
8
@automatic_inverse_of = nil
-
8
@type = options[:as] && "#{options[:as]}_type"
-
8
@foreign_type = options[:foreign_type] || "#{name}_type"
-
8
@constructable = calculate_constructable(macro, options)
-
end
-
-
# Returns a new, unsaved instance of the associated class. +attributes+ will
-
# be passed to the class's constructor.
-
1
def build_association(attributes, &block)
-
klass.new(attributes, &block)
-
end
-
-
1
def constructable? # :nodoc:
-
@constructable
-
end
-
-
1
def table_name
-
klass.table_name
-
end
-
-
1
def quoted_table_name
-
klass.quoted_table_name
-
end
-
-
1
def join_table
-
@join_table ||= options[:join_table] || derive_join_table
-
end
-
-
1
def foreign_key
-
@foreign_key ||= options[:foreign_key] || derive_foreign_key
-
end
-
-
1
def primary_key_column
-
klass.columns_hash[klass.primary_key]
-
end
-
-
1
def association_foreign_key
-
@association_foreign_key ||= options[:association_foreign_key] || class_name.foreign_key
-
end
-
-
# klass option is necessary to support loading polymorphic associations
-
1
def association_primary_key(klass = nil)
-
options[:primary_key] || primary_key(klass || self.klass)
-
end
-
-
1
def active_record_primary_key
-
@active_record_primary_key ||= options[:primary_key] || primary_key(active_record)
-
end
-
-
1
def counter_cache_column
-
if options[:counter_cache] == true
-
"#{active_record.name.demodulize.underscore.pluralize}_count"
-
elsif options[:counter_cache]
-
options[:counter_cache].to_s
-
end
-
end
-
-
1
def check_validity!
-
check_validity_of_inverse!
-
end
-
-
1
def check_validity_of_inverse!
-
unless options[:polymorphic]
-
if has_inverse? && inverse_of.nil?
-
raise InverseOfAssociationNotFoundError.new(self)
-
end
-
end
-
end
-
-
1
def through_reflection
-
nil
-
end
-
-
1
def source_reflection
-
self
-
end
-
-
# A chain of reflections from this one back to the owner. For more see the explanation in
-
# ThroughReflection.
-
1
def chain
-
[self]
-
end
-
-
1
def nested?
-
false
-
end
-
-
# An array of arrays of scopes. Each item in the outside array corresponds to a reflection
-
# in the #chain.
-
1
def scope_chain
-
scope ? [[scope]] : [[]]
-
end
-
-
1
alias :source_macro :macro
-
-
1
def has_inverse?
-
inverse_name
-
end
-
-
1
def inverse_of
-
return unless inverse_name
-
-
@inverse_of ||= klass.reflect_on_association inverse_name
-
end
-
-
1
def polymorphic_inverse_of(associated_class)
-
if has_inverse?
-
if inverse_relationship = associated_class.reflect_on_association(options[:inverse_of])
-
inverse_relationship
-
else
-
raise InverseOfAssociationNotFoundError.new(self, associated_class)
-
end
-
end
-
end
-
-
# Returns whether or not this association reflection is for a collection
-
# association. Returns +true+ if the +macro+ is either +has_many+ or
-
# +has_and_belongs_to_many+, +false+ otherwise.
-
1
def collection?
-
18
@collection
-
end
-
-
# Returns whether or not the association should be validated as part of
-
# the parent's validation.
-
#
-
# Unless you explicitly disable validation with
-
# <tt>validate: false</tt>, validation will take place when:
-
#
-
# * you explicitly enable validation; <tt>validate: true</tt>
-
# * you use autosave; <tt>autosave: true</tt>
-
# * the association is a +has_many+ association
-
1
def validate?
-
13
!options[:validate].nil? ? options[:validate] : (options[:autosave] == true || macro == :has_many)
-
end
-
-
# Returns +true+ if +self+ is a +belongs_to+ reflection.
-
1
def belongs_to?
-
macro == :belongs_to
-
end
-
-
1
def association_class
-
case macro
-
when :belongs_to
-
if options[:polymorphic]
-
Associations::BelongsToPolymorphicAssociation
-
else
-
Associations::BelongsToAssociation
-
end
-
when :has_many
-
if options[:through]
-
Associations::HasManyThroughAssociation
-
else
-
Associations::HasManyAssociation
-
end
-
when :has_one
-
if options[:through]
-
Associations::HasOneThroughAssociation
-
else
-
Associations::HasOneAssociation
-
end
-
end
-
end
-
-
1
def polymorphic?
-
options.key? :polymorphic
-
end
-
-
1
VALID_AUTOMATIC_INVERSE_MACROS = [:has_many, :has_one, :belongs_to]
-
1
INVALID_AUTOMATIC_INVERSE_OPTIONS = [:conditions, :through, :polymorphic, :foreign_key]
-
-
1
protected
-
-
1
def actual_source_reflection # FIXME: this is a horrible name
-
self
-
end
-
-
1
private
-
-
1
def calculate_constructable(macro, options)
-
8
case macro
-
when :belongs_to
-
!options[:polymorphic]
-
when :has_one
-
!options[:through]
-
else
-
8
true
-
end
-
end
-
-
# Attempts to find the inverse association name automatically.
-
# If it cannot find a suitable inverse association name, it returns
-
# nil.
-
1
def inverse_name
-
options.fetch(:inverse_of) do
-
if @automatic_inverse_of == false
-
nil
-
else
-
@automatic_inverse_of ||= automatic_inverse_of
-
end
-
end
-
end
-
-
# returns either nil or the inverse association name that it finds.
-
1
def automatic_inverse_of
-
if can_find_inverse_of_automatically?(self)
-
inverse_name = ActiveSupport::Inflector.underscore(active_record.name).to_sym
-
-
begin
-
reflection = klass.reflect_on_association(inverse_name)
-
rescue NameError
-
# Give up: we couldn't compute the klass type so we won't be able
-
# to find any associations either.
-
reflection = false
-
end
-
-
if valid_inverse_reflection?(reflection)
-
return inverse_name
-
end
-
end
-
-
false
-
end
-
-
# Checks if the inverse reflection that is returned from the
-
# +automatic_inverse_of+ method is a valid reflection. We must
-
# make sure that the reflection's active_record name matches up
-
# with the current reflection's klass name.
-
#
-
# Note: klass will always be valid because when there's a NameError
-
# from calling +klass+, +reflection+ will already be set to false.
-
1
def valid_inverse_reflection?(reflection)
-
reflection &&
-
klass.name == reflection.active_record.name &&
-
can_find_inverse_of_automatically?(reflection)
-
end
-
-
# Checks to see if the reflection doesn't have any options that prevent
-
# us from being able to guess the inverse automatically. First, the
-
# <tt>inverse_of</tt> option cannot be set to false. Second, we must
-
# have <tt>has_many</tt>, <tt>has_one</tt>, <tt>belongs_to</tt> associations.
-
# Third, we must not have options such as <tt>:polymorphic</tt> or
-
# <tt>:foreign_key</tt> which prevent us from correctly guessing the
-
# inverse association.
-
#
-
# Anything with a scope can additionally ruin our attempt at finding an
-
# inverse, so we exclude reflections with scopes.
-
1
def can_find_inverse_of_automatically?(reflection)
-
reflection.options[:inverse_of] != false &&
-
VALID_AUTOMATIC_INVERSE_MACROS.include?(reflection.macro) &&
-
!INVALID_AUTOMATIC_INVERSE_OPTIONS.any? { |opt| reflection.options[opt] } &&
-
!reflection.scope
-
end
-
-
1
def derive_class_name
-
class_name = name.to_s.camelize
-
class_name = class_name.singularize if collection?
-
class_name
-
end
-
-
1
def derive_foreign_key
-
if belongs_to?
-
"#{name}_id"
-
elsif options[:as]
-
"#{options[:as]}_id"
-
else
-
active_record.name.foreign_key
-
end
-
end
-
-
1
def derive_join_table
-
[active_record.table_name, klass.table_name].sort.join("\0").gsub(/^(.*_)(.+)\0\1(.+)/, '\1\2_\3').gsub("\0", "_")
-
end
-
-
1
def primary_key(klass)
-
klass.primary_key || raise(UnknownPrimaryKey.new(klass))
-
end
-
end
-
-
# Holds all the meta-data about a :through association as it was specified
-
# in the Active Record class.
-
1
class ThroughReflection < AssociationReflection #:nodoc:
-
1
delegate :foreign_key, :foreign_type, :association_foreign_key,
-
:active_record_primary_key, :type, :to => :source_reflection
-
-
1
def initialize(macro, name, scope, options, active_record)
-
1
super
-
1
@source_reflection_name = options[:source]
-
end
-
-
# Returns the source of the through reflection. It checks both a singularized
-
# and pluralized form for <tt>:belongs_to</tt> or <tt>:has_many</tt>.
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :taggings
-
# has_many :tags, through: :taggings
-
# end
-
#
-
# class Tagging < ActiveRecord::Base
-
# belongs_to :post
-
# belongs_to :tag
-
# end
-
#
-
# tags_reflection = Post.reflect_on_association(:tags)
-
# tags_reflection.source_reflection
-
# # => <ActiveRecord::Reflection::AssociationReflection: @macro=:belongs_to, @name=:tag, @active_record=Tagging, @plural_name="tags">
-
#
-
1
def source_reflection
-
through_reflection.klass.reflect_on_association(source_reflection_name)
-
end
-
-
# Returns the AssociationReflection object specified in the <tt>:through</tt> option
-
# of a HasManyThrough or HasOneThrough association.
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :taggings
-
# has_many :tags, through: :taggings
-
# end
-
#
-
# tags_reflection = Post.reflect_on_association(:tags)
-
# tags_reflection.through_reflection
-
# # => <ActiveRecord::Reflection::AssociationReflection: @macro=:has_many, @name=:taggings, @active_record=Post, @plural_name="taggings">
-
#
-
1
def through_reflection
-
active_record.reflect_on_association(options[:through])
-
end
-
-
# Returns an array of reflections which are involved in this association. Each item in the
-
# array corresponds to a table which will be part of the query for this association.
-
#
-
# The chain is built by recursively calling #chain on the source reflection and the through
-
# reflection. The base case for the recursion is a normal association, which just returns
-
# [self] as its #chain.
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :taggings
-
# has_many :tags, through: :taggings
-
# end
-
#
-
# tags_reflection = Post.reflect_on_association(:tags)
-
# tags_reflection.chain
-
# # => [<ActiveRecord::Reflection::ThroughReflection: @macro=:has_many, @name=:tags, @options={:through=>:taggings}, @active_record=Post>,
-
# <ActiveRecord::Reflection::AssociationReflection: @macro=:has_many, @name=:taggings, @options={}, @active_record=Post>]
-
#
-
1
def chain
-
@chain ||= begin
-
a = source_reflection.chain
-
b = through_reflection.chain
-
chain = a + b
-
chain[0] = self # Use self so we don't lose the information from :source_type
-
chain
-
end
-
end
-
-
# Consider the following example:
-
#
-
# class Person
-
# has_many :articles
-
# has_many :comment_tags, through: :articles
-
# end
-
#
-
# class Article
-
# has_many :comments
-
# has_many :comment_tags, through: :comments, source: :tags
-
# end
-
#
-
# class Comment
-
# has_many :tags
-
# end
-
#
-
# There may be scopes on Person.comment_tags, Article.comment_tags and/or Comment.tags,
-
# but only Comment.tags will be represented in the #chain. So this method creates an array
-
# of scopes corresponding to the chain.
-
1
def scope_chain
-
@scope_chain ||= begin
-
scope_chain = source_reflection.scope_chain.map(&:dup)
-
-
# Add to it the scope from this reflection (if any)
-
scope_chain.first << scope if scope
-
-
through_scope_chain = through_reflection.scope_chain.map(&:dup)
-
-
if options[:source_type]
-
through_scope_chain.first <<
-
through_reflection.klass.where(foreign_type => options[:source_type])
-
end
-
-
# Recursively fill out the rest of the array from the through reflection
-
scope_chain + through_scope_chain
-
end
-
end
-
-
# The macro used by the source association
-
1
def source_macro
-
source_reflection.source_macro
-
end
-
-
# A through association is nested if there would be more than one join table
-
1
def nested?
-
chain.length > 2
-
end
-
-
# We want to use the klass from this reflection, rather than just delegate straight to
-
# the source_reflection, because the source_reflection may be polymorphic. We still
-
# need to respect the source_reflection's :primary_key option, though.
-
1
def association_primary_key(klass = nil)
-
# Get the "actual" source reflection if the immediate source reflection has a
-
# source reflection itself
-
actual_source_reflection.options[:primary_key] || primary_key(klass || self.klass)
-
end
-
-
# Gets an array of possible <tt>:through</tt> source reflection names in both singular and plural form.
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :taggings
-
# has_many :tags, through: :taggings
-
# end
-
#
-
# tags_reflection = Post.reflect_on_association(:tags)
-
# tags_reflection.source_reflection_names
-
# # => [:tag, :tags]
-
#
-
1
def source_reflection_names
-
(options[:source] ? [options[:source]] : [name.to_s.singularize, name]).collect { |n| n.to_sym }.uniq
-
end
-
-
1
def source_reflection_name # :nodoc:
-
return @source_reflection_name if @source_reflection_name
-
-
names = [name.to_s.singularize, name].collect { |n| n.to_sym }.uniq
-
names = names.find_all { |n|
-
through_reflection.klass.reflect_on_association(n)
-
}
-
-
if names.length > 1
-
example_options = options.dup
-
example_options[:source] = source_reflection_names.first
-
ActiveSupport::Deprecation.warn <<-eowarn
-
Ambiguous source reflection for through association. Please specify a :source
-
directive on your declaration like:
-
-
class #{active_record.name} < ActiveRecord::Base
-
#{macro} :#{name}, #{example_options}
-
end
-
-
eowarn
-
end
-
-
@source_reflection_name = names.first
-
end
-
-
1
def source_options
-
source_reflection.options
-
end
-
-
1
def through_options
-
through_reflection.options
-
end
-
-
1
def check_validity!
-
if through_reflection.nil?
-
raise HasManyThroughAssociationNotFoundError.new(active_record.name, self)
-
end
-
-
if through_reflection.options[:polymorphic]
-
raise HasManyThroughAssociationPolymorphicThroughError.new(active_record.name, self)
-
end
-
-
if source_reflection.nil?
-
raise HasManyThroughSourceAssociationNotFoundError.new(self)
-
end
-
-
if options[:source_type] && source_reflection.options[:polymorphic].nil?
-
raise HasManyThroughAssociationPointlessSourceTypeError.new(active_record.name, self, source_reflection)
-
end
-
-
if source_reflection.options[:polymorphic] && options[:source_type].nil?
-
raise HasManyThroughAssociationPolymorphicSourceError.new(active_record.name, self, source_reflection)
-
end
-
-
if macro == :has_one && through_reflection.collection?
-
raise HasOneThroughCantAssociateThroughCollection.new(active_record.name, self, through_reflection)
-
end
-
-
check_validity_of_inverse!
-
end
-
-
1
protected
-
-
1
def actual_source_reflection # FIXME: this is a horrible name
-
source_reflection.actual_source_reflection
-
end
-
-
1
private
-
1
def derive_class_name
-
# get the class_name of the belongs_to association of the through reflection
-
options[:source_type] || source_reflection.class_name
-
end
-
end
-
end
-
end
-
# -*- coding: utf-8 -*-
-
-
1
module ActiveRecord
-
# = Active Record Relation
-
1
class Relation
-
1
JoinOperation = Struct.new(:relation, :join_class, :on)
-
-
1
MULTI_VALUE_METHODS = [:includes, :eager_load, :preload, :select, :group,
-
:order, :joins, :where, :having, :bind, :references,
-
:extending, :unscope]
-
-
1
SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :from, :reordering,
-
:reverse_order, :distinct, :create_with, :uniq]
-
-
1
VALUE_METHODS = MULTI_VALUE_METHODS + SINGLE_VALUE_METHODS
-
-
1
include FinderMethods, Calculations, SpawnMethods, QueryMethods, Batches, Explain, Delegation
-
-
1
attr_reader :table, :klass, :loaded
-
1
alias :model :klass
-
1
alias :loaded? :loaded
-
-
1
def initialize(klass, table, values = {})
-
@klass = klass
-
@table = table
-
@values = values
-
@offsets = {}
-
@loaded = false
-
end
-
-
1
def initialize_copy(other)
-
# This method is a hot spot, so for now, use Hash[] to dup the hash.
-
# https://bugs.ruby-lang.org/issues/7166
-
@values = Hash[@values]
-
@values[:bind] = @values[:bind].dup if @values.key? :bind
-
reset
-
end
-
-
1
def insert(values) # :nodoc:
-
primary_key_value = nil
-
-
if primary_key && Hash === values
-
primary_key_value = values[values.keys.find { |k|
-
k.name == primary_key
-
}]
-
-
if !primary_key_value && connection.prefetch_primary_key?(klass.table_name)
-
primary_key_value = connection.next_sequence_value(klass.sequence_name)
-
values[klass.arel_table[klass.primary_key]] = primary_key_value
-
end
-
end
-
-
im = arel.create_insert
-
im.into @table
-
-
substitutes, binds = substitute_values values
-
-
if values.empty? # empty insert
-
im.values = Arel.sql(connection.empty_insert_statement_value)
-
else
-
im.insert substitutes
-
end
-
-
@klass.connection.insert(
-
im,
-
'SQL',
-
primary_key,
-
primary_key_value,
-
nil,
-
binds)
-
end
-
-
1
def update_record(values, id, id_was) # :nodoc:
-
substitutes, binds = substitute_values values
-
um = @klass.unscoped.where(@klass.arel_table[@klass.primary_key].eq(id_was || id)).arel.compile_update(substitutes, @klass.primary_key)
-
-
@klass.connection.update(
-
um,
-
'SQL',
-
binds)
-
end
-
-
1
def substitute_values(values) # :nodoc:
-
substitutes = values.sort_by { |arel_attr,_| arel_attr.name }
-
binds = substitutes.map do |arel_attr, value|
-
[@klass.columns_hash[arel_attr.name], value]
-
end
-
-
substitutes.each_with_index do |tuple, i|
-
tuple[1] = @klass.connection.substitute_at(binds[i][0], i)
-
end
-
-
[substitutes, binds]
-
end
-
-
# Initializes new record from relation while maintaining the current
-
# scope.
-
#
-
# Expects arguments in the same format as +Base.new+.
-
#
-
# users = User.where(name: 'DHH')
-
# user = users.new # => #<User id: nil, name: "DHH", created_at: nil, updated_at: nil>
-
#
-
# You can also pass a block to new with the new record as argument:
-
#
-
# user = users.new { |user| user.name = 'Oscar' }
-
# user.name # => Oscar
-
1
def new(*args, &block)
-
scoping { @klass.new(*args, &block) }
-
end
-
-
1
alias build new
-
-
# Tries to create a new record with the same scoped attributes
-
# defined in the relation. Returns the initialized object if validation fails.
-
#
-
# Expects arguments in the same format as +Base.create+.
-
#
-
# ==== Examples
-
# users = User.where(name: 'Oscar')
-
# users.create # #<User id: 3, name: "oscar", ...>
-
#
-
# users.create(name: 'fxn')
-
# users.create # #<User id: 4, name: "fxn", ...>
-
#
-
# users.create { |user| user.name = 'tenderlove' }
-
# # #<User id: 5, name: "tenderlove", ...>
-
#
-
# users.create(name: nil) # validation on name
-
# # #<User id: nil, name: nil, ...>
-
1
def create(*args, &block)
-
scoping { @klass.create(*args, &block) }
-
end
-
-
# Similar to #create, but calls +create!+ on the base class. Raises
-
# an exception if a validation error occurs.
-
#
-
# Expects arguments in the same format as <tt>Base.create!</tt>.
-
1
def create!(*args, &block)
-
scoping { @klass.create!(*args, &block) }
-
end
-
-
1
def first_or_create(attributes = nil, &block) # :nodoc:
-
first || create(attributes, &block)
-
end
-
-
1
def first_or_create!(attributes = nil, &block) # :nodoc:
-
first || create!(attributes, &block)
-
end
-
-
1
def first_or_initialize(attributes = nil, &block) # :nodoc:
-
first || new(attributes, &block)
-
end
-
-
# Finds the first record with the given attributes, or creates a record
-
# with the attributes if one is not found:
-
#
-
# # Find the first user named "Penélope" or create a new one.
-
# User.find_or_create_by(first_name: 'Penélope')
-
# # => #<User id: 1, first_name: "Penélope", last_name: nil>
-
#
-
# # Find the first user named "Penélope" or create a new one.
-
# # We already have one so the existing record will be returned.
-
# User.find_or_create_by(first_name: 'Penélope')
-
# # => #<User id: 1, first_name: "Penélope", last_name: nil>
-
#
-
# # Find the first user named "Scarlett" or create a new one with
-
# # a particular last name.
-
# User.create_with(last_name: 'Johansson').find_or_create_by(first_name: 'Scarlett')
-
# # => #<User id: 2, first_name: "Scarlett", last_name: "Johansson">
-
#
-
# This method accepts a block, which is passed down to +create+. The last example
-
# above can be alternatively written this way:
-
#
-
# # Find the first user named "Scarlett" or create a new one with a
-
# # different last name.
-
# User.find_or_create_by(first_name: 'Scarlett') do |user|
-
# user.last_name = 'Johansson'
-
# end
-
# # => #<User id: 2, first_name: "Scarlett", last_name: "Johansson">
-
#
-
# This method always returns a record, but if creation was attempted and
-
# failed due to validation errors it won't be persisted, you get what
-
# +create+ returns in such situation.
-
#
-
# Please note *this method is not atomic*, it runs first a SELECT, and if
-
# there are no results an INSERT is attempted. If there are other threads
-
# or processes there is a race condition between both calls and it could
-
# be the case that you end up with two similar records.
-
#
-
# Whether that is a problem or not depends on the logic of the
-
# application, but in the particular case in which rows have a UNIQUE
-
# constraint an exception may be raised, just retry:
-
#
-
# begin
-
# CreditAccount.find_or_create_by(user_id: user.id)
-
# rescue ActiveRecord::RecordNotUnique
-
# retry
-
# end
-
#
-
1
def find_or_create_by(attributes, &block)
-
find_by(attributes) || create(attributes, &block)
-
end
-
-
# Like <tt>find_or_create_by</tt>, but calls <tt>create!</tt> so an exception
-
# is raised if the created record is invalid.
-
1
def find_or_create_by!(attributes, &block)
-
find_by(attributes) || create!(attributes, &block)
-
end
-
-
# Like <tt>find_or_create_by</tt>, but calls <tt>new</tt> instead of <tt>create</tt>.
-
1
def find_or_initialize_by(attributes, &block)
-
find_by(attributes) || new(attributes, &block)
-
end
-
-
# Runs EXPLAIN on the query or queries triggered by this relation and
-
# returns the result as a string. The string is formatted imitating the
-
# ones printed by the database shell.
-
#
-
# Note that this method actually runs the queries, since the results of some
-
# are needed by the next ones when eager loading is going on.
-
#
-
# Please see further details in the
-
# {Active Record Query Interface guide}[http://guides.rubyonrails.org/active_record_querying.html#running-explain].
-
1
def explain
-
exec_explain(collecting_queries_for_explain { exec_queries })
-
end
-
-
# Converts relation objects to Array.
-
1
def to_a
-
load
-
@records
-
end
-
-
1
def as_json(options = nil) #:nodoc:
-
to_a.as_json(options)
-
end
-
-
# Returns size of the records.
-
1
def size
-
loaded? ? @records.length : count
-
end
-
-
# Returns true if there are no records.
-
1
def empty?
-
return @records.empty? if loaded?
-
-
if limit_value == 0
-
true
-
else
-
# FIXME: This count is not compatible with #select('authors.*') or other select narrows
-
c = count
-
c.respond_to?(:zero?) ? c.zero? : c.empty?
-
end
-
end
-
-
# Returns true if there are any records.
-
1
def any?
-
if block_given?
-
to_a.any? { |*block_args| yield(*block_args) }
-
else
-
!empty?
-
end
-
end
-
-
# Returns true if there is more than one record.
-
1
def many?
-
if block_given?
-
to_a.many? { |*block_args| yield(*block_args) }
-
else
-
limit_value ? to_a.many? : size > 1
-
end
-
end
-
-
# Scope all queries to the current scope.
-
#
-
# Comment.where(post_id: 1).scoping do
-
# Comment.first
-
# end
-
# # => SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = 1 ORDER BY "comments"."id" ASC LIMIT 1
-
#
-
# Please check unscoped if you want to remove all previous scopes (including
-
# the default_scope) during the execution of a block.
-
1
def scoping
-
previous, klass.current_scope = klass.current_scope, self
-
yield
-
ensure
-
klass.current_scope = previous
-
end
-
-
# Updates all records with details given if they match a set of conditions supplied, limits and order can
-
# also be supplied. This method constructs a single SQL UPDATE statement and sends it straight to the
-
# database. It does not instantiate the involved models and it does not trigger Active Record callbacks
-
# or validations.
-
#
-
# ==== Parameters
-
#
-
# * +updates+ - A string, array, or hash representing the SET part of an SQL statement.
-
#
-
# ==== Examples
-
#
-
# # Update all customers with the given attributes
-
# Customer.update_all wants_email: true
-
#
-
# # Update all books with 'Rails' in their title
-
# Book.where('title LIKE ?', '%Rails%').update_all(author: 'David')
-
#
-
# # Update all books that match conditions, but limit it to 5 ordered by date
-
# Book.where('title LIKE ?', '%Rails%').order(:created_at).limit(5).update_all(author: 'David')
-
1
def update_all(updates)
-
raise ArgumentError, "Empty list of attributes to change" if updates.blank?
-
-
stmt = Arel::UpdateManager.new(arel.engine)
-
-
stmt.set Arel.sql(@klass.send(:sanitize_sql_for_assignment, updates))
-
stmt.table(table)
-
stmt.key = table[primary_key]
-
-
if joins_values.any?
-
@klass.connection.join_to_update(stmt, arel)
-
else
-
stmt.take(arel.limit)
-
stmt.order(*arel.orders)
-
stmt.wheres = arel.constraints
-
end
-
-
@klass.connection.update stmt, 'SQL', bind_values
-
end
-
-
# Updates an object (or multiple objects) and saves it to the database, if validations pass.
-
# The resulting object is returned whether the object was saved successfully to the database or not.
-
#
-
# ==== Parameters
-
#
-
# * +id+ - This should be the id or an array of ids to be updated.
-
# * +attributes+ - This should be a hash of attributes or an array of hashes.
-
#
-
# ==== Examples
-
#
-
# # Updates one record
-
# Person.update(15, user_name: 'Samuel', group: 'expert')
-
#
-
# # Updates multiple records
-
# people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
-
# Person.update(people.keys, people.values)
-
1
def update(id, attributes)
-
if id.is_a?(Array)
-
id.map.with_index { |one_id, idx| update(one_id, attributes[idx]) }
-
else
-
object = find(id)
-
object.update(attributes)
-
object
-
end
-
end
-
-
# Destroys the records matching +conditions+ by instantiating each
-
# record and calling its +destroy+ method. Each object's callbacks are
-
# executed (including <tt>:dependent</tt> association options). Returns the
-
# collection of objects that were destroyed; each will be frozen, to
-
# reflect that no changes should be made (since they can't be persisted).
-
#
-
# Note: Instantiation, callback execution, and deletion of each
-
# record can be time consuming when you're removing many records at
-
# once. It generates at least one SQL +DELETE+ query per record (or
-
# possibly more, to enforce your callbacks). If you want to delete many
-
# rows quickly, without concern for their associations or callbacks, use
-
# +delete_all+ instead.
-
#
-
# ==== Parameters
-
#
-
# * +conditions+ - A string, array, or hash that specifies which records
-
# to destroy. If omitted, all records are destroyed. See the
-
# Conditions section in the introduction to ActiveRecord::Base for
-
# more information.
-
#
-
# ==== Examples
-
#
-
# Person.destroy_all("last_login < '2004-04-04'")
-
# Person.destroy_all(status: "inactive")
-
# Person.where(age: 0..18).destroy_all
-
1
def destroy_all(conditions = nil)
-
if conditions
-
where(conditions).destroy_all
-
else
-
to_a.each {|object| object.destroy }.tap { reset }
-
end
-
end
-
-
# Destroy an object (or multiple objects) that has the given id. The object is instantiated first,
-
# therefore all callbacks and filters are fired off before the object is deleted. This method is
-
# less efficient than ActiveRecord#delete but allows cleanup methods and other actions to be run.
-
#
-
# This essentially finds the object (or multiple objects) with the given id, creates a new object
-
# from the attributes, and then calls destroy on it.
-
#
-
# ==== Parameters
-
#
-
# * +id+ - Can be either an Integer or an Array of Integers.
-
#
-
# ==== Examples
-
#
-
# # Destroy a single object
-
# Todo.destroy(1)
-
#
-
# # Destroy multiple objects
-
# todos = [1,2,3]
-
# Todo.destroy(todos)
-
1
def destroy(id)
-
if id.is_a?(Array)
-
id.map { |one_id| destroy(one_id) }
-
else
-
find(id).destroy
-
end
-
end
-
-
# Deletes the records matching +conditions+ without instantiating the records
-
# first, and hence not calling the +destroy+ method nor invoking callbacks. This
-
# is a single SQL DELETE statement that goes straight to the database, much more
-
# efficient than +destroy_all+. Be careful with relations though, in particular
-
# <tt>:dependent</tt> rules defined on associations are not honored. Returns the
-
# number of rows affected.
-
#
-
# Post.delete_all("person_id = 5 AND (category = 'Something' OR category = 'Else')")
-
# Post.delete_all(["person_id = ? AND (category = ? OR category = ?)", 5, 'Something', 'Else'])
-
# Post.where(person_id: 5).where(category: ['Something', 'Else']).delete_all
-
#
-
# Both calls delete the affected posts all at once with a single DELETE statement.
-
# If you need to destroy dependent associations or call your <tt>before_*</tt> or
-
# +after_destroy+ callbacks, use the +destroy_all+ method instead.
-
#
-
# If a limit scope is supplied, +delete_all+ raises an ActiveRecord error:
-
#
-
# Post.limit(100).delete_all
-
# # => ActiveRecord::ActiveRecordError: delete_all doesn't support limit scope
-
1
def delete_all(conditions = nil)
-
raise ActiveRecordError.new("delete_all doesn't support limit scope") if self.limit_value
-
-
if conditions
-
where(conditions).delete_all
-
else
-
stmt = Arel::DeleteManager.new(arel.engine)
-
stmt.from(table)
-
-
if joins_values.any?
-
@klass.connection.join_to_delete(stmt, arel, table[primary_key])
-
else
-
stmt.wheres = arel.constraints
-
end
-
-
affected = @klass.connection.delete(stmt, 'SQL', bind_values)
-
-
reset
-
affected
-
end
-
end
-
-
# Deletes the row with a primary key matching the +id+ argument, using a
-
# SQL +DELETE+ statement, and returns the number of rows deleted. Active
-
# Record objects are not instantiated, so the object's callbacks are not
-
# executed, including any <tt>:dependent</tt> association options.
-
#
-
# You can delete multiple rows at once by passing an Array of <tt>id</tt>s.
-
#
-
# Note: Although it is often much faster than the alternative,
-
# <tt>#destroy</tt>, skipping callbacks might bypass business logic in
-
# your application that ensures referential integrity or performs other
-
# essential jobs.
-
#
-
# ==== Examples
-
#
-
# # Delete a single row
-
# Todo.delete(1)
-
#
-
# # Delete multiple rows
-
# Todo.delete([2,3,4])
-
1
def delete(id_or_array)
-
where(primary_key => id_or_array).delete_all
-
end
-
-
# Causes the records to be loaded from the database if they have not
-
# been loaded already. You can use this if for some reason you need
-
# to explicitly load some records before actually using them. The
-
# return value is the relation itself, not the records.
-
#
-
# Post.where(published: true).load # => #<ActiveRecord::Relation>
-
1
def load
-
exec_queries unless loaded?
-
-
self
-
end
-
-
# Forces reloading of relation.
-
1
def reload
-
reset
-
load
-
end
-
-
1
def reset
-
@last = @to_sql = @order_clause = @scope_for_create = @arel = @loaded = nil
-
@should_eager_load = @join_dependency = nil
-
@records = []
-
@offsets = {}
-
self
-
end
-
-
# Returns sql statement for the relation.
-
#
-
# User.where(name: 'Oscar').to_sql
-
# # => SELECT "users".* FROM "users" WHERE "users"."name" = 'Oscar'
-
1
def to_sql
-
@to_sql ||= begin
-
relation = self
-
connection = klass.connection
-
visitor = connection.visitor
-
-
if eager_loading?
-
find_with_associations { |rel| relation = rel }
-
end
-
-
ast = relation.arel.ast
-
binds = relation.bind_values.dup
-
visitor.accept(ast) do
-
connection.quote(*binds.shift.reverse)
-
end
-
end
-
end
-
-
# Returns a hash of where conditions.
-
#
-
# User.where(name: 'Oscar').where_values_hash
-
# # => {name: "Oscar"}
-
1
def where_values_hash
-
equalities = where_values.grep(Arel::Nodes::Equality).find_all { |node|
-
node.left.relation.name == table_name
-
}
-
-
binds = Hash[bind_values.find_all(&:first).map { |column, v| [column.name, v] }]
-
-
Hash[equalities.map { |where|
-
name = where.left.name
-
[name, binds.fetch(name.to_s) { where.right }]
-
}]
-
end
-
-
1
def scope_for_create
-
@scope_for_create ||= where_values_hash.merge(create_with_value)
-
end
-
-
# Returns true if relation needs eager loading.
-
1
def eager_loading?
-
@should_eager_load ||=
-
eager_load_values.any? ||
-
includes_values.any? && (joined_includes_values.any? || references_eager_loaded_tables?)
-
end
-
-
# Joins that are also marked for preloading. In which case we should just eager load them.
-
# Note that this is a naive implementation because we could have strings and symbols which
-
# represent the same association, but that aren't matched by this. Also, we could have
-
# nested hashes which partially match, e.g. { a: :b } & { a: [:b, :c] }
-
1
def joined_includes_values
-
includes_values & joins_values
-
end
-
-
# +uniq+ and +uniq!+ are silently deprecated. +uniq_value+ delegates to +distinct_value+
-
# to maintain backwards compatibility. Use +distinct_value+ instead.
-
1
def uniq_value
-
distinct_value
-
end
-
-
# Compares two relations for equality.
-
1
def ==(other)
-
case other
-
when Relation
-
other.to_sql == to_sql
-
when Array
-
to_a == other
-
end
-
end
-
-
1
def pretty_print(q)
-
q.pp(self.to_a)
-
end
-
-
# Returns true if relation is blank.
-
1
def blank?
-
to_a.blank?
-
end
-
-
1
def values
-
Hash[@values]
-
end
-
-
1
def inspect
-
entries = to_a.take([limit_value, 11].compact.min).map!(&:inspect)
-
entries[10] = '...' if entries.size == 11
-
-
"#<#{self.class.name} [#{entries.join(', ')}]>"
-
end
-
-
1
private
-
-
1
def exec_queries
-
@records = eager_loading? ? find_with_associations : @klass.find_by_sql(arel, bind_values)
-
-
preload = preload_values
-
preload += includes_values unless eager_loading?
-
preloader = ActiveRecord::Associations::Preloader.new
-
preload.each do |associations|
-
preloader.preload @records, associations
-
end
-
-
@records.each { |record| record.readonly! } if readonly_value
-
-
@loaded = true
-
@records
-
end
-
-
1
def references_eager_loaded_tables?
-
joined_tables = arel.join_sources.map do |join|
-
if join.is_a?(Arel::Nodes::StringJoin)
-
tables_in_string(join.left)
-
else
-
[join.left.table_name, join.left.table_alias]
-
end
-
end
-
-
joined_tables += [table.name, table.table_alias]
-
-
# always convert table names to downcase as in Oracle quoted table names are in uppercase
-
joined_tables = joined_tables.flatten.compact.map { |t| t.downcase }.uniq
-
-
(references_values - joined_tables).any?
-
end
-
-
1
def tables_in_string(string)
-
return [] if string.blank?
-
# always convert table names to downcase as in Oracle quoted table names are in uppercase
-
# ignore raw_sql_ that is used by Oracle adapter as alias for limit/offset subqueries
-
string.scan(/([a-zA-Z_][.\w]+).?\./).flatten.map{ |s| s.downcase }.uniq - ['raw_sql_']
-
end
-
end
-
end
-
-
1
module ActiveRecord
-
1
module Batches
-
# Looping through a collection of records from the database
-
# (using the +all+ method, for example) is very inefficient
-
# since it will try to instantiate all the objects at once.
-
#
-
# In that case, batch processing methods allow you to work
-
# with the records in batches, thereby greatly reducing memory consumption.
-
#
-
# The #find_each method uses #find_in_batches with a batch size of 1000 (or as
-
# specified by the +:batch_size+ option).
-
#
-
# Person.find_each do |person|
-
# person.do_awesome_stuff
-
# end
-
#
-
# Person.where("age > 21").find_each do |person|
-
# person.party_all_night!
-
# end
-
#
-
# If you do not provide a block to #find_each, it will return an Enumerator
-
# for chaining with other methods:
-
#
-
# Person.find_each.with_index do |person, index|
-
# person.award_trophy(index + 1)
-
# end
-
#
-
# ==== Options
-
# * <tt>:batch_size</tt> - Specifies the size of the batch. Default to 1000.
-
# * <tt>:start</tt> - Specifies the starting point for the batch processing.
-
# This is especially useful if you want multiple workers dealing with
-
# the same processing queue. You can make worker 1 handle all the records
-
# between id 0 and 10,000 and worker 2 handle from 10,000 and beyond
-
# (by setting the +:start+ option on that worker).
-
#
-
# # Let's process for a batch of 2000 records, skipping the first 2000 rows
-
# Person.find_each(start: 2000, batch_size: 2000) do |person|
-
# person.party_all_night!
-
# end
-
#
-
# NOTE: It's not possible to set the order. That is automatically set to
-
# ascending on the primary key ("id ASC") to make the batch ordering
-
# work. This also means that this method only works with integer-based
-
# primary keys.
-
#
-
# NOTE: You can't set the limit either, that's used to control
-
# the batch sizes.
-
1
def find_each(options = {})
-
if block_given?
-
find_in_batches(options) do |records|
-
records.each { |record| yield record }
-
end
-
else
-
enum_for :find_each, options do
-
options[:start] ? where(table[primary_key].gteq(options[:start])).size : size
-
end
-
end
-
end
-
-
# Yields each batch of records that was found by the find +options+ as
-
# an array.
-
#
-
# Person.where("age > 21").find_in_batches do |group|
-
# sleep(50) # Make sure it doesn't get too crowded in there!
-
# group.each { |person| person.party_all_night! }
-
# end
-
#
-
# If you do not provide a block to #find_in_batches, it will return an Enumerator
-
# for chaining with other methods:
-
#
-
# Person.find_in_batches.with_index do |group, batch|
-
# puts "Processing group ##{batch}"
-
# group.each(&:recover_from_last_night!)
-
# end
-
#
-
# To be yielded each record one by one, use #find_each instead.
-
#
-
# ==== Options
-
# * <tt>:batch_size</tt> - Specifies the size of the batch. Default to 1000.
-
# * <tt>:start</tt> - Specifies the starting point for the batch processing.
-
# This is especially useful if you want multiple workers dealing with
-
# the same processing queue. You can make worker 1 handle all the records
-
# between id 0 and 10,000 and worker 2 handle from 10,000 and beyond
-
# (by setting the +:start+ option on that worker).
-
#
-
# # Let's process the next 2000 records
-
# Person.find_in_batches(start: 2000, batch_size: 2000) do |group|
-
# group.each { |person| person.party_all_night! }
-
# end
-
#
-
# NOTE: It's not possible to set the order. That is automatically set to
-
# ascending on the primary key ("id ASC") to make the batch ordering
-
# work. This also means that this method only works with integer-based
-
# primary keys.
-
#
-
# NOTE: You can't set the limit either, that's used to control
-
# the batch sizes.
-
1
def find_in_batches(options = {})
-
options.assert_valid_keys(:start, :batch_size)
-
-
relation = self
-
start = options[:start]
-
batch_size = options[:batch_size] || 1000
-
-
unless block_given?
-
return to_enum(:find_in_batches, options) do
-
total = start ? where(table[primary_key].gteq(start)).size : size
-
(total - 1).div(batch_size) + 1
-
end
-
end
-
-
if logger && (arel.orders.present? || arel.taken.present?)
-
logger.warn("Scoped order and limit are ignored, it's forced to be batch order and batch size")
-
end
-
-
relation = relation.reorder(batch_order).limit(batch_size)
-
records = start ? relation.where(table[primary_key].gteq(start)).to_a : relation.to_a
-
-
while records.any?
-
records_size = records.size
-
primary_key_offset = records.last.id
-
raise "Primary key not included in the custom select clause" unless primary_key_offset
-
-
yield records
-
-
break if records_size < batch_size
-
-
records = relation.where(table[primary_key].gt(primary_key_offset)).to_a
-
end
-
end
-
-
1
private
-
-
1
def batch_order
-
"#{quoted_table_name}.#{quoted_primary_key} ASC"
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Calculations
-
# Count the records.
-
#
-
# Person.count
-
# # => the total count of all people
-
#
-
# Person.count(:age)
-
# # => returns the total count of all people whose age is present in database
-
#
-
# Person.count(:all)
-
# # => performs a COUNT(*) (:all is an alias for '*')
-
#
-
# Person.distinct.count(:age)
-
# # => counts the number of different age values
-
#
-
# If +count+ is used with +group+, it returns a Hash whose keys represent the aggregated column,
-
# and the values are the respective amounts:
-
#
-
# Person.group(:city).count
-
# # => { 'Rome' => 5, 'Paris' => 3 }
-
1
def count(column_name = nil, options = {})
-
# TODO: Remove options argument as soon we remove support to
-
# activerecord-deprecated_finders.
-
column_name, options = nil, column_name if column_name.is_a?(Hash)
-
calculate(:count, column_name, options)
-
end
-
-
# Calculates the average value on a given column. Returns +nil+ if there's
-
# no row. See +calculate+ for examples with options.
-
#
-
# Person.average(:age) # => 35.8
-
1
def average(column_name, options = {})
-
# TODO: Remove options argument as soon we remove support to
-
# activerecord-deprecated_finders.
-
calculate(:average, column_name, options)
-
end
-
-
# Calculates the minimum value on a given column. The value is returned
-
# with the same data type of the column, or +nil+ if there's no row. See
-
# +calculate+ for examples with options.
-
#
-
# Person.minimum(:age) # => 7
-
1
def minimum(column_name, options = {})
-
# TODO: Remove options argument as soon we remove support to
-
# activerecord-deprecated_finders.
-
calculate(:minimum, column_name, options)
-
end
-
-
# Calculates the maximum value on a given column. The value is returned
-
# with the same data type of the column, or +nil+ if there's no row. See
-
# +calculate+ for examples with options.
-
#
-
# Person.maximum(:age) # => 93
-
1
def maximum(column_name, options = {})
-
# TODO: Remove options argument as soon we remove support to
-
# activerecord-deprecated_finders.
-
calculate(:maximum, column_name, options)
-
end
-
-
# Calculates the sum of values on a given column. The value is returned
-
# with the same data type of the column, 0 if there's no row. See
-
# +calculate+ for examples with options.
-
#
-
# Person.sum(:age) # => 4562
-
1
def sum(*args)
-
calculate(:sum, *args)
-
end
-
-
# This calculates aggregate values in the given column. Methods for count, sum, average,
-
# minimum, and maximum have been added as shortcuts.
-
#
-
# There are two basic forms of output:
-
#
-
# * Single aggregate value: The single value is type cast to Fixnum for COUNT, Float
-
# for AVG, and the given column's type for everything else.
-
#
-
# * Grouped values: This returns an ordered hash of the values and groups them. It
-
# takes either a column name, or the name of a belongs_to association.
-
#
-
# values = Person.group('last_name').maximum(:age)
-
# puts values["Drake"]
-
# # => 43
-
#
-
# drake = Family.find_by(last_name: 'Drake')
-
# values = Person.group(:family).maximum(:age) # Person belongs_to :family
-
# puts values[drake]
-
# # => 43
-
#
-
# values.each do |family, max_age|
-
# ...
-
# end
-
#
-
# Person.calculate(:count, :all) # The same as Person.count
-
# Person.average(:age) # SELECT AVG(age) FROM people...
-
#
-
# # Selects the minimum age for any family without any minors
-
# Person.group(:last_name).having("min(age) > 17").minimum(:age)
-
#
-
# Person.sum("2 * age")
-
1
def calculate(operation, column_name, options = {})
-
# TODO: Remove options argument as soon we remove support to
-
# activerecord-deprecated_finders.
-
if column_name.is_a?(Symbol) && attribute_alias?(column_name)
-
column_name = attribute_alias(column_name)
-
end
-
-
if has_include?(column_name)
-
construct_relation_for_association_calculations.calculate(operation, column_name, options)
-
else
-
perform_calculation(operation, column_name, options)
-
end
-
end
-
-
# Use <tt>pluck</tt> as a shortcut to select one or more attributes without
-
# loading a bunch of records just to grab the attributes you want.
-
#
-
# Person.pluck(:name)
-
#
-
# instead of
-
#
-
# Person.all.map(&:name)
-
#
-
# Pluck returns an <tt>Array</tt> of attribute values type-casted to match
-
# the plucked column names, if they can be deduced. Plucking an SQL fragment
-
# returns String values by default.
-
#
-
# Person.pluck(:id)
-
# # SELECT people.id FROM people
-
# # => [1, 2, 3]
-
#
-
# Person.pluck(:id, :name)
-
# # SELECT people.id, people.name FROM people
-
# # => [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']]
-
#
-
# Person.pluck('DISTINCT role')
-
# # SELECT DISTINCT role FROM people
-
# # => ['admin', 'member', 'guest']
-
#
-
# Person.where(age: 21).limit(5).pluck(:id)
-
# # SELECT people.id FROM people WHERE people.age = 21 LIMIT 5
-
# # => [2, 3]
-
#
-
# Person.pluck('DATEDIFF(updated_at, created_at)')
-
# # SELECT DATEDIFF(updated_at, created_at) FROM people
-
# # => ['0', '27761', '173']
-
#
-
1
def pluck(*column_names)
-
column_names.map! do |column_name|
-
if column_name.is_a?(Symbol) && attribute_alias?(column_name)
-
attribute_alias(column_name)
-
else
-
column_name.to_s
-
end
-
end
-
-
if has_include?(column_names.first)
-
construct_relation_for_association_calculations.pluck(*column_names)
-
else
-
relation = spawn
-
relation.select_values = column_names.map { |cn|
-
columns_hash.key?(cn) ? arel_table[cn] : cn
-
}
-
result = klass.connection.select_all(relation.arel, nil, bind_values)
-
columns = result.columns.map do |key|
-
klass.column_types.fetch(key) {
-
result.column_types.fetch(key) { result.identity_type }
-
}
-
end
-
-
result = result.map do |attributes|
-
values = klass.initialize_attributes(attributes).values
-
-
columns.zip(values).map { |column, value| column.type_cast value }
-
end
-
columns.one? ? result.map!(&:first) : result
-
end
-
end
-
-
# Pluck all the ID's for the relation using the table's primary key
-
#
-
# Person.ids # SELECT people.id FROM people
-
# Person.joins(:companies).ids # SELECT people.id FROM people INNER JOIN companies ON companies.person_id = people.id
-
1
def ids
-
pluck primary_key
-
end
-
-
1
private
-
-
1
def has_include?(column_name)
-
eager_loading? || (includes_values.present? && (column_name || references_eager_loaded_tables?))
-
end
-
-
1
def perform_calculation(operation, column_name, options = {})
-
# TODO: Remove options argument as soon we remove support to
-
# activerecord-deprecated_finders.
-
operation = operation.to_s.downcase
-
-
# If #count is used with #distinct / #uniq it is considered distinct. (eg. relation.distinct.count)
-
distinct = self.distinct_value
-
-
if operation == "count"
-
column_name ||= select_for_count
-
-
unless arel.ast.grep(Arel::Nodes::OuterJoin).empty?
-
distinct = true
-
end
-
-
column_name = primary_key if column_name == :all && distinct
-
distinct = nil if column_name =~ /\s*DISTINCT[\s(]+/i
-
end
-
-
if group_values.any?
-
execute_grouped_calculation(operation, column_name, distinct)
-
else
-
execute_simple_calculation(operation, column_name, distinct)
-
end
-
end
-
-
1
def aggregate_column(column_name)
-
if @klass.column_names.include?(column_name.to_s)
-
Arel::Attribute.new(@klass.unscoped.table, column_name)
-
else
-
Arel.sql(column_name == :all ? "*" : column_name.to_s)
-
end
-
end
-
-
1
def operation_over_aggregate_column(column, operation, distinct)
-
operation == 'count' ? column.count(distinct) : column.send(operation)
-
end
-
-
1
def execute_simple_calculation(operation, column_name, distinct) #:nodoc:
-
# Postgresql doesn't like ORDER BY when there are no GROUP BY
-
relation = unscope(:order)
-
-
column_alias = column_name
-
-
if operation == "count" && (relation.limit_value || relation.offset_value)
-
# Shortcut when limit is zero.
-
return 0 if relation.limit_value == 0
-
-
query_builder = build_count_subquery(relation, column_name, distinct)
-
else
-
column = aggregate_column(column_name)
-
-
select_value = operation_over_aggregate_column(column, operation, distinct)
-
-
column_alias = select_value.alias
-
relation.select_values = [select_value]
-
-
query_builder = relation.arel
-
end
-
-
result = @klass.connection.select_all(query_builder, nil, relation.bind_values)
-
row = result.first
-
value = row && row.values.first
-
column = result.column_types.fetch(column_alias) do
-
column_for(column_name)
-
end
-
-
type_cast_calculated_value(value, column, operation)
-
end
-
-
1
def execute_grouped_calculation(operation, column_name, distinct) #:nodoc:
-
group_attrs = group_values
-
-
if group_attrs.first.respond_to?(:to_sym)
-
association = @klass.reflect_on_association(group_attrs.first.to_sym)
-
associated = group_attrs.size == 1 && association && association.macro == :belongs_to # only count belongs_to associations
-
group_fields = Array(associated ? association.foreign_key : group_attrs)
-
else
-
group_fields = group_attrs
-
end
-
-
group_aliases = group_fields.map { |field|
-
column_alias_for(field)
-
}
-
group_columns = group_aliases.zip(group_fields).map { |aliaz,field|
-
[aliaz, field]
-
}
-
-
group = group_fields
-
-
if operation == 'count' && column_name == :all
-
aggregate_alias = 'count_all'
-
else
-
aggregate_alias = column_alias_for([operation, column_name].join(' '))
-
end
-
-
select_values = [
-
operation_over_aggregate_column(
-
aggregate_column(column_name),
-
operation,
-
distinct).as(aggregate_alias)
-
]
-
select_values += select_values unless having_values.empty?
-
-
select_values.concat group_fields.zip(group_aliases).map { |field,aliaz|
-
if field.respond_to?(:as)
-
field.as(aliaz)
-
else
-
"#{field} AS #{aliaz}"
-
end
-
}
-
-
relation = except(:group)
-
relation.group_values = group
-
relation.select_values = select_values
-
-
calculated_data = @klass.connection.select_all(relation, nil, bind_values)
-
-
if association
-
key_ids = calculated_data.collect { |row| row[group_aliases.first] }
-
key_records = association.klass.base_class.find(key_ids)
-
key_records = Hash[key_records.map { |r| [r.id, r] }]
-
end
-
-
Hash[calculated_data.map do |row|
-
key = group_columns.map { |aliaz, col_name|
-
column = calculated_data.column_types.fetch(aliaz) do
-
column_for(col_name)
-
end
-
type_cast_calculated_value(row[aliaz], column)
-
}
-
key = key.first if key.size == 1
-
key = key_records[key] if associated
-
-
column_type = calculated_data.column_types.fetch(aggregate_alias) { column_for(column_name) }
-
[key, type_cast_calculated_value(row[aggregate_alias], column_type, operation)]
-
end]
-
end
-
-
# Converts the given keys to the value that the database adapter returns as
-
# a usable column name:
-
#
-
# column_alias_for("users.id") # => "users_id"
-
# column_alias_for("sum(id)") # => "sum_id"
-
# column_alias_for("count(distinct users.id)") # => "count_distinct_users_id"
-
# column_alias_for("count(*)") # => "count_all"
-
# column_alias_for("count", "id") # => "count_id"
-
1
def column_alias_for(keys)
-
if keys.respond_to? :name
-
keys = "#{keys.relation.name}.#{keys.name}"
-
end
-
-
table_name = keys.to_s.downcase
-
table_name.gsub!(/\*/, 'all')
-
table_name.gsub!(/\W+/, ' ')
-
table_name.strip!
-
table_name.gsub!(/ +/, '_')
-
-
@klass.connection.table_alias_for(table_name)
-
end
-
-
1
def column_for(field)
-
field_name = field.respond_to?(:name) ? field.name.to_s : field.to_s.split('.').last
-
@klass.columns_hash[field_name]
-
end
-
-
1
def type_cast_calculated_value(value, column, operation = nil)
-
case operation
-
when 'count' then value.to_i
-
when 'sum' then type_cast_using_column(value || 0, column)
-
when 'average' then value.respond_to?(:to_d) ? value.to_d : value
-
else type_cast_using_column(value, column)
-
end
-
end
-
-
1
def type_cast_using_column(value, column)
-
column ? column.type_cast(value) : value
-
end
-
-
# TODO: refactor to allow non-string `select_values` (eg. Arel nodes).
-
1
def select_for_count
-
if select_values.present?
-
select_values.join(", ")
-
else
-
:all
-
end
-
end
-
-
1
def build_count_subquery(relation, column_name, distinct)
-
column_alias = Arel.sql('count_column')
-
subquery_alias = Arel.sql('subquery_for_count')
-
-
aliased_column = aggregate_column(column_name == :all ? 1 : column_name).as(column_alias)
-
relation.select_values = [aliased_column]
-
subquery = relation.arel.as(subquery_alias)
-
-
sm = Arel::SelectManager.new relation.engine
-
select_value = operation_over_aggregate_column(column_alias, 'count', distinct)
-
sm.project(select_value).from(subquery)
-
end
-
end
-
end
-
1
require 'set'
-
1
require 'active_support/concern'
-
1
require 'active_support/deprecation'
-
-
1
module ActiveRecord
-
1
module Delegation # :nodoc:
-
1
module DelegateCache
-
1
def relation_delegate_class(klass) # :nodoc:
-
@relation_delegate_cache[klass]
-
end
-
-
1
def initialize_relation_delegate_cache # :nodoc:
-
2
@relation_delegate_cache = cache = {}
-
[
-
ActiveRecord::Relation,
-
ActiveRecord::Associations::CollectionProxy,
-
ActiveRecord::AssociationRelation
-
2
].each do |klass|
-
6
delegate = Class.new(klass) {
-
6
include ClassSpecificRelation
-
}
-
6
const_set klass.name.gsub('::', '_'), delegate
-
6
cache[klass] = delegate
-
end
-
end
-
-
1
def inherited(child_class)
-
2
child_class.initialize_relation_delegate_cache
-
2
super
-
end
-
end
-
-
1
extend ActiveSupport::Concern
-
-
# This module creates compiled delegation methods dynamically at runtime, which makes
-
# subsequent calls to that method faster by avoiding method_missing. The delegations
-
# may vary depending on the klass of a relation, so we create a subclass of Relation
-
# for each different klass, and the delegations are compiled into that subclass only.
-
-
1
BLACKLISTED_ARRAY_METHODS = [
-
:compact!, :flatten!, :reject!, :reverse!, :rotate!, :map!,
-
:shuffle!, :slice!, :sort!, :sort_by!, :delete_if,
-
:keep_if, :pop, :shift, :delete_at, :compact
-
].to_set # :nodoc:
-
-
1
delegate :to_xml, :to_yaml, :length, :collect, :map, :each, :all?, :include?, :to_ary, to: :to_a
-
-
1
delegate :table_name, :quoted_table_name, :primary_key, :quoted_primary_key,
-
:connection, :columns_hash, :to => :klass
-
-
1
module ClassSpecificRelation # :nodoc:
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
6
@delegation_mutex = Mutex.new
-
end
-
-
1
module ClassMethods # :nodoc:
-
1
def name
-
superclass.name
-
end
-
-
1
def delegate_to_scoped_klass(method)
-
@delegation_mutex.synchronize do
-
return if method_defined?(method)
-
-
if method.to_s =~ /\A[a-zA-Z_]\w*[!?]?\z/
-
module_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{method}(*args, &block)
-
scoping { @klass.#{method}(*args, &block) }
-
end
-
RUBY
-
else
-
define_method method do |*args, &block|
-
scoping { @klass.public_send(method, *args, &block) }
-
end
-
end
-
end
-
end
-
-
1
def delegate(method, opts = {})
-
@delegation_mutex.synchronize do
-
return if method_defined?(method)
-
super
-
end
-
end
-
end
-
-
1
protected
-
-
1
def method_missing(method, *args, &block)
-
if @klass.respond_to?(method)
-
self.class.delegate_to_scoped_klass(method)
-
scoping { @klass.public_send(method, *args, &block) }
-
elsif arel.respond_to?(method)
-
self.class.delegate method, :to => :arel
-
arel.public_send(method, *args, &block)
-
else
-
super
-
end
-
end
-
end
-
-
1
module ClassMethods # :nodoc:
-
1
def create(klass, *args)
-
relation_class_for(klass).new(klass, *args)
-
end
-
-
1
private
-
-
1
def relation_class_for(klass)
-
klass.relation_delegate_class(self)
-
end
-
end
-
-
1
def respond_to?(method, include_private = false)
-
super || @klass.respond_to?(method, include_private) ||
-
array_delegable?(method) ||
-
arel.respond_to?(method, include_private)
-
end
-
-
1
protected
-
-
1
def array_delegable?(method)
-
Array.method_defined?(method) && BLACKLISTED_ARRAY_METHODS.exclude?(method)
-
end
-
-
1
def method_missing(method, *args, &block)
-
if @klass.respond_to?(method)
-
scoping { @klass.public_send(method, *args, &block) }
-
elsif array_delegable?(method)
-
to_a.public_send(method, *args, &block)
-
elsif arel.respond_to?(method)
-
arel.public_send(method, *args, &block)
-
else
-
super
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module FinderMethods
-
1
ONE_AS_ONE = '1 AS one'
-
-
# Find by id - This can either be a specific id (1), a list of ids (1, 5, 6), or an array of ids ([5, 6, 10]).
-
# If no record can be found for all of the listed ids, then RecordNotFound will be raised. If the primary key
-
# is an integer, find by id coerces its arguments using +to_i+.
-
#
-
# Person.find(1) # returns the object for ID = 1
-
# Person.find("1") # returns the object for ID = 1
-
# Person.find("31-sarah") # returns the object for ID = 31
-
# Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
-
# Person.find([7, 17]) # returns an array for objects with IDs in (7, 17)
-
# Person.find([1]) # returns an array for the object with ID = 1
-
# Person.where("administrator = 1").order("created_on DESC").find(1)
-
#
-
# <tt>ActiveRecord::RecordNotFound</tt> will be raised if one or more ids are not found.
-
#
-
# NOTE: The returned records may not be in the same order as the ids you
-
# provide since database rows are unordered. You'd need to provide an explicit <tt>order</tt>
-
# option if you want the results are sorted.
-
#
-
# ==== Find with lock
-
#
-
# Example for find with a lock: Imagine two concurrent transactions:
-
# each will read <tt>person.visits == 2</tt>, add 1 to it, and save, resulting
-
# in two saves of <tt>person.visits = 3</tt>. By locking the row, the second
-
# transaction has to wait until the first is finished; we get the
-
# expected <tt>person.visits == 4</tt>.
-
#
-
# Person.transaction do
-
# person = Person.lock(true).find(1)
-
# person.visits += 1
-
# person.save!
-
# end
-
#
-
# ==== Variations of +find+
-
#
-
# Person.where(name: 'Spartacus', rating: 4)
-
# # returns a chainable list (which can be empty).
-
#
-
# Person.find_by(name: 'Spartacus', rating: 4)
-
# # returns the first item or nil.
-
#
-
# Person.where(name: 'Spartacus', rating: 4).first_or_initialize
-
# # returns the first item or returns a new instance (requires you call .save to persist against the database).
-
#
-
# Person.where(name: 'Spartacus', rating: 4).first_or_create
-
# # returns the first item or creates it and returns it, available since Rails 3.2.1.
-
#
-
# ==== Alternatives for +find+
-
#
-
# Person.where(name: 'Spartacus', rating: 4).exists?(conditions = :none)
-
# # returns a boolean indicating if any record with the given conditions exist.
-
#
-
# Person.where(name: 'Spartacus', rating: 4).select("field1, field2, field3")
-
# # returns a chainable list of instances with only the mentioned fields.
-
#
-
# Person.where(name: 'Spartacus', rating: 4).ids
-
# # returns an Array of ids, available since Rails 3.2.1.
-
#
-
# Person.where(name: 'Spartacus', rating: 4).pluck(:field1, :field2)
-
# # returns an Array of the required fields, available since Rails 3.1.
-
1
def find(*args)
-
if block_given?
-
to_a.find { |*block_args| yield(*block_args) }
-
else
-
find_with_ids(*args)
-
end
-
end
-
-
# Finds the first record matching the specified conditions. There
-
# is no implied ordering so if order matters, you should specify it
-
# yourself.
-
#
-
# If no record is found, returns <tt>nil</tt>.
-
#
-
# Post.find_by name: 'Spartacus', rating: 4
-
# Post.find_by "published_at < ?", 2.weeks.ago
-
1
def find_by(*args)
-
where(*args).take
-
end
-
-
# Like <tt>find_by</tt>, except that if no record is found, raises
-
# an <tt>ActiveRecord::RecordNotFound</tt> error.
-
1
def find_by!(*args)
-
where(*args).take!
-
end
-
-
# Gives a record (or N records if a parameter is supplied) without any implied
-
# order. The order will depend on the database implementation.
-
# If an order is supplied it will be respected.
-
#
-
# Person.take # returns an object fetched by SELECT * FROM people LIMIT 1
-
# Person.take(5) # returns 5 objects fetched by SELECT * FROM people LIMIT 5
-
# Person.where(["name LIKE '%?'", name]).take
-
1
def take(limit = nil)
-
limit ? limit(limit).to_a : find_take
-
end
-
-
# Same as +take+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
-
# is found. Note that <tt>take!</tt> accepts no arguments.
-
1
def take!
-
take or raise RecordNotFound
-
end
-
-
# Find the first record (or first N records if a parameter is supplied).
-
# If no order is defined it will order by primary key.
-
#
-
# Person.first # returns the first object fetched by SELECT * FROM people
-
# Person.where(["user_name = ?", user_name]).first
-
# Person.where(["user_name = :u", { u: user_name }]).first
-
# Person.order("created_on DESC").offset(5).first
-
# Person.first(3) # returns the first three objects fetched by SELECT * FROM people LIMIT 3
-
#
-
# ==== Rails 3
-
#
-
# Person.first # SELECT "people".* FROM "people" LIMIT 1
-
#
-
# NOTE: Rails 3 may not order this query by the primary key and the order
-
# will depend on the database implementation. In order to ensure that behavior,
-
# use <tt>User.order(:id).first</tt> instead.
-
#
-
# ==== Rails 4
-
#
-
# Person.first # SELECT "people".* FROM "people" ORDER BY "people"."id" ASC LIMIT 1
-
#
-
1
def first(limit = nil)
-
if limit
-
find_nth_with_limit(offset_value, limit)
-
else
-
find_nth(:first, offset_value)
-
end
-
end
-
-
# Same as +first+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
-
# is found. Note that <tt>first!</tt> accepts no arguments.
-
1
def first!
-
first or raise RecordNotFound
-
end
-
-
# Find the last record (or last N records if a parameter is supplied).
-
# If no order is defined it will order by primary key.
-
#
-
# Person.last # returns the last object fetched by SELECT * FROM people
-
# Person.where(["user_name = ?", user_name]).last
-
# Person.order("created_on DESC").offset(5).last
-
# Person.last(3) # returns the last three objects fetched by SELECT * FROM people.
-
#
-
# Take note that in that last case, the results are sorted in ascending order:
-
#
-
# [#<Person id:2>, #<Person id:3>, #<Person id:4>]
-
#
-
# and not:
-
#
-
# [#<Person id:4>, #<Person id:3>, #<Person id:2>]
-
1
def last(limit = nil)
-
if limit
-
if order_values.empty? && primary_key
-
order(arel_table[primary_key].desc).limit(limit).reverse
-
else
-
to_a.last(limit)
-
end
-
else
-
find_last
-
end
-
end
-
-
# Same as +last+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
-
# is found. Note that <tt>last!</tt> accepts no arguments.
-
1
def last!
-
last or raise RecordNotFound
-
end
-
-
# Find the second record.
-
# If no order is defined it will order by primary key.
-
#
-
# Person.second # returns the second object fetched by SELECT * FROM people
-
# Person.offset(3).second # returns the second object from OFFSET 3 (which is OFFSET 4)
-
# Person.where(["user_name = :u", { u: user_name }]).second
-
1
def second
-
find_nth(:second, offset_value ? offset_value + 1 : 1)
-
end
-
-
# Same as +second+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
-
# is found.
-
1
def second!
-
second or raise RecordNotFound
-
end
-
-
# Find the third record.
-
# If no order is defined it will order by primary key.
-
#
-
# Person.third # returns the third object fetched by SELECT * FROM people
-
# Person.offset(3).third # returns the third object from OFFSET 3 (which is OFFSET 5)
-
# Person.where(["user_name = :u", { u: user_name }]).third
-
1
def third
-
find_nth(:third, offset_value ? offset_value + 2 : 2)
-
end
-
-
# Same as +third+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
-
# is found.
-
1
def third!
-
third or raise RecordNotFound
-
end
-
-
# Find the fourth record.
-
# If no order is defined it will order by primary key.
-
#
-
# Person.fourth # returns the fourth object fetched by SELECT * FROM people
-
# Person.offset(3).fourth # returns the fourth object from OFFSET 3 (which is OFFSET 6)
-
# Person.where(["user_name = :u", { u: user_name }]).fourth
-
1
def fourth
-
find_nth(:fourth, offset_value ? offset_value + 3 : 3)
-
end
-
-
# Same as +fourth+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
-
# is found.
-
1
def fourth!
-
fourth or raise RecordNotFound
-
end
-
-
# Find the fifth record.
-
# If no order is defined it will order by primary key.
-
#
-
# Person.fifth # returns the fifth object fetched by SELECT * FROM people
-
# Person.offset(3).fifth # returns the fifth object from OFFSET 3 (which is OFFSET 7)
-
# Person.where(["user_name = :u", { u: user_name }]).fifth
-
1
def fifth
-
find_nth(:fifth, offset_value ? offset_value + 4 : 4)
-
end
-
-
# Same as +fifth+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
-
# is found.
-
1
def fifth!
-
fifth or raise RecordNotFound
-
end
-
-
# Find the forty-second record. Also known as accessing "the reddit".
-
# If no order is defined it will order by primary key.
-
#
-
# Person.forty_two # returns the forty-second object fetched by SELECT * FROM people
-
# Person.offset(3).forty_two # returns the fifth object from OFFSET 3 (which is OFFSET 44)
-
# Person.where(["user_name = :u", { u: user_name }]).forty_two
-
1
def forty_two
-
find_nth(:forty_two, offset_value ? offset_value + 41 : 41)
-
end
-
-
# Same as +forty_two+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
-
# is found.
-
1
def forty_two!
-
forty_two or raise RecordNotFound
-
end
-
-
# Returns +true+ if a record exists in the table that matches the +id+ or
-
# conditions given, or +false+ otherwise. The argument can take six forms:
-
#
-
# * Integer - Finds the record with this primary key.
-
# * String - Finds the record with a primary key corresponding to this
-
# string (such as <tt>'5'</tt>).
-
# * Array - Finds the record that matches these +find+-style conditions
-
# (such as <tt>['name LIKE ?', "%#{query}%"]</tt>).
-
# * Hash - Finds the record that matches these +find+-style conditions
-
# (such as <tt>{name: 'David'}</tt>).
-
# * +false+ - Returns always +false+.
-
# * No args - Returns +false+ if the table is empty, +true+ otherwise.
-
#
-
# For more information about specifying conditions as a hash or array,
-
# see the Conditions section in the introduction to <tt>ActiveRecord::Base</tt>.
-
#
-
# Note: You can't pass in a condition as a string (like <tt>name =
-
# 'Jamie'</tt>), since it would be sanitized and then queried against
-
# the primary key column, like <tt>id = 'name = \'Jamie\''</tt>.
-
#
-
# Person.exists?(5)
-
# Person.exists?('5')
-
# Person.exists?(['name LIKE ?', "%#{query}%"])
-
# Person.exists?(id: [1, 4, 8])
-
# Person.exists?(name: 'David')
-
# Person.exists?(false)
-
# Person.exists?
-
1
def exists?(conditions = :none)
-
conditions = conditions.id if Base === conditions
-
return false if !conditions
-
-
relation = apply_join_dependency(self, construct_join_dependency)
-
return false if ActiveRecord::NullRelation === relation
-
-
relation = relation.except(:select, :order).select(ONE_AS_ONE).limit(1)
-
-
case conditions
-
when Array, Hash
-
relation = relation.where(conditions)
-
else
-
relation = relation.where(table[primary_key].eq(conditions)) if conditions != :none
-
end
-
-
connection.select_value(relation, "#{name} Exists", relation.bind_values) ? true : false
-
end
-
-
# This method is called whenever no records are found with either a single
-
# id or multiple ids and raises a +ActiveRecord::RecordNotFound+ exception.
-
#
-
# The error message is different depending on whether a single id or
-
# multiple ids are provided. If multiple ids are provided, then the number
-
# of results obtained should be provided in the +result_size+ argument and
-
# the expected number of results should be provided in the +expected_size+
-
# argument.
-
1
def raise_record_not_found_exception!(ids, result_size, expected_size) #:nodoc:
-
conditions = arel.where_sql
-
conditions = " [#{conditions}]" if conditions
-
-
if Array(ids).size == 1
-
error = "Couldn't find #{@klass.name} with '#{primary_key}'=#{ids}#{conditions}"
-
else
-
error = "Couldn't find all #{@klass.name.pluralize} with '#{primary_key}': "
-
error << "(#{ids.join(", ")})#{conditions} (found #{result_size} results, but was looking for #{expected_size})"
-
end
-
-
raise RecordNotFound, error
-
end
-
-
1
private
-
-
1
def find_with_associations
-
join_dependency = construct_join_dependency
-
-
aliases = join_dependency.aliases
-
relation = select aliases.columns
-
relation = apply_join_dependency(relation, join_dependency)
-
-
if block_given?
-
yield relation
-
else
-
if ActiveRecord::NullRelation === relation
-
[]
-
else
-
rows = connection.select_all(relation.arel, 'SQL', relation.bind_values.dup)
-
join_dependency.instantiate(rows, aliases)
-
end
-
end
-
end
-
-
1
def construct_join_dependency(joins = [])
-
including = eager_load_values + includes_values
-
ActiveRecord::Associations::JoinDependency.new(@klass, including, joins)
-
end
-
-
1
def construct_relation_for_association_calculations
-
from = arel.froms.first
-
if Arel::Table === from
-
apply_join_dependency(self, construct_join_dependency)
-
else
-
# FIXME: as far as I can tell, `from` will always be an Arel::Table.
-
# There are no tests that test this branch, but presumably it's
-
# possible for `from` to be a list?
-
apply_join_dependency(self, construct_join_dependency(from))
-
end
-
end
-
-
1
def apply_join_dependency(relation, join_dependency)
-
relation = relation.except(:includes, :eager_load, :preload)
-
relation = relation.joins join_dependency
-
-
if using_limitable_reflections?(join_dependency.reflections)
-
relation
-
else
-
if relation.limit_value
-
limited_ids = limited_ids_for(relation)
-
limited_ids.empty? ? relation.none! : relation.where!(table[primary_key].in(limited_ids))
-
end
-
relation.except(:limit, :offset)
-
end
-
end
-
-
1
def limited_ids_for(relation)
-
values = @klass.connection.columns_for_distinct(
-
"#{quoted_table_name}.#{quoted_primary_key}", relation.order_values)
-
-
relation = relation.except(:select).select(values).distinct!
-
-
id_rows = @klass.connection.select_all(relation.arel, 'SQL', relation.bind_values)
-
id_rows.map {|row| row[primary_key]}
-
end
-
-
1
def using_limitable_reflections?(reflections)
-
reflections.none? { |r| r.collection? }
-
end
-
-
1
protected
-
-
1
def find_with_ids(*ids)
-
raise UnknownPrimaryKey.new(@klass) if primary_key.nil?
-
-
expects_array = ids.first.kind_of?(Array)
-
return ids.first if expects_array && ids.first.empty?
-
-
ids = ids.flatten.compact.uniq
-
-
case ids.size
-
when 0
-
raise RecordNotFound, "Couldn't find #{@klass.name} without an ID"
-
when 1
-
result = find_one(ids.first)
-
expects_array ? [ result ] : result
-
else
-
find_some(ids)
-
end
-
end
-
-
1
def find_one(id)
-
id = id.id if ActiveRecord::Base === id
-
-
column = columns_hash[primary_key]
-
substitute = connection.substitute_at(column, bind_values.length)
-
relation = where(table[primary_key].eq(substitute))
-
relation.bind_values += [[column, id]]
-
record = relation.take
-
-
raise_record_not_found_exception!(id, 0, 1) unless record
-
-
record
-
end
-
-
1
def find_some(ids)
-
result = where(table[primary_key].in(ids)).to_a
-
-
expected_size =
-
if limit_value && ids.size > limit_value
-
limit_value
-
else
-
ids.size
-
end
-
-
# 11 ids with limit 3, offset 9 should give 2 results.
-
if offset_value && (ids.size - offset_value < expected_size)
-
expected_size = ids.size - offset_value
-
end
-
-
if result.size == expected_size
-
result
-
else
-
raise_record_not_found_exception!(ids, result.size, expected_size)
-
end
-
end
-
-
1
def find_take
-
if loaded?
-
@records.first
-
else
-
@take ||= limit(1).to_a.first
-
end
-
end
-
-
1
def find_nth(ordinal, offset)
-
if loaded?
-
@records.send(ordinal)
-
else
-
@offsets[offset] ||= find_nth_with_limit(offset, 1).first
-
end
-
end
-
-
1
def find_nth_with_limit(offset, limit)
-
if order_values.empty? && primary_key
-
order(arel_table[primary_key].asc).limit(limit).offset(offset).to_a
-
else
-
limit(limit).offset(offset).to_a
-
end
-
end
-
-
1
def find_last
-
if loaded?
-
@records.last
-
else
-
@last ||=
-
if limit_value
-
to_a.last
-
else
-
reverse_order.limit(1).to_a.first
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/keys'
-
1
require "set"
-
-
1
module ActiveRecord
-
1
class Relation
-
1
class HashMerger # :nodoc:
-
1
attr_reader :relation, :hash
-
-
1
def initialize(relation, hash)
-
hash.assert_valid_keys(*Relation::VALUE_METHODS)
-
-
@relation = relation
-
@hash = hash
-
end
-
-
1
def merge
-
Merger.new(relation, other).merge
-
end
-
-
# Applying values to a relation has some side effects. E.g.
-
# interpolation might take place for where values. So we should
-
# build a relation to merge in rather than directly merging
-
# the values.
-
1
def other
-
other = Relation.create(relation.klass, relation.table)
-
hash.each { |k, v|
-
if k == :joins
-
if Hash === v
-
other.joins!(v)
-
else
-
other.joins!(*v)
-
end
-
else
-
other.send("#{k}!", v)
-
end
-
}
-
other
-
end
-
end
-
-
1
class Merger # :nodoc:
-
1
attr_reader :relation, :values, :other
-
-
1
def initialize(relation, other)
-
@relation = relation
-
@values = other.values
-
@other = other
-
end
-
-
1
NORMAL_VALUES = Relation::SINGLE_VALUE_METHODS +
-
Relation::MULTI_VALUE_METHODS -
-
[:joins, :where, :order, :bind, :reverse_order, :lock, :create_with, :reordering, :from] # :nodoc:
-
-
1
def normal_values
-
NORMAL_VALUES
-
end
-
-
1
def merge
-
normal_values.each do |name|
-
value = values[name]
-
# The unless clause is here mostly for performance reasons (since the `send` call might be moderately
-
# expensive), most of the time the value is going to be `nil` or `.blank?`, the only catch is that
-
# `false.blank?` returns `true`, so there needs to be an extra check so that explicit `false` values
-
# don't fall through the cracks.
-
relation.send("#{name}!", *value) unless value.nil? || (value.blank? && false != value)
-
end
-
-
merge_multi_values
-
merge_single_values
-
merge_joins
-
-
relation
-
end
-
-
1
private
-
-
1
def merge_joins
-
return if values[:joins].blank?
-
-
if other.klass == relation.klass
-
relation.joins!(*values[:joins])
-
else
-
joins_dependency, rest = values[:joins].partition do |join|
-
case join
-
when Hash, Symbol, Array
-
true
-
else
-
false
-
end
-
end
-
-
join_dependency = ActiveRecord::Associations::JoinDependency.new(other.klass,
-
joins_dependency,
-
[])
-
relation.joins! rest
-
-
@relation = relation.joins join_dependency
-
end
-
end
-
-
1
def merge_multi_values
-
lhs_wheres = relation.where_values
-
rhs_wheres = values[:where] || []
-
-
lhs_binds = relation.bind_values
-
rhs_binds = values[:bind] || []
-
-
removed, kept = partition_overwrites(lhs_wheres, rhs_wheres)
-
-
where_values = kept + rhs_wheres
-
bind_values = filter_binds(lhs_binds, removed) + rhs_binds
-
-
conn = relation.klass.connection
-
bv_index = 0
-
where_values.map! do |node|
-
if Arel::Nodes::Equality === node && Arel::Nodes::BindParam === node.right
-
substitute = conn.substitute_at(bind_values[bv_index].first, bv_index)
-
bv_index += 1
-
Arel::Nodes::Equality.new(node.left, substitute)
-
else
-
node
-
end
-
end
-
-
relation.where_values = where_values
-
relation.bind_values = bind_values
-
-
if values[:reordering]
-
# override any order specified in the original relation
-
relation.reorder! values[:order]
-
elsif values[:order]
-
# merge in order_values from relation
-
relation.order! values[:order]
-
end
-
-
relation.extend(*values[:extending]) unless values[:extending].blank?
-
end
-
-
1
def merge_single_values
-
relation.from_value = values[:from] unless relation.from_value
-
relation.lock_value = values[:lock] unless relation.lock_value
-
relation.reverse_order_value = values[:reverse_order]
-
-
unless values[:create_with].blank?
-
relation.create_with_value = (relation.create_with_value || {}).merge(values[:create_with])
-
end
-
end
-
-
1
def filter_binds(lhs_binds, removed_wheres)
-
return lhs_binds if removed_wheres.empty?
-
-
set = Set.new removed_wheres.map { |x| x.left.name }
-
lhs_binds.dup.delete_if { |col,_| set.include? col.name }
-
end
-
-
# Remove equalities from the existing relation with a LHS which is
-
# present in the relation being merged in.
-
# returns [things_to_remove, things_to_keep]
-
1
def partition_overwrites(lhs_wheres, rhs_wheres)
-
if lhs_wheres.empty? || rhs_wheres.empty?
-
return [[], lhs_wheres]
-
end
-
-
nodes = rhs_wheres.find_all do |w|
-
w.respond_to?(:operator) && w.operator == :==
-
end
-
seen = Set.new(nodes) { |node| node.left }
-
-
lhs_wheres.partition do |w|
-
w.respond_to?(:operator) && w.operator == :== && seen.include?(w.left)
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/array/wrap'
-
-
1
module ActiveRecord
-
1
module QueryMethods
-
1
extend ActiveSupport::Concern
-
-
# WhereChain objects act as placeholder for queries in which #where does not have any parameter.
-
# In this case, #where must be chained with #not to return a new relation.
-
1
class WhereChain
-
1
def initialize(scope)
-
@scope = scope
-
end
-
-
# Returns a new relation expressing WHERE + NOT condition according to
-
# the conditions in the arguments.
-
#
-
# +not+ accepts conditions as a string, array, or hash. See #where for
-
# more details on each format.
-
#
-
# User.where.not("name = 'Jon'")
-
# # SELECT * FROM users WHERE NOT (name = 'Jon')
-
#
-
# User.where.not(["name = ?", "Jon"])
-
# # SELECT * FROM users WHERE NOT (name = 'Jon')
-
#
-
# User.where.not(name: "Jon")
-
# # SELECT * FROM users WHERE name != 'Jon'
-
#
-
# User.where.not(name: nil)
-
# # SELECT * FROM users WHERE name IS NOT NULL
-
#
-
# User.where.not(name: %w(Ko1 Nobu))
-
# # SELECT * FROM users WHERE name NOT IN ('Ko1', 'Nobu')
-
#
-
# User.where.not(name: "Jon", role: "admin")
-
# # SELECT * FROM users WHERE name != 'Jon' AND role != 'admin'
-
1
def not(opts, *rest)
-
where_value = @scope.send(:build_where, opts, rest).map do |rel|
-
case rel
-
when NilClass
-
raise ArgumentError, 'Invalid argument for .where.not(), got nil.'
-
when Arel::Nodes::In
-
Arel::Nodes::NotIn.new(rel.left, rel.right)
-
when Arel::Nodes::Equality
-
Arel::Nodes::NotEqual.new(rel.left, rel.right)
-
when String
-
Arel::Nodes::Not.new(Arel::Nodes::SqlLiteral.new(rel))
-
else
-
Arel::Nodes::Not.new(rel)
-
end
-
end
-
-
@scope.references!(PredicateBuilder.references(opts)) if Hash === opts
-
@scope.where_values += where_value
-
@scope
-
end
-
end
-
-
1
Relation::MULTI_VALUE_METHODS.each do |name|
-
13
class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{name}_values # def select_values
-
@values[:#{name}] || [] # @values[:select] || []
-
end # end
-
#
-
def #{name}_values=(values) # def select_values=(values)
-
raise ImmutableRelation if @loaded # raise ImmutableRelation if @loaded
-
@values[:#{name}] = values # @values[:select] = values
-
end # end
-
CODE
-
end
-
-
1
(Relation::SINGLE_VALUE_METHODS - [:create_with]).each do |name|
-
9
class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{name}_value # def readonly_value
-
@values[:#{name}] # @values[:readonly]
-
end # end
-
CODE
-
end
-
-
1
Relation::SINGLE_VALUE_METHODS.each do |name|
-
10
class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{name}_value=(value) # def readonly_value=(value)
-
raise ImmutableRelation if @loaded # raise ImmutableRelation if @loaded
-
@values[:#{name}] = value # @values[:readonly] = value
-
end # end
-
CODE
-
end
-
-
1
def create_with_value # :nodoc:
-
@values[:create_with] || {}
-
end
-
-
1
alias extensions extending_values
-
-
# Specify relationships to be included in the result set. For
-
# example:
-
#
-
# users = User.includes(:address)
-
# users.each do |user|
-
# user.address.city
-
# end
-
#
-
# allows you to access the +address+ attribute of the +User+ model without
-
# firing an additional query. This will often result in a
-
# performance improvement over a simple +join+.
-
#
-
# You can also specify multiple relationships, like this:
-
#
-
# users = User.includes(:address, :friends)
-
#
-
# Loading nested relationships is possible using a Hash:
-
#
-
# users = User.includes(:address, friends: [:address, :followers])
-
#
-
# === conditions
-
#
-
# If you want to add conditions to your included models you'll have
-
# to explicitly reference them. For example:
-
#
-
# User.includes(:posts).where('posts.name = ?', 'example')
-
#
-
# Will throw an error, but this will work:
-
#
-
# User.includes(:posts).where('posts.name = ?', 'example').references(:posts)
-
#
-
# Note that +includes+ works with association names while +references+ needs
-
# the actual table name.
-
1
def includes(*args)
-
check_if_method_has_arguments!(:includes, args)
-
spawn.includes!(*args)
-
end
-
-
1
def includes!(*args) # :nodoc:
-
args.reject!(&:blank?)
-
args.flatten!
-
-
self.includes_values |= args
-
self
-
end
-
-
# Forces eager loading by performing a LEFT OUTER JOIN on +args+:
-
#
-
# User.eager_load(:posts)
-
# => SELECT "users"."id" AS t0_r0, "users"."name" AS t0_r1, ...
-
# FROM "users" LEFT OUTER JOIN "posts" ON "posts"."user_id" =
-
# "users"."id"
-
1
def eager_load(*args)
-
check_if_method_has_arguments!(:eager_load, args)
-
spawn.eager_load!(*args)
-
end
-
-
1
def eager_load!(*args) # :nodoc:
-
self.eager_load_values += args
-
self
-
end
-
-
# Allows preloading of +args+, in the same way that +includes+ does:
-
#
-
# User.preload(:posts)
-
# => SELECT "posts".* FROM "posts" WHERE "posts"."user_id" IN (1, 2, 3)
-
1
def preload(*args)
-
check_if_method_has_arguments!(:preload, args)
-
spawn.preload!(*args)
-
end
-
-
1
def preload!(*args) # :nodoc:
-
self.preload_values += args
-
self
-
end
-
-
# Use to indicate that the given +table_names+ are referenced by an SQL string,
-
# and should therefore be JOINed in any query rather than loaded separately.
-
# This method only works in conjuction with +includes+.
-
# See #includes for more details.
-
#
-
# User.includes(:posts).where("posts.name = 'foo'")
-
# # => Doesn't JOIN the posts table, resulting in an error.
-
#
-
# User.includes(:posts).where("posts.name = 'foo'").references(:posts)
-
# # => Query now knows the string references posts, so adds a JOIN
-
1
def references(*table_names)
-
check_if_method_has_arguments!(:references, table_names)
-
spawn.references!(*table_names)
-
end
-
-
1
def references!(*table_names) # :nodoc:
-
table_names.flatten!
-
table_names.map!(&:to_s)
-
-
self.references_values |= table_names
-
self
-
end
-
-
# Works in two unique ways.
-
#
-
# First: takes a block so it can be used just like Array#select.
-
#
-
# Model.all.select { |m| m.field == value }
-
#
-
# This will build an array of objects from the database for the scope,
-
# converting them into an array and iterating through them using Array#select.
-
#
-
# Second: Modifies the SELECT statement for the query so that only certain
-
# fields are retrieved:
-
#
-
# Model.select(:field)
-
# # => [#<Model field:value>]
-
#
-
# Although in the above example it looks as though this method returns an
-
# array, it actually returns a relation object and can have other query
-
# methods appended to it, such as the other methods in ActiveRecord::QueryMethods.
-
#
-
# The argument to the method can also be an array of fields.
-
#
-
# Model.select(:field, :other_field, :and_one_more)
-
# # => [#<Model field: "value", other_field: "value", and_one_more: "value">]
-
#
-
# You can also use one or more strings, which will be used unchanged as SELECT fields.
-
#
-
# Model.select('field AS field_one', 'other_field AS field_two')
-
# # => [#<Model field: "value", other_field: "value">]
-
#
-
# If an alias was specified, it will be accessible from the resulting objects:
-
#
-
# Model.select('field AS field_one').first.field_one
-
# # => "value"
-
#
-
# Accessing attributes of an object that do not have fields retrieved by a select
-
# will throw <tt>ActiveModel::MissingAttributeError</tt>:
-
#
-
# Model.select(:field).first.other_field
-
# # => ActiveModel::MissingAttributeError: missing attribute: other_field
-
1
def select(*fields)
-
if block_given?
-
to_a.select { |*block_args| yield(*block_args) }
-
else
-
raise ArgumentError, 'Call this with at least one field' if fields.empty?
-
spawn.select!(*fields)
-
end
-
end
-
-
1
def select!(*fields) # :nodoc:
-
fields.flatten!
-
fields.map! do |field|
-
klass.attribute_alias?(field) ? klass.attribute_alias(field) : field
-
end
-
self.select_values += fields
-
self
-
end
-
-
# Allows to specify a group attribute:
-
#
-
# User.group(:name)
-
# => SELECT "users".* FROM "users" GROUP BY name
-
#
-
# Returns an array with distinct records based on the +group+ attribute:
-
#
-
# User.select([:id, :name])
-
# => [#<User id: 1, name: "Oscar">, #<User id: 2, name: "Oscar">, #<User id: 3, name: "Foo">
-
#
-
# User.group(:name)
-
# => [#<User id: 3, name: "Foo", ...>, #<User id: 2, name: "Oscar", ...>]
-
#
-
# User.group('name AS grouped_name, age')
-
# => [#<User id: 3, name: "Foo", age: 21, ...>, #<User id: 2, name: "Oscar", age: 21, ...>, #<User id: 5, name: "Foo", age: 23, ...>]
-
1
def group(*args)
-
check_if_method_has_arguments!(:group, args)
-
spawn.group!(*args)
-
end
-
-
1
def group!(*args) # :nodoc:
-
args.flatten!
-
-
self.group_values += args
-
self
-
end
-
-
# Allows to specify an order attribute:
-
#
-
# User.order('name')
-
# => SELECT "users".* FROM "users" ORDER BY name
-
#
-
# User.order('name DESC')
-
# => SELECT "users".* FROM "users" ORDER BY name DESC
-
#
-
# User.order('name DESC, email')
-
# => SELECT "users".* FROM "users" ORDER BY name DESC, email
-
#
-
# User.order(:name)
-
# => SELECT "users".* FROM "users" ORDER BY "users"."name" ASC
-
#
-
# User.order(email: :desc)
-
# => SELECT "users".* FROM "users" ORDER BY "users"."email" DESC
-
#
-
# User.order(:name, email: :desc)
-
# => SELECT "users".* FROM "users" ORDER BY "users"."name" ASC, "users"."email" DESC
-
1
def order(*args)
-
check_if_method_has_arguments!(:order, args)
-
spawn.order!(*args)
-
end
-
-
1
def order!(*args) # :nodoc:
-
preprocess_order_args(args)
-
-
self.order_values += args
-
self
-
end
-
-
# Replaces any existing order defined on the relation with the specified order.
-
#
-
# User.order('email DESC').reorder('id ASC') # generated SQL has 'ORDER BY id ASC'
-
#
-
# Subsequent calls to order on the same relation will be appended. For example:
-
#
-
# User.order('email DESC').reorder('id ASC').order('name ASC')
-
#
-
# generates a query with 'ORDER BY id ASC, name ASC'.
-
1
def reorder(*args)
-
check_if_method_has_arguments!(:reorder, args)
-
spawn.reorder!(*args)
-
end
-
-
1
def reorder!(*args) # :nodoc:
-
preprocess_order_args(args)
-
-
self.reordering_value = true
-
self.order_values = args
-
self
-
end
-
-
1
VALID_UNSCOPING_VALUES = Set.new([:where, :select, :group, :order, :lock,
-
:limit, :offset, :joins, :includes, :from,
-
:readonly, :having])
-
-
# Removes an unwanted relation that is already defined on a chain of relations.
-
# This is useful when passing around chains of relations and would like to
-
# modify the relations without reconstructing the entire chain.
-
#
-
# User.order('email DESC').unscope(:order) == User.all
-
#
-
# The method arguments are symbols which correspond to the names of the methods
-
# which should be unscoped. The valid arguments are given in VALID_UNSCOPING_VALUES.
-
# The method can also be called with multiple arguments. For example:
-
#
-
# User.order('email DESC').select('id').where(name: "John")
-
# .unscope(:order, :select, :where) == User.all
-
#
-
# One can additionally pass a hash as an argument to unscope specific :where values.
-
# This is done by passing a hash with a single key-value pair. The key should be
-
# :where and the value should be the where value to unscope. For example:
-
#
-
# User.where(name: "John", active: true).unscope(where: :name)
-
# == User.where(active: true)
-
#
-
# This method is similar to <tt>except</tt>, but unlike
-
# <tt>except</tt>, it persists across merges:
-
#
-
# User.order('email').merge(User.except(:order))
-
# == User.order('email')
-
#
-
# User.order('email').merge(User.unscope(:order))
-
# == User.all
-
#
-
# This means it can be used in association definitions:
-
#
-
# has_many :comments, -> { unscope where: :trashed }
-
#
-
1
def unscope(*args)
-
check_if_method_has_arguments!(:unscope, args)
-
spawn.unscope!(*args)
-
end
-
-
1
def unscope!(*args) # :nodoc:
-
args.flatten!
-
self.unscope_values += args
-
-
args.each do |scope|
-
case scope
-
when Symbol
-
symbol_unscoping(scope)
-
when Hash
-
scope.each do |key, target_value|
-
if key != :where
-
raise ArgumentError, "Hash arguments in .unscope(*args) must have :where as the key."
-
end
-
-
Array(target_value).each do |val|
-
where_unscoping(val)
-
end
-
end
-
else
-
raise ArgumentError, "Unrecognized scoping: #{args.inspect}. Use .unscope(where: :attribute_name) or .unscope(:order), for example."
-
end
-
end
-
-
self
-
end
-
-
# Performs a joins on +args+:
-
#
-
# User.joins(:posts)
-
# => SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
-
#
-
# You can use strings in order to customize your joins:
-
#
-
# User.joins("LEFT JOIN bookmarks ON bookmarks.bookmarkable_type = 'Post' AND bookmarks.user_id = users.id")
-
# => SELECT "users".* FROM "users" LEFT JOIN bookmarks ON bookmarks.bookmarkable_type = 'Post' AND bookmarks.user_id = users.id
-
1
def joins(*args)
-
check_if_method_has_arguments!(:joins, args)
-
-
args.compact!
-
args.flatten!
-
-
spawn.joins!(*args)
-
end
-
-
1
def joins!(*args) # :nodoc:
-
self.joins_values += args
-
self
-
end
-
-
1
def bind(value)
-
spawn.bind!(value)
-
end
-
-
1
def bind!(value) # :nodoc:
-
self.bind_values += [value]
-
self
-
end
-
-
# Returns a new relation, which is the result of filtering the current relation
-
# according to the conditions in the arguments.
-
#
-
# #where accepts conditions in one of several formats. In the examples below, the resulting
-
# SQL is given as an illustration; the actual query generated may be different depending
-
# on the database adapter.
-
#
-
# === string
-
#
-
# A single string, without additional arguments, is passed to the query
-
# constructor as an SQL fragment, and used in the where clause of the query.
-
#
-
# Client.where("orders_count = '2'")
-
# # SELECT * from clients where orders_count = '2';
-
#
-
# Note that building your own string from user input may expose your application
-
# to injection attacks if not done properly. As an alternative, it is recommended
-
# to use one of the following methods.
-
#
-
# === array
-
#
-
# If an array is passed, then the first element of the array is treated as a template, and
-
# the remaining elements are inserted into the template to generate the condition.
-
# Active Record takes care of building the query to avoid injection attacks, and will
-
# convert from the ruby type to the database type where needed. Elements are inserted
-
# into the string in the order in which they appear.
-
#
-
# User.where(["name = ? and email = ?", "Joe", "joe@example.com"])
-
# # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
-
#
-
# Alternatively, you can use named placeholders in the template, and pass a hash as the
-
# second element of the array. The names in the template are replaced with the corresponding
-
# values from the hash.
-
#
-
# User.where(["name = :name and email = :email", { name: "Joe", email: "joe@example.com" }])
-
# # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
-
#
-
# This can make for more readable code in complex queries.
-
#
-
# Lastly, you can use sprintf-style % escapes in the template. This works slightly differently
-
# than the previous methods; you are responsible for ensuring that the values in the template
-
# are properly quoted. The values are passed to the connector for quoting, but the caller
-
# is responsible for ensuring they are enclosed in quotes in the resulting SQL. After quoting,
-
# the values are inserted using the same escapes as the Ruby core method <tt>Kernel::sprintf</tt>.
-
#
-
# User.where(["name = '%s' and email = '%s'", "Joe", "joe@example.com"])
-
# # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
-
#
-
# If #where is called with multiple arguments, these are treated as if they were passed as
-
# the elements of a single array.
-
#
-
# User.where("name = :name and email = :email", { name: "Joe", email: "joe@example.com" })
-
# # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
-
#
-
# When using strings to specify conditions, you can use any operator available from
-
# the database. While this provides the most flexibility, you can also unintentionally introduce
-
# dependencies on the underlying database. If your code is intended for general consumption,
-
# test with multiple database backends.
-
#
-
# === hash
-
#
-
# #where will also accept a hash condition, in which the keys are fields and the values
-
# are values to be searched for.
-
#
-
# Fields can be symbols or strings. Values can be single values, arrays, or ranges.
-
#
-
# User.where({ name: "Joe", email: "joe@example.com" })
-
# # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com'
-
#
-
# User.where({ name: ["Alice", "Bob"]})
-
# # SELECT * FROM users WHERE name IN ('Alice', 'Bob')
-
#
-
# User.where({ created_at: (Time.now.midnight - 1.day)..Time.now.midnight })
-
# # SELECT * FROM users WHERE (created_at BETWEEN '2012-06-09 07:00:00.000000' AND '2012-06-10 07:00:00.000000')
-
#
-
# In the case of a belongs_to relationship, an association key can be used
-
# to specify the model if an ActiveRecord object is used as the value.
-
#
-
# author = Author.find(1)
-
#
-
# # The following queries will be equivalent:
-
# Post.where(author: author)
-
# Post.where(author_id: author)
-
#
-
# This also works with polymorphic belongs_to relationships:
-
#
-
# treasure = Treasure.create(name: 'gold coins')
-
# treasure.price_estimates << PriceEstimate.create(price: 125)
-
#
-
# # The following queries will be equivalent:
-
# PriceEstimate.where(estimate_of: treasure)
-
# PriceEstimate.where(estimate_of_type: 'Treasure', estimate_of_id: treasure)
-
#
-
# === Joins
-
#
-
# If the relation is the result of a join, you may create a condition which uses any of the
-
# tables in the join. For string and array conditions, use the table name in the condition.
-
#
-
# User.joins(:posts).where("posts.created_at < ?", Time.now)
-
#
-
# For hash conditions, you can either use the table name in the key, or use a sub-hash.
-
#
-
# User.joins(:posts).where({ "posts.published" => true })
-
# User.joins(:posts).where({ posts: { published: true } })
-
#
-
# === no argument
-
#
-
# If no argument is passed, #where returns a new instance of WhereChain, that
-
# can be chained with #not to return a new relation that negates the where clause.
-
#
-
# User.where.not(name: "Jon")
-
# # SELECT * FROM users WHERE name != 'Jon'
-
#
-
# See WhereChain for more details on #not.
-
#
-
# === blank condition
-
#
-
# If the condition is any blank-ish object, then #where is a no-op and returns
-
# the current relation.
-
1
def where(opts = :chain, *rest)
-
if opts == :chain
-
WhereChain.new(spawn)
-
elsif opts.blank?
-
self
-
else
-
spawn.where!(opts, *rest)
-
end
-
end
-
-
1
def where!(opts = :chain, *rest) # :nodoc:
-
if opts == :chain
-
WhereChain.new(self)
-
else
-
references!(PredicateBuilder.references(opts)) if Hash === opts
-
-
self.where_values += build_where(opts, rest)
-
self
-
end
-
end
-
-
# Allows you to change a previously set where condition for a given attribute, instead of appending to that condition.
-
#
-
# Post.where(trashed: true).where(trashed: false) # => WHERE `trashed` = 1 AND `trashed` = 0
-
# Post.where(trashed: true).rewhere(trashed: false) # => WHERE `trashed` = 0
-
# Post.where(active: true).where(trashed: true).rewhere(trashed: false) # => WHERE `active` = 1 AND `trashed` = 0
-
#
-
# This is short-hand for unscope(where: conditions.keys).where(conditions). Note that unlike reorder, we're only unscoping
-
# the named conditions -- not the entire where statement.
-
1
def rewhere(conditions)
-
unscope(where: conditions.keys).where(conditions)
-
end
-
-
# Allows to specify a HAVING clause. Note that you can't use HAVING
-
# without also specifying a GROUP clause.
-
#
-
# Order.having('SUM(price) > 30').group('user_id')
-
1
def having(opts, *rest)
-
opts.blank? ? self : spawn.having!(opts, *rest)
-
end
-
-
1
def having!(opts, *rest) # :nodoc:
-
references!(PredicateBuilder.references(opts)) if Hash === opts
-
-
self.having_values += build_where(opts, rest)
-
self
-
end
-
-
# Specifies a limit for the number of records to retrieve.
-
#
-
# User.limit(10) # generated SQL has 'LIMIT 10'
-
#
-
# User.limit(10).limit(20) # generated SQL has 'LIMIT 20'
-
1
def limit(value)
-
spawn.limit!(value)
-
end
-
-
1
def limit!(value) # :nodoc:
-
self.limit_value = value
-
self
-
end
-
-
# Specifies the number of rows to skip before returning rows.
-
#
-
# User.offset(10) # generated SQL has "OFFSET 10"
-
#
-
# Should be used with order.
-
#
-
# User.offset(10).order("name ASC")
-
1
def offset(value)
-
spawn.offset!(value)
-
end
-
-
1
def offset!(value) # :nodoc:
-
self.offset_value = value
-
self
-
end
-
-
# Specifies locking settings (default to +true+). For more information
-
# on locking, please see +ActiveRecord::Locking+.
-
1
def lock(locks = true)
-
spawn.lock!(locks)
-
end
-
-
1
def lock!(locks = true) # :nodoc:
-
case locks
-
when String, TrueClass, NilClass
-
self.lock_value = locks || true
-
else
-
self.lock_value = false
-
end
-
-
self
-
end
-
-
# Returns a chainable relation with zero records.
-
#
-
# The returned relation implements the Null Object pattern. It is an
-
# object with defined null behavior and always returns an empty array of
-
# records without querying the database.
-
#
-
# Any subsequent condition chained to the returned relation will continue
-
# generating an empty relation and will not fire any query to the database.
-
#
-
# Used in cases where a method or scope could return zero records but the
-
# result needs to be chainable.
-
#
-
# For example:
-
#
-
# @posts = current_user.visible_posts.where(name: params[:name])
-
# # => the visible_posts method is expected to return a chainable Relation
-
#
-
# def visible_posts
-
# case role
-
# when 'Country Manager'
-
# Post.where(country: country)
-
# when 'Reviewer'
-
# Post.published
-
# when 'Bad User'
-
# Post.none # It can't be chained if [] is returned.
-
# end
-
# end
-
#
-
1
def none
-
extending(NullRelation)
-
end
-
-
1
def none! # :nodoc:
-
extending!(NullRelation)
-
end
-
-
# Sets readonly attributes for the returned relation. If value is
-
# true (default), attempting to update a record will result in an error.
-
#
-
# users = User.readonly
-
# users.first.save
-
# => ActiveRecord::ReadOnlyRecord: ActiveRecord::ReadOnlyRecord
-
1
def readonly(value = true)
-
spawn.readonly!(value)
-
end
-
-
1
def readonly!(value = true) # :nodoc:
-
self.readonly_value = value
-
self
-
end
-
-
# Sets attributes to be used when creating new records from a
-
# relation object.
-
#
-
# users = User.where(name: 'Oscar')
-
# users.new.name # => 'Oscar'
-
#
-
# users = users.create_with(name: 'DHH')
-
# users.new.name # => 'DHH'
-
#
-
# You can pass +nil+ to +create_with+ to reset attributes:
-
#
-
# users = users.create_with(nil)
-
# users.new.name # => 'Oscar'
-
1
def create_with(value)
-
spawn.create_with!(value)
-
end
-
-
1
def create_with!(value) # :nodoc:
-
self.create_with_value = value ? create_with_value.merge(value) : {}
-
self
-
end
-
-
# Specifies table from which the records will be fetched. For example:
-
#
-
# Topic.select('title').from('posts')
-
# # => SELECT title FROM posts
-
#
-
# Can accept other relation objects. For example:
-
#
-
# Topic.select('title').from(Topic.approved)
-
# # => SELECT title FROM (SELECT * FROM topics WHERE approved = 't') subquery
-
#
-
# Topic.select('a.title').from(Topic.approved, :a)
-
# # => SELECT a.title FROM (SELECT * FROM topics WHERE approved = 't') a
-
#
-
1
def from(value, subquery_name = nil)
-
spawn.from!(value, subquery_name)
-
end
-
-
1
def from!(value, subquery_name = nil) # :nodoc:
-
self.from_value = [value, subquery_name]
-
self
-
end
-
-
# Specifies whether the records should be unique or not. For example:
-
#
-
# User.select(:name)
-
# # => Might return two records with the same name
-
#
-
# User.select(:name).distinct
-
# # => Returns 1 record per distinct name
-
#
-
# User.select(:name).distinct.distinct(false)
-
# # => You can also remove the uniqueness
-
1
def distinct(value = true)
-
spawn.distinct!(value)
-
end
-
1
alias uniq distinct
-
-
# Like #distinct, but modifies relation in place.
-
1
def distinct!(value = true) # :nodoc:
-
self.distinct_value = value
-
self
-
end
-
1
alias uniq! distinct!
-
-
# Used to extend a scope with additional methods, either through
-
# a module or through a block provided.
-
#
-
# The object returned is a relation, which can be further extended.
-
#
-
# === Using a module
-
#
-
# module Pagination
-
# def page(number)
-
# # pagination code goes here
-
# end
-
# end
-
#
-
# scope = Model.all.extending(Pagination)
-
# scope.page(params[:page])
-
#
-
# You can also pass a list of modules:
-
#
-
# scope = Model.all.extending(Pagination, SomethingElse)
-
#
-
# === Using a block
-
#
-
# scope = Model.all.extending do
-
# def page(number)
-
# # pagination code goes here
-
# end
-
# end
-
# scope.page(params[:page])
-
#
-
# You can also use a block and a module list:
-
#
-
# scope = Model.all.extending(Pagination) do
-
# def per_page(number)
-
# # pagination code goes here
-
# end
-
# end
-
1
def extending(*modules, &block)
-
if modules.any? || block
-
spawn.extending!(*modules, &block)
-
else
-
self
-
end
-
end
-
-
1
def extending!(*modules, &block) # :nodoc:
-
modules << Module.new(&block) if block
-
modules.flatten!
-
-
self.extending_values += modules
-
extend(*extending_values) if extending_values.any?
-
-
self
-
end
-
-
# Reverse the existing order clause on the relation.
-
#
-
# User.order('name ASC').reverse_order # generated SQL has 'ORDER BY name DESC'
-
1
def reverse_order
-
spawn.reverse_order!
-
end
-
-
1
def reverse_order! # :nodoc:
-
self.reverse_order_value = !reverse_order_value
-
self
-
end
-
-
# Returns the Arel object associated with the relation.
-
1
def arel # :nodoc:
-
@arel ||= build_arel
-
end
-
-
1
private
-
-
1
def build_arel
-
arel = Arel::SelectManager.new(table.engine, table)
-
-
build_joins(arel, joins_values.flatten) unless joins_values.empty?
-
-
collapse_wheres(arel, (where_values - ['']).uniq)
-
-
arel.having(*having_values.uniq.reject(&:blank?)) unless having_values.empty?
-
-
arel.take(connection.sanitize_limit(limit_value)) if limit_value
-
arel.skip(offset_value.to_i) if offset_value
-
-
arel.group(*group_values.uniq.reject(&:blank?)) unless group_values.empty?
-
-
build_order(arel)
-
-
build_select(arel, select_values.uniq)
-
-
arel.distinct(distinct_value)
-
arel.from(build_from) if from_value
-
arel.lock(lock_value) if lock_value
-
-
arel
-
end
-
-
1
def symbol_unscoping(scope)
-
if !VALID_UNSCOPING_VALUES.include?(scope)
-
raise ArgumentError, "Called unscope() with invalid unscoping argument ':#{scope}'. Valid arguments are :#{VALID_UNSCOPING_VALUES.to_a.join(", :")}."
-
end
-
-
single_val_method = Relation::SINGLE_VALUE_METHODS.include?(scope)
-
unscope_code = "#{scope}_value#{'s' unless single_val_method}="
-
-
case scope
-
when :order
-
self.reverse_order_value = false
-
result = []
-
else
-
result = [] unless single_val_method
-
end
-
-
self.send(unscope_code, result)
-
end
-
-
1
def where_unscoping(target_value)
-
target_value = target_value.to_s
-
-
where_values.reject! do |rel|
-
case rel
-
when Arel::Nodes::In, Arel::Nodes::NotIn, Arel::Nodes::Equality, Arel::Nodes::NotEqual
-
subrelation = (rel.left.kind_of?(Arel::Attributes::Attribute) ? rel.left : rel.right)
-
subrelation.name == target_value
-
end
-
end
-
-
bind_values.reject! { |col,_| col.name == target_value }
-
end
-
-
1
def custom_join_ast(table, joins)
-
joins = joins.reject(&:blank?)
-
-
return [] if joins.empty?
-
-
joins.map! do |join|
-
case join
-
when Array
-
join = Arel.sql(join.join(' ')) if array_of_strings?(join)
-
when String
-
join = Arel.sql(join)
-
end
-
table.create_string_join(join)
-
end
-
end
-
-
1
def collapse_wheres(arel, wheres)
-
predicates = wheres.map do |where|
-
next where if ::Arel::Nodes::Equality === where
-
where = Arel.sql(where) if String === where
-
Arel::Nodes::Grouping.new(where)
-
end
-
-
arel.where(Arel::Nodes::And.new(predicates)) if predicates.present?
-
end
-
-
1
def build_where(opts, other = [])
-
case opts
-
when String, Array
-
#TODO: Remove duplication with: /activerecord/lib/active_record/sanitization.rb:113
-
values = Hash === other.first ? other.first.values : other
-
-
values.grep(ActiveRecord::Relation) do |rel|
-
self.bind_values += rel.bind_values
-
end
-
-
[@klass.send(:sanitize_sql, other.empty? ? opts : ([opts] + other))]
-
when Hash
-
opts = PredicateBuilder.resolve_column_aliases(klass, opts)
-
attributes = @klass.send(:expand_hash_conditions_for_aggregates, opts)
-
-
attributes.values.grep(ActiveRecord::Relation) do |rel|
-
self.bind_values += rel.bind_values
-
end
-
-
PredicateBuilder.build_from_hash(klass, attributes, table)
-
else
-
[opts]
-
end
-
end
-
-
1
def build_from
-
opts, name = from_value
-
case opts
-
when Relation
-
name ||= 'subquery'
-
self.bind_values = opts.bind_values + self.bind_values
-
opts.arel.as(name.to_s)
-
else
-
opts
-
end
-
end
-
-
1
def build_joins(manager, joins)
-
buckets = joins.group_by do |join|
-
case join
-
when String
-
:string_join
-
when Hash, Symbol, Array
-
:association_join
-
when ActiveRecord::Associations::JoinDependency
-
:stashed_join
-
when Arel::Nodes::Join
-
:join_node
-
else
-
raise 'unknown class: %s' % join.class.name
-
end
-
end
-
-
association_joins = buckets[:association_join] || []
-
stashed_association_joins = buckets[:stashed_join] || []
-
join_nodes = (buckets[:join_node] || []).uniq
-
string_joins = (buckets[:string_join] || []).map(&:strip).uniq
-
-
join_list = join_nodes + custom_join_ast(manager, string_joins)
-
-
join_dependency = ActiveRecord::Associations::JoinDependency.new(
-
@klass,
-
association_joins,
-
join_list
-
)
-
-
joins = join_dependency.join_constraints stashed_association_joins
-
-
joins.each { |join| manager.from(join) }
-
-
manager.join_sources.concat(join_list)
-
-
manager
-
end
-
-
1
def build_select(arel, selects)
-
if !selects.empty?
-
expanded_select = selects.map do |field|
-
columns_hash.key?(field.to_s) ? arel_table[field] : field
-
end
-
arel.project(*expanded_select)
-
else
-
arel.project(@klass.arel_table[Arel.star])
-
end
-
end
-
-
1
def reverse_sql_order(order_query)
-
order_query = ["#{quoted_table_name}.#{quoted_primary_key} ASC"] if order_query.empty?
-
-
order_query.flat_map do |o|
-
case o
-
when Arel::Nodes::Ordering
-
o.reverse
-
when String
-
o.to_s.split(',').map! do |s|
-
s.strip!
-
s.gsub!(/\sasc\Z/i, ' DESC') || s.gsub!(/\sdesc\Z/i, ' ASC') || s.concat(' DESC')
-
end
-
else
-
o
-
end
-
end
-
end
-
-
1
def array_of_strings?(o)
-
o.is_a?(Array) && o.all? { |obj| obj.is_a?(String) }
-
end
-
-
1
def build_order(arel)
-
orders = order_values.uniq
-
orders.reject!(&:blank?)
-
orders = reverse_sql_order(orders) if reverse_order_value
-
-
arel.order(*orders) unless orders.empty?
-
end
-
-
1
def validate_order_args(args)
-
args.grep(Hash) do |h|
-
unless (h.values - [:asc, :desc]).empty?
-
raise ArgumentError, 'Direction should be :asc or :desc'
-
end
-
end
-
end
-
-
1
def preprocess_order_args(order_args)
-
order_args.flatten!
-
validate_order_args(order_args)
-
-
references = order_args.grep(String)
-
references.map! { |arg| arg =~ /^([a-zA-Z]\w*)\.(\w+)/ && $1 }.compact!
-
references!(references) if references.any?
-
-
# if a symbol is given we prepend the quoted table name
-
order_args.map! do |arg|
-
case arg
-
when Symbol
-
arg = klass.attribute_alias(arg) if klass.attribute_alias?(arg)
-
table[arg].asc
-
when Hash
-
arg.map { |field, dir|
-
field = klass.attribute_alias(field) if klass.attribute_alias?(field)
-
table[field].send(dir)
-
}
-
else
-
arg
-
end
-
end.flatten!
-
end
-
-
# Checks to make sure that the arguments are not blank. Note that if some
-
# blank-like object were initially passed into the query method, then this
-
# method will not raise an error.
-
#
-
# Example:
-
#
-
# Post.references() # => raises an error
-
# Post.references([]) # => does not raise an error
-
#
-
# This particular method should be called with a method_name and the args
-
# passed into that method as an input. For example:
-
#
-
# def references(*args)
-
# check_if_method_has_arguments!("references", args)
-
# ...
-
# end
-
1
def check_if_method_has_arguments!(method_name, args)
-
if args.blank?
-
raise ArgumentError, "The method .#{method_name}() must contain arguments."
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/hash/slice'
-
1
require 'active_record/relation/merger'
-
-
1
module ActiveRecord
-
1
module SpawnMethods
-
-
# This is overridden by Associations::CollectionProxy
-
1
def spawn #:nodoc:
-
clone
-
end
-
-
# Merges in the conditions from <tt>other</tt>, if <tt>other</tt> is an <tt>ActiveRecord::Relation</tt>.
-
# Returns an array representing the intersection of the resulting records with <tt>other</tt>, if <tt>other</tt> is an array.
-
# Post.where(published: true).joins(:comments).merge( Comment.where(spam: false) )
-
# # Performs a single join query with both where conditions.
-
#
-
# recent_posts = Post.order('created_at DESC').first(5)
-
# Post.where(published: true).merge(recent_posts)
-
# # Returns the intersection of all published posts with the 5 most recently created posts.
-
# # (This is just an example. You'd probably want to do this with a single query!)
-
#
-
# Procs will be evaluated by merge:
-
#
-
# Post.where(published: true).merge(-> { joins(:comments) })
-
# # => Post.where(published: true).joins(:comments)
-
#
-
# This is mainly intended for sharing common conditions between multiple associations.
-
1
def merge(other)
-
if other.is_a?(Array)
-
to_a & other
-
elsif other
-
spawn.merge!(other)
-
else
-
self
-
end
-
end
-
-
1
def merge!(other) # :nodoc:
-
if !other.is_a?(Relation) && other.respond_to?(:to_proc)
-
instance_exec(&other)
-
else
-
klass = other.is_a?(Hash) ? Relation::HashMerger : Relation::Merger
-
klass.new(self, other).merge
-
end
-
end
-
-
# Removes from the query the condition(s) specified in +skips+.
-
#
-
# Post.order('id asc').except(:order) # discards the order condition
-
# Post.where('id > 10').order('id asc').except(:where) # discards the where condition but keeps the order
-
1
def except(*skips)
-
relation_with values.except(*skips)
-
end
-
-
# Removes any condition from the query other than the one(s) specified in +onlies+.
-
#
-
# Post.order('id asc').only(:where) # discards the order condition
-
# Post.order('id asc').only(:where, :order) # uses the specified order
-
1
def only(*onlies)
-
relation_with values.slice(*onlies)
-
end
-
-
1
private
-
-
1
def relation_with(values) # :nodoc:
-
result = Relation.create(klass, table, values)
-
result.extend(*extending_values) if extending_values.any?
-
result
-
end
-
end
-
end
-
1
module ActiveRecord
-
###
-
# This class encapsulates a Result returned from calling +exec_query+ on any
-
# database connection adapter. For example:
-
#
-
# result = ActiveRecord::Base.connection.exec_query('SELECT id, title, body FROM posts')
-
# result # => #<ActiveRecord::Result:0xdeadbeef>
-
#
-
# # Get the column names of the result:
-
# result.columns
-
# # => ["id", "title", "body"]
-
#
-
# # Get the record values of the result:
-
# result.rows
-
# # => [[1, "title_1", "body_1"],
-
# [2, "title_2", "body_2"],
-
# ...
-
# ]
-
#
-
# # Get an array of hashes representing the result (column => value):
-
# result.to_hash
-
# # => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
-
# {"id" => 2, "title" => "title_2", "body" => "body_2"},
-
# ...
-
# ]
-
#
-
# # ActiveRecord::Result also includes Enumerable.
-
# result.each do |row|
-
# puts row['title'] + " " + row['body']
-
# end
-
1
class Result
-
1
include Enumerable
-
-
2
IDENTITY_TYPE = Class.new { def type_cast(v); v; end }.new # :nodoc:
-
-
1
attr_reader :columns, :rows, :column_types
-
-
1
def initialize(columns, rows, column_types = {})
-
1
@columns = columns
-
1
@rows = rows
-
1
@hash_rows = nil
-
1
@column_types = column_types
-
end
-
-
1
def identity_type # :nodoc:
-
IDENTITY_TYPE
-
end
-
-
1
def column_type(name)
-
@column_types[name] || identity_type
-
end
-
-
1
def each
-
if block_given?
-
hash_rows.each { |row| yield row }
-
else
-
hash_rows.to_enum { @rows.size }
-
end
-
end
-
-
1
def to_hash
-
hash_rows
-
end
-
-
1
alias :map! :map
-
1
alias :collect! :map
-
-
# Returns true if there are no records.
-
1
def empty?
-
rows.empty?
-
end
-
-
1
def to_ary
-
hash_rows
-
end
-
-
1
def [](idx)
-
hash_rows[idx]
-
end
-
-
1
def last
-
hash_rows.last
-
end
-
-
1
def initialize_copy(other)
-
@columns = columns.dup
-
@rows = rows.dup
-
@column_types = column_types.dup
-
@hash_rows = nil
-
end
-
-
1
private
-
-
1
def hash_rows
-
@hash_rows ||=
-
begin
-
# We freeze the strings to prevent them getting duped when
-
# used as keys in ActiveRecord::Base's @attributes hash
-
columns = @columns.map { |c| c.dup.freeze }
-
@rows.map { |row|
-
# In the past we used Hash[columns.zip(row)]
-
# though elegant, the verbose way is much more efficient
-
# both time and memory wise cause it avoids a big array allocation
-
# this method is called a lot and needs to be micro optimised
-
hash = {}
-
-
index = 0
-
length = columns.length
-
-
while index < length
-
hash[columns[index]] = row[index]
-
index += 1
-
end
-
-
hash
-
}
-
end
-
end
-
end
-
end
-
1
require 'active_support/per_thread_registry'
-
-
1
module ActiveRecord
-
# This is a thread locals registry for Active Record. For example:
-
#
-
# ActiveRecord::RuntimeRegistry.connection_handler
-
#
-
# returns the connection handler local to the current thread.
-
#
-
# See the documentation of <tt>ActiveSupport::PerThreadRegistry</tt>
-
# for further details.
-
1
class RuntimeRegistry # :nodoc:
-
1
extend ActiveSupport::PerThreadRegistry
-
-
1
attr_accessor :connection_handler, :sql_runtime, :connection_id
-
-
1
[:connection_handler, :sql_runtime, :connection_id].each do |val|
-
3
class_eval %{ def self.#{val}; instance.#{val}; end }, __FILE__, __LINE__
-
3
class_eval %{ def self.#{val}=(x); instance.#{val}=x; end }, __FILE__, __LINE__
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Sanitization
-
1
extend ActiveSupport::Concern
-
-
1
module ClassMethods
-
1
def quote_value(value, column) #:nodoc:
-
connection.quote(value, column)
-
end
-
-
# Used to sanitize objects before they're used in an SQL SELECT statement. Delegates to <tt>connection.quote</tt>.
-
1
def sanitize(object) #:nodoc:
-
connection.quote(object)
-
end
-
-
1
protected
-
-
# Accepts an array, hash, or string of SQL conditions and sanitizes
-
# them into a valid SQL fragment for a WHERE clause.
-
# ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'"
-
# { name: "foo'bar", group_id: 4 } returns "name='foo''bar' and group_id='4'"
-
# "name='foo''bar' and group_id='4'" returns "name='foo''bar' and group_id='4'"
-
1
def sanitize_sql_for_conditions(condition, table_name = self.table_name)
-
return nil if condition.blank?
-
-
case condition
-
when Array; sanitize_sql_array(condition)
-
when Hash; sanitize_sql_hash_for_conditions(condition, table_name)
-
else condition
-
end
-
end
-
1
alias_method :sanitize_sql, :sanitize_sql_for_conditions
-
1
alias_method :sanitize_conditions, :sanitize_sql
-
-
# Accepts an array, hash, or string of SQL conditions and sanitizes
-
# them into a valid SQL fragment for a SET clause.
-
# { name: nil, group_id: 4 } returns "name = NULL , group_id='4'"
-
1
def sanitize_sql_for_assignment(assignments, default_table_name = self.table_name)
-
case assignments
-
when Array; sanitize_sql_array(assignments)
-
when Hash; sanitize_sql_hash_for_assignment(assignments, default_table_name)
-
else assignments
-
end
-
end
-
-
# Accepts a hash of SQL conditions and replaces those attributes
-
# that correspond to a +composed_of+ relationship with their expanded
-
# aggregate attribute values.
-
# Given:
-
# class Person < ActiveRecord::Base
-
# composed_of :address, class_name: "Address",
-
# mapping: [%w(address_street street), %w(address_city city)]
-
# end
-
# Then:
-
# { address: Address.new("813 abc st.", "chicago") }
-
# # => { address_street: "813 abc st.", address_city: "chicago" }
-
1
def expand_hash_conditions_for_aggregates(attrs)
-
expanded_attrs = {}
-
attrs.each do |attr, value|
-
if aggregation = reflect_on_aggregation(attr.to_sym)
-
mapping = aggregation.mapping
-
mapping.each do |field_attr, aggregate_attr|
-
if mapping.size == 1 && !value.respond_to?(aggregate_attr)
-
expanded_attrs[field_attr] = value
-
else
-
expanded_attrs[field_attr] = value.send(aggregate_attr)
-
end
-
end
-
else
-
expanded_attrs[attr] = value
-
end
-
end
-
expanded_attrs
-
end
-
-
# Sanitizes a hash of attribute/value pairs into SQL conditions for a WHERE clause.
-
# { name: "foo'bar", group_id: 4 }
-
# # => "name='foo''bar' and group_id= 4"
-
# { status: nil, group_id: [1,2,3] }
-
# # => "status IS NULL and group_id IN (1,2,3)"
-
# { age: 13..18 }
-
# # => "age BETWEEN 13 AND 18"
-
# { 'other_records.id' => 7 }
-
# # => "`other_records`.`id` = 7"
-
# { other_records: { id: 7 } }
-
# # => "`other_records`.`id` = 7"
-
# And for value objects on a composed_of relationship:
-
# { address: Address.new("123 abc st.", "chicago") }
-
# # => "address_street='123 abc st.' and address_city='chicago'"
-
1
def sanitize_sql_hash_for_conditions(attrs, default_table_name = self.table_name)
-
attrs = PredicateBuilder.resolve_column_aliases self, attrs
-
attrs = expand_hash_conditions_for_aggregates(attrs)
-
-
table = Arel::Table.new(table_name, arel_engine).alias(default_table_name)
-
PredicateBuilder.build_from_hash(self, attrs, table).map { |b|
-
connection.visitor.accept b
-
}.join(' AND ')
-
end
-
1
alias_method :sanitize_sql_hash, :sanitize_sql_hash_for_conditions
-
-
# Sanitizes a hash of attribute/value pairs into SQL conditions for a SET clause.
-
# { status: nil, group_id: 1 }
-
# # => "status = NULL , group_id = 1"
-
1
def sanitize_sql_hash_for_assignment(attrs, table)
-
c = connection
-
attrs.map do |attr, value|
-
"#{c.quote_table_name_for_assignment(table, attr)} = #{quote_bound_value(value, c, columns_hash[attr.to_s])}"
-
end.join(', ')
-
end
-
-
# Accepts an array of conditions. The array has each value
-
# sanitized and interpolated into the SQL statement.
-
# ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'"
-
1
def sanitize_sql_array(ary)
-
statement, *values = ary
-
if values.first.is_a?(Hash) && statement =~ /:\w+/
-
replace_named_bind_variables(statement, values.first)
-
elsif statement.include?('?')
-
replace_bind_variables(statement, values)
-
elsif statement.blank?
-
statement
-
else
-
statement % values.collect { |value| connection.quote_string(value.to_s) }
-
end
-
end
-
-
1
def replace_bind_variables(statement, values) #:nodoc:
-
raise_if_bind_arity_mismatch(statement, statement.count('?'), values.size)
-
bound = values.dup
-
c = connection
-
statement.gsub('?') do
-
replace_bind_variable(bound.shift, c)
-
end
-
end
-
-
1
def replace_bind_variable(value, c = connection) #:nodoc:
-
if ActiveRecord::Relation === value
-
value.to_sql
-
else
-
quote_bound_value(value, c)
-
end
-
end
-
-
1
def replace_named_bind_variables(statement, bind_vars) #:nodoc:
-
statement.gsub(/(:?):([a-zA-Z]\w*)/) do
-
if $1 == ':' # skip postgresql casts
-
$& # return the whole match
-
elsif bind_vars.include?(match = $2.to_sym)
-
replace_bind_variable(bind_vars[match])
-
else
-
raise PreparedStatementInvalid, "missing value for :#{match} in #{statement}"
-
end
-
end
-
end
-
-
1
def quote_bound_value(value, c = connection, column = nil) #:nodoc:
-
if column
-
c.quote(value, column)
-
elsif value.respond_to?(:map) && !value.acts_like?(:string)
-
if value.respond_to?(:empty?) && value.empty?
-
c.quote(nil)
-
else
-
value.map { |v| c.quote(v) }.join(',')
-
end
-
else
-
c.quote(value)
-
end
-
end
-
-
1
def raise_if_bind_arity_mismatch(statement, expected, provided) #:nodoc:
-
unless expected == provided
-
raise PreparedStatementInvalid, "wrong number of bind variables (#{provided} for #{expected}) in: #{statement}"
-
end
-
end
-
end
-
-
# TODO: Deprecate this
-
1
def quoted_id
-
self.class.quote_value(id, column_for_attribute(self.class.primary_key))
-
end
-
end
-
end
-
1
require 'active_record/scoping/default'
-
1
require 'active_record/scoping/named'
-
1
require 'active_record/base'
-
-
1
module ActiveRecord
-
1
class SchemaMigration < ActiveRecord::Base
-
1
class << self
-
-
1
def table_name
-
1
"#{table_name_prefix}#{ActiveRecord::Base.schema_migrations_table_name}#{table_name_suffix}"
-
end
-
-
1
def index_name
-
"#{table_name_prefix}unique_#{ActiveRecord::Base.schema_migrations_table_name}#{table_name_suffix}"
-
end
-
-
1
def table_exists?
-
connection.table_exists?(table_name)
-
end
-
-
1
def create_table(limit=nil)
-
unless table_exists?
-
version_options = {null: false}
-
version_options[:limit] = limit if limit
-
-
connection.create_table(table_name, id: false) do |t|
-
t.column :version, :string, version_options
-
end
-
connection.add_index table_name, :version, unique: true, name: index_name
-
end
-
end
-
-
1
def drop_table
-
if table_exists?
-
connection.remove_index table_name, name: index_name
-
connection.drop_table(table_name)
-
end
-
end
-
end
-
-
1
def version
-
super.to_i
-
end
-
end
-
end
-
1
require 'active_support/per_thread_registry'
-
-
1
module ActiveRecord
-
1
module Scoping
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
include Default
-
1
include Named
-
end
-
-
1
module ClassMethods
-
1
def current_scope #:nodoc:
-
ScopeRegistry.value_for(:current_scope, base_class.to_s)
-
end
-
-
1
def current_scope=(scope) #:nodoc:
-
ScopeRegistry.set_value_for(:current_scope, base_class.to_s, scope)
-
end
-
end
-
-
1
def populate_with_current_scope_attributes
-
return unless self.class.scope_attributes?
-
-
self.class.scope_attributes.each do |att,value|
-
send("#{att}=", value) if respond_to?("#{att}=")
-
end
-
end
-
-
1
def initialize_internals_callback
-
super
-
populate_with_current_scope_attributes
-
end
-
-
# This class stores the +:current_scope+ and +:ignore_default_scope+ values
-
# for different classes. The registry is stored as a thread local, which is
-
# accessed through +ScopeRegistry.current+.
-
#
-
# This class allows you to store and get the scope values on different
-
# classes and different types of scopes. For example, if you are attempting
-
# to get the current_scope for the +Board+ model, then you would use the
-
# following code:
-
#
-
# registry = ActiveRecord::Scoping::ScopeRegistry
-
# registry.set_value_for(:current_scope, "Board", some_new_scope)
-
#
-
# Now when you run:
-
#
-
# registry.value_for(:current_scope, "Board")
-
#
-
# You will obtain whatever was defined in +some_new_scope+. The +value_for+
-
# and +set_value_for+ methods are delegated to the current +ScopeRegistry+
-
# object, so the above example code can also be called as:
-
#
-
# ActiveRecord::Scoping::ScopeRegistry.set_value_for(:current_scope,
-
# "Board", some_new_scope)
-
1
class ScopeRegistry # :nodoc:
-
1
extend ActiveSupport::PerThreadRegistry
-
-
1
VALID_SCOPE_TYPES = [:current_scope, :ignore_default_scope]
-
-
1
def initialize
-
@registry = Hash.new { |hash, key| hash[key] = {} }
-
end
-
-
# Obtains the value for a given +scope_name+ and +variable_name+.
-
1
def value_for(scope_type, variable_name)
-
raise_invalid_scope_type!(scope_type)
-
@registry[scope_type][variable_name]
-
end
-
-
# Sets the +value+ for a given +scope_type+ and +variable_name+.
-
1
def set_value_for(scope_type, variable_name, value)
-
raise_invalid_scope_type!(scope_type)
-
@registry[scope_type][variable_name] = value
-
end
-
-
1
private
-
-
1
def raise_invalid_scope_type!(scope_type)
-
if !VALID_SCOPE_TYPES.include?(scope_type)
-
raise ArgumentError, "Invalid scope type '#{scope_type}' sent to the registry. Scope types must be included in VALID_SCOPE_TYPES"
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Scoping
-
1
module Default
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
# Stores the default scope for the class.
-
1
class_attribute :default_scopes, instance_writer: false, instance_predicate: false
-
-
1
self.default_scopes = []
-
end
-
-
1
module ClassMethods
-
# Returns a scope for the model without the +default_scope+.
-
#
-
# class Post < ActiveRecord::Base
-
# def self.default_scope
-
# where published: true
-
# end
-
# end
-
#
-
# Post.all # Fires "SELECT * FROM posts WHERE published = true"
-
# Post.unscoped.all # Fires "SELECT * FROM posts"
-
#
-
# This method also accepts a block. All queries inside the block will
-
# not use the +default_scope+:
-
#
-
# Post.unscoped {
-
# Post.limit(10) # Fires "SELECT * FROM posts LIMIT 10"
-
# }
-
1
def unscoped
-
block_given? ? relation.scoping { yield } : relation
-
end
-
-
1
def before_remove_const #:nodoc:
-
self.current_scope = nil
-
end
-
-
1
protected
-
-
# Use this macro in your model to set a default scope for all operations on
-
# the model.
-
#
-
# class Article < ActiveRecord::Base
-
# default_scope { where(published: true) }
-
# end
-
#
-
# Article.all # => SELECT * FROM articles WHERE published = true
-
#
-
# The +default_scope+ is also applied while creating/building a record.
-
# It is not applied while updating a record.
-
#
-
# Article.new.published # => true
-
# Article.create.published # => true
-
#
-
# (You can also pass any object which responds to +call+ to the
-
# +default_scope+ macro, and it will be called when building the
-
# default scope.)
-
#
-
# If you use multiple +default_scope+ declarations in your model then
-
# they will be merged together:
-
#
-
# class Article < ActiveRecord::Base
-
# default_scope { where(published: true) }
-
# default_scope { where(rating: 'G') }
-
# end
-
#
-
# Article.all # => SELECT * FROM articles WHERE published = true AND rating = 'G'
-
#
-
# This is also the case with inheritance and module includes where the
-
# parent or module defines a +default_scope+ and the child or including
-
# class defines a second one.
-
#
-
# If you need to do more complex things with a default scope, you can
-
# alternatively define it as a class method:
-
#
-
# class Article < ActiveRecord::Base
-
# def self.default_scope
-
# # Should return a scope, you can call 'super' here etc.
-
# end
-
# end
-
1
def default_scope(scope = nil)
-
scope = Proc.new if block_given?
-
-
if scope.is_a?(Relation) || !scope.respond_to?(:call)
-
raise ArgumentError,
-
"Support for calling #default_scope without a block is removed. For example instead " \
-
"of `default_scope where(color: 'red')`, please use " \
-
"`default_scope { where(color: 'red') }`. (Alternatively you can just redefine " \
-
"self.default_scope.)"
-
end
-
-
self.default_scopes += [scope]
-
end
-
-
1
def build_default_scope # :nodoc:
-
if !Base.is_a?(method(:default_scope).owner)
-
# The user has defined their own default scope method, so call that
-
evaluate_default_scope { default_scope }
-
elsif default_scopes.any?
-
evaluate_default_scope do
-
default_scopes.inject(relation) do |default_scope, scope|
-
default_scope.merge(unscoped { scope.call })
-
end
-
end
-
end
-
end
-
-
1
def ignore_default_scope? # :nodoc:
-
ScopeRegistry.value_for(:ignore_default_scope, self)
-
end
-
-
1
def ignore_default_scope=(ignore) # :nodoc:
-
ScopeRegistry.set_value_for(:ignore_default_scope, self, ignore)
-
end
-
-
# The ignore_default_scope flag is used to prevent an infinite recursion
-
# situation where a default scope references a scope which has a default
-
# scope which references a scope...
-
1
def evaluate_default_scope # :nodoc:
-
return if ignore_default_scope?
-
-
begin
-
self.ignore_default_scope = true
-
yield
-
ensure
-
self.ignore_default_scope = false
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/array'
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/kernel/singleton_class'
-
-
1
module ActiveRecord
-
# = Active Record \Named \Scopes
-
1
module Scoping
-
1
module Named
-
1
extend ActiveSupport::Concern
-
-
1
module ClassMethods
-
# Returns an <tt>ActiveRecord::Relation</tt> scope object.
-
#
-
# posts = Post.all
-
# posts.size # Fires "select count(*) from posts" and returns the count
-
# posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects
-
#
-
# fruits = Fruit.all
-
# fruits = fruits.where(color: 'red') if options[:red_only]
-
# fruits = fruits.limit(10) if limited?
-
#
-
# You can define a scope that applies to all finders using
-
# <tt>ActiveRecord::Base.default_scope</tt>.
-
1
def all
-
if current_scope
-
current_scope.clone
-
else
-
default_scoped
-
end
-
end
-
-
1
def default_scoped # :nodoc:
-
relation.merge(build_default_scope)
-
end
-
-
# Collects attributes from scopes that should be applied when creating
-
# an AR instance for the particular class this is called on.
-
1
def scope_attributes # :nodoc:
-
all.scope_for_create
-
end
-
-
# Are there default attributes associated with this scope?
-
1
def scope_attributes? # :nodoc:
-
current_scope || default_scopes.any?
-
end
-
-
# Adds a class method for retrieving and querying objects. A \scope
-
# represents a narrowing of a database query, such as
-
# <tt>where(color: :red).select('shirts.*').includes(:washing_instructions)</tt>.
-
#
-
# class Shirt < ActiveRecord::Base
-
# scope :red, -> { where(color: 'red') }
-
# scope :dry_clean_only, -> { joins(:washing_instructions).where('washing_instructions.dry_clean_only = ?', true) }
-
# end
-
#
-
# The above calls to +scope+ define class methods <tt>Shirt.red</tt> and
-
# <tt>Shirt.dry_clean_only</tt>. <tt>Shirt.red</tt>, in effect,
-
# represents the query <tt>Shirt.where(color: 'red')</tt>.
-
#
-
# You should always pass a callable object to the scopes defined
-
# with +scope+. This ensures that the scope is re-evaluated each
-
# time it is called.
-
#
-
# Note that this is simply 'syntactic sugar' for defining an actual
-
# class method:
-
#
-
# class Shirt < ActiveRecord::Base
-
# def self.red
-
# where(color: 'red')
-
# end
-
# end
-
#
-
# Unlike <tt>Shirt.find(...)</tt>, however, the object returned by
-
# <tt>Shirt.red</tt> is not an Array; it resembles the association object
-
# constructed by a +has_many+ declaration. For instance, you can invoke
-
# <tt>Shirt.red.first</tt>, <tt>Shirt.red.count</tt>,
-
# <tt>Shirt.red.where(size: 'small')</tt>. Also, just as with the
-
# association objects, named \scopes act like an Array, implementing
-
# Enumerable; <tt>Shirt.red.each(&block)</tt>, <tt>Shirt.red.first</tt>,
-
# and <tt>Shirt.red.inject(memo, &block)</tt> all behave as if
-
# <tt>Shirt.red</tt> really was an Array.
-
#
-
# These named \scopes are composable. For instance,
-
# <tt>Shirt.red.dry_clean_only</tt> will produce all shirts that are
-
# both red and dry clean only. Nested finds and calculations also work
-
# with these compositions: <tt>Shirt.red.dry_clean_only.count</tt>
-
# returns the number of garments for which these criteria obtain.
-
# Similarly with <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>.
-
#
-
# All scopes are available as class methods on the ActiveRecord::Base
-
# descendant upon which the \scopes were defined. But they are also
-
# available to +has_many+ associations. If,
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :shirts
-
# end
-
#
-
# then <tt>elton.shirts.red.dry_clean_only</tt> will return all of
-
# Elton's red, dry clean only shirts.
-
#
-
# \Named scopes can also have extensions, just as with +has_many+
-
# declarations:
-
#
-
# class Shirt < ActiveRecord::Base
-
# scope :red, -> { where(color: 'red') } do
-
# def dom_id
-
# 'red_shirts'
-
# end
-
# end
-
# end
-
#
-
# Scopes can also be used while creating/building a record.
-
#
-
# class Article < ActiveRecord::Base
-
# scope :published, -> { where(published: true) }
-
# end
-
#
-
# Article.published.new.published # => true
-
# Article.published.create.published # => true
-
#
-
# \Class methods on your model are automatically available
-
# on scopes. Assuming the following setup:
-
#
-
# class Article < ActiveRecord::Base
-
# scope :published, -> { where(published: true) }
-
# scope :featured, -> { where(featured: true) }
-
#
-
# def self.latest_article
-
# order('published_at desc').first
-
# end
-
#
-
# def self.titles
-
# pluck(:title)
-
# end
-
# end
-
#
-
# We are able to call the methods like this:
-
#
-
# Article.published.featured.latest_article
-
# Article.featured.titles
-
1
def scope(name, body, &block)
-
if dangerous_class_method?(name)
-
raise ArgumentError, "You tried to define a scope named \"#{name}\" " \
-
"on the model \"#{self.name}\", but Active Record already defined " \
-
"a class method with the same name."
-
end
-
-
extension = Module.new(&block) if block
-
-
singleton_class.send(:define_method, name) do |*args|
-
scope = all.scoping { body.call(*args) }
-
scope = scope.extending(extension) if extension
-
-
scope || all
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord #:nodoc:
-
# = Active Record Serialization
-
1
module Serialization
-
1
extend ActiveSupport::Concern
-
1
include ActiveModel::Serializers::JSON
-
-
1
included do
-
1
self.include_root_in_json = false
-
end
-
-
1
def serializable_hash(options = nil)
-
options = options.try(:clone) || {}
-
-
options[:except] = Array(options[:except]).map { |n| n.to_s }
-
options[:except] |= Array(self.class.inheritance_column)
-
-
super(options)
-
end
-
end
-
end
-
-
1
require 'active_record/serializers/xml_serializer'
-
1
require 'active_support/core_ext/hash/conversions'
-
-
1
module ActiveRecord #:nodoc:
-
1
module Serialization
-
1
include ActiveModel::Serializers::Xml
-
-
# Builds an XML document to represent the model. Some configuration is
-
# available through +options+. However more complicated cases should
-
# override ActiveRecord::Base#to_xml.
-
#
-
# By default the generated XML document will include the processing
-
# instruction and all the object's attributes. For example:
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <topic>
-
# <title>The First Topic</title>
-
# <author-name>David</author-name>
-
# <id type="integer">1</id>
-
# <approved type="boolean">false</approved>
-
# <replies-count type="integer">0</replies-count>
-
# <bonus-time type="dateTime">2000-01-01T08:28:00+12:00</bonus-time>
-
# <written-on type="dateTime">2003-07-16T09:28:00+1200</written-on>
-
# <content>Have a nice day</content>
-
# <author-email-address>david@loudthinking.com</author-email-address>
-
# <parent-id></parent-id>
-
# <last-read type="date">2004-04-15</last-read>
-
# </topic>
-
#
-
# This behavior can be controlled with <tt>:only</tt>, <tt>:except</tt>,
-
# <tt>:skip_instruct</tt>, <tt>:skip_types</tt>, <tt>:dasherize</tt> and <tt>:camelize</tt> .
-
# The <tt>:only</tt> and <tt>:except</tt> options are the same as for the
-
# +attributes+ method. The default is to dasherize all column names, but you
-
# can disable this setting <tt>:dasherize</tt> to +false+. Setting <tt>:camelize</tt>
-
# to +true+ will camelize all column names - this also overrides <tt>:dasherize</tt>.
-
# To not have the column type included in the XML output set <tt>:skip_types</tt> to +true+.
-
#
-
# For instance:
-
#
-
# topic.to_xml(skip_instruct: true, except: [ :id, :bonus_time, :written_on, :replies_count ])
-
#
-
# <topic>
-
# <title>The First Topic</title>
-
# <author-name>David</author-name>
-
# <approved type="boolean">false</approved>
-
# <content>Have a nice day</content>
-
# <author-email-address>david@loudthinking.com</author-email-address>
-
# <parent-id></parent-id>
-
# <last-read type="date">2004-04-15</last-read>
-
# </topic>
-
#
-
# To include first level associations use <tt>:include</tt>:
-
#
-
# firm.to_xml include: [ :account, :clients ]
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <firm>
-
# <id type="integer">1</id>
-
# <rating type="integer">1</rating>
-
# <name>37signals</name>
-
# <clients type="array">
-
# <client>
-
# <rating type="integer">1</rating>
-
# <name>Summit</name>
-
# </client>
-
# <client>
-
# <rating type="integer">1</rating>
-
# <name>Microsoft</name>
-
# </client>
-
# </clients>
-
# <account>
-
# <id type="integer">1</id>
-
# <credit-limit type="integer">50</credit-limit>
-
# </account>
-
# </firm>
-
#
-
# Additionally, the record being serialized will be passed to a Proc's second
-
# parameter. This allows for ad hoc additions to the resultant document that
-
# incorporate the context of the record being serialized. And by leveraging the
-
# closure created by a Proc, to_xml can be used to add elements that normally fall
-
# outside of the scope of the model -- for example, generating and appending URLs
-
# associated with models.
-
#
-
# proc = Proc.new { |options, record| options[:builder].tag!('name-reverse', record.name.reverse) }
-
# firm.to_xml procs: [ proc ]
-
#
-
# <firm>
-
# # ... normal attributes as shown above ...
-
# <name-reverse>slangis73</name-reverse>
-
# </firm>
-
#
-
# To include deeper levels of associations pass a hash like this:
-
#
-
# firm.to_xml include: {account: {}, clients: {include: :address}}
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <firm>
-
# <id type="integer">1</id>
-
# <rating type="integer">1</rating>
-
# <name>37signals</name>
-
# <clients type="array">
-
# <client>
-
# <rating type="integer">1</rating>
-
# <name>Summit</name>
-
# <address>
-
# ...
-
# </address>
-
# </client>
-
# <client>
-
# <rating type="integer">1</rating>
-
# <name>Microsoft</name>
-
# <address>
-
# ...
-
# </address>
-
# </client>
-
# </clients>
-
# <account>
-
# <id type="integer">1</id>
-
# <credit-limit type="integer">50</credit-limit>
-
# </account>
-
# </firm>
-
#
-
# To include any methods on the model being called use <tt>:methods</tt>:
-
#
-
# firm.to_xml methods: [ :calculated_earnings, :real_earnings ]
-
#
-
# <firm>
-
# # ... normal attributes as shown above ...
-
# <calculated-earnings>100000000000000000</calculated-earnings>
-
# <real-earnings>5</real-earnings>
-
# </firm>
-
#
-
# To call any additional Procs use <tt>:procs</tt>. The Procs are passed a
-
# modified version of the options hash that was given to +to_xml+:
-
#
-
# proc = Proc.new { |options| options[:builder].tag!('abc', 'def') }
-
# firm.to_xml procs: [ proc ]
-
#
-
# <firm>
-
# # ... normal attributes as shown above ...
-
# <abc>def</abc>
-
# </firm>
-
#
-
# Alternatively, you can yield the builder object as part of the +to_xml+ call:
-
#
-
# firm.to_xml do |xml|
-
# xml.creator do
-
# xml.first_name "David"
-
# xml.last_name "Heinemeier Hansson"
-
# end
-
# end
-
#
-
# <firm>
-
# # ... normal attributes as shown above ...
-
# <creator>
-
# <first_name>David</first_name>
-
# <last_name>Heinemeier Hansson</last_name>
-
# </creator>
-
# </firm>
-
#
-
# As noted above, you may override +to_xml+ in your ActiveRecord::Base
-
# subclasses to have complete control about what's generated. The general
-
# form of doing this is:
-
#
-
# class IHaveMyOwnXML < ActiveRecord::Base
-
# def to_xml(options = {})
-
# require 'builder'
-
# options[:indent] ||= 2
-
# xml = options[:builder] ||= ::Builder::XmlMarkup.new(indent: options[:indent])
-
# xml.instruct! unless options[:skip_instruct]
-
# xml.level_one do
-
# xml.tag!(:second_level, 'content')
-
# end
-
# end
-
# end
-
1
def to_xml(options = {}, &block)
-
XmlSerializer.new(self, options).serialize(&block)
-
end
-
end
-
-
1
class XmlSerializer < ActiveModel::Serializers::Xml::Serializer #:nodoc:
-
1
class Attribute < ActiveModel::Serializers::Xml::Serializer::Attribute #:nodoc:
-
1
def compute_type
-
klass = @serializable.class
-
type = if klass.serialized_attributes.key?(name)
-
super
-
elsif klass.columns_hash.key?(name)
-
klass.columns_hash[name].type
-
else
-
NilClass
-
end
-
-
{ :text => :string,
-
:time => :datetime }[type] || type
-
end
-
1
protected :compute_type
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/indifferent_access'
-
-
1
module ActiveRecord
-
# Store gives you a thin wrapper around serialize for the purpose of storing hashes in a single column.
-
# It's like a simple key/value store baked into your record when you don't care about being able to
-
# query that store outside the context of a single record.
-
#
-
# You can then declare accessors to this store that are then accessible just like any other attribute
-
# of the model. This is very helpful for easily exposing store keys to a form or elsewhere that's
-
# already built around just accessing attributes on the model.
-
#
-
# Make sure that you declare the database column used for the serialized store as a text, so there's
-
# plenty of room.
-
#
-
# You can set custom coder to encode/decode your serialized attributes to/from different formats.
-
# JSON, YAML, Marshal are supported out of the box. Generally it can be any wrapper that provides +load+ and +dump+.
-
#
-
# NOTE - If you are using PostgreSQL specific columns like +hstore+ or +json+ there is no need for
-
# the serialization provided by +store+. Simply use +store_accessor+ instead to generate
-
# the accessor methods. Be aware that these columns use a string keyed hash and do not allow access
-
# using a symbol.
-
#
-
# Examples:
-
#
-
# class User < ActiveRecord::Base
-
# store :settings, accessors: [ :color, :homepage ], coder: JSON
-
# end
-
#
-
# u = User.new(color: 'black', homepage: '37signals.com')
-
# u.color # Accessor stored attribute
-
# u.settings[:country] = 'Denmark' # Any attribute, even if not specified with an accessor
-
#
-
# # There is no difference between strings and symbols for accessing custom attributes
-
# u.settings[:country] # => 'Denmark'
-
# u.settings['country'] # => 'Denmark'
-
#
-
# # Add additional accessors to an existing store through store_accessor
-
# class SuperUser < User
-
# store_accessor :settings, :privileges, :servants
-
# end
-
#
-
# The stored attribute names can be retrieved using +stored_attributes+.
-
#
-
# User.stored_attributes[:settings] # [:color, :homepage]
-
#
-
# == Overwriting default accessors
-
#
-
# All stored values are automatically available through accessors on the Active Record
-
# object, but sometimes you want to specialize this behavior. This can be done by overwriting
-
# the default accessors (using the same name as the attribute) and calling <tt>super</tt>
-
# to actually change things.
-
#
-
# class Song < ActiveRecord::Base
-
# # Uses a stored integer to hold the volume adjustment of the song
-
# store :settings, accessors: [:volume_adjustment]
-
#
-
# def volume_adjustment=(decibels)
-
# super(decibels.to_i)
-
# end
-
#
-
# def volume_adjustment
-
# super.to_i
-
# end
-
# end
-
1
module Store
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
class_attribute :stored_attributes, instance_accessor: false
-
1
self.stored_attributes = {}
-
end
-
-
1
module ClassMethods
-
1
def store(store_attribute, options = {})
-
serialize store_attribute, IndifferentCoder.new(options[:coder])
-
store_accessor(store_attribute, options[:accessors]) if options.has_key? :accessors
-
end
-
-
1
def store_accessor(store_attribute, *keys)
-
keys = keys.flatten
-
-
_store_accessors_module.module_eval do
-
keys.each do |key|
-
define_method("#{key}=") do |value|
-
write_store_attribute(store_attribute, key, value)
-
end
-
-
define_method(key) do
-
read_store_attribute(store_attribute, key)
-
end
-
end
-
end
-
-
# assign new store attribute and create new hash to ensure that each class in the hierarchy
-
# has its own hash of stored attributes.
-
self.stored_attributes = {} if self.stored_attributes.blank?
-
self.stored_attributes[store_attribute] ||= []
-
self.stored_attributes[store_attribute] |= keys
-
end
-
-
1
def _store_accessors_module
-
@_store_accessors_module ||= begin
-
mod = Module.new
-
include mod
-
mod
-
end
-
end
-
end
-
-
1
protected
-
1
def read_store_attribute(store_attribute, key)
-
accessor = store_accessor_for(store_attribute)
-
accessor.read(self, store_attribute, key)
-
end
-
-
1
def write_store_attribute(store_attribute, key, value)
-
accessor = store_accessor_for(store_attribute)
-
accessor.write(self, store_attribute, key, value)
-
end
-
-
1
private
-
1
def store_accessor_for(store_attribute)
-
@column_types[store_attribute.to_s].accessor
-
end
-
-
1
class HashAccessor
-
1
def self.read(object, attribute, key)
-
prepare(object, attribute)
-
object.public_send(attribute)[key]
-
end
-
-
1
def self.write(object, attribute, key, value)
-
prepare(object, attribute)
-
if value != read(object, attribute, key)
-
object.public_send :"#{attribute}_will_change!"
-
object.public_send(attribute)[key] = value
-
end
-
end
-
-
1
def self.prepare(object, attribute)
-
object.public_send :"#{attribute}=", {} unless object.send(attribute)
-
end
-
end
-
-
1
class StringKeyedHashAccessor < HashAccessor
-
1
def self.read(object, attribute, key)
-
super object, attribute, key.to_s
-
end
-
-
1
def self.write(object, attribute, key, value)
-
super object, attribute, key.to_s, value
-
end
-
end
-
-
1
class IndifferentHashAccessor < ActiveRecord::Store::HashAccessor
-
1
def self.prepare(object, store_attribute)
-
attribute = object.send(store_attribute)
-
unless attribute.is_a?(ActiveSupport::HashWithIndifferentAccess)
-
attribute = IndifferentCoder.as_indifferent_hash(attribute)
-
object.send :"#{store_attribute}=", attribute
-
end
-
attribute
-
end
-
end
-
-
1
class IndifferentCoder # :nodoc:
-
1
def initialize(coder_or_class_name)
-
@coder =
-
if coder_or_class_name.respond_to?(:load) && coder_or_class_name.respond_to?(:dump)
-
coder_or_class_name
-
else
-
ActiveRecord::Coders::YAMLColumn.new(coder_or_class_name || Object)
-
end
-
end
-
-
1
def dump(obj)
-
@coder.dump self.class.as_indifferent_hash(obj)
-
end
-
-
1
def load(yaml)
-
self.class.as_indifferent_hash(@coder.load(yaml || ''))
-
end
-
-
1
def self.as_indifferent_hash(obj)
-
case obj
-
when ActiveSupport::HashWithIndifferentAccess
-
obj
-
when Hash
-
obj.with_indifferent_access
-
else
-
ActiveSupport::HashWithIndifferentAccess.new
-
end
-
end
-
end
-
end
-
end
-
1
require 'thread'
-
-
1
module ActiveRecord
-
# See ActiveRecord::Transactions::ClassMethods for documentation.
-
1
module Transactions
-
1
extend ActiveSupport::Concern
-
1
ACTIONS = [:create, :destroy, :update]
-
-
1
included do
-
1
define_callbacks :commit, :rollback,
-
terminator: ->(_, result) { result == false },
-
scope: [:kind, :name]
-
end
-
-
# = Active Record Transactions
-
#
-
# Transactions are protective blocks where SQL statements are only permanent
-
# if they can all succeed as one atomic action. The classic example is a
-
# transfer between two accounts where you can only have a deposit if the
-
# withdrawal succeeded and vice versa. Transactions enforce the integrity of
-
# the database and guard the data against program errors or database
-
# break-downs. So basically you should use transaction blocks whenever you
-
# have a number of statements that must be executed together or not at all.
-
#
-
# For example:
-
#
-
# ActiveRecord::Base.transaction do
-
# david.withdrawal(100)
-
# mary.deposit(100)
-
# end
-
#
-
# This example will only take money from David and give it to Mary if neither
-
# +withdrawal+ nor +deposit+ raise an exception. Exceptions will force a
-
# ROLLBACK that returns the database to the state before the transaction
-
# began. Be aware, though, that the objects will _not_ have their instance
-
# data returned to their pre-transactional state.
-
#
-
# == Different Active Record classes in a single transaction
-
#
-
# Though the transaction class method is called on some Active Record class,
-
# the objects within the transaction block need not all be instances of
-
# that class. This is because transactions are per-database connection, not
-
# per-model.
-
#
-
# In this example a +balance+ record is transactionally saved even
-
# though +transaction+ is called on the +Account+ class:
-
#
-
# Account.transaction do
-
# balance.save!
-
# account.save!
-
# end
-
#
-
# The +transaction+ method is also available as a model instance method.
-
# For example, you can also do this:
-
#
-
# balance.transaction do
-
# balance.save!
-
# account.save!
-
# end
-
#
-
# == Transactions are not distributed across database connections
-
#
-
# A transaction acts on a single database connection. If you have
-
# multiple class-specific databases, the transaction will not protect
-
# interaction among them. One workaround is to begin a transaction
-
# on each class whose models you alter:
-
#
-
# Student.transaction do
-
# Course.transaction do
-
# course.enroll(student)
-
# student.units += course.units
-
# end
-
# end
-
#
-
# This is a poor solution, but fully distributed transactions are beyond
-
# the scope of Active Record.
-
#
-
# == +save+ and +destroy+ are automatically wrapped in a transaction
-
#
-
# Both +save+ and +destroy+ come wrapped in a transaction that ensures
-
# that whatever you do in validations or callbacks will happen under its
-
# protected cover. So you can use validations to check for values that
-
# the transaction depends on or you can raise exceptions in the callbacks
-
# to rollback, including <tt>after_*</tt> callbacks.
-
#
-
# As a consequence changes to the database are not seen outside your connection
-
# until the operation is complete. For example, if you try to update the index
-
# of a search engine in +after_save+ the indexer won't see the updated record.
-
# The +after_commit+ callback is the only one that is triggered once the update
-
# is committed. See below.
-
#
-
# == Exception handling and rolling back
-
#
-
# Also have in mind that exceptions thrown within a transaction block will
-
# be propagated (after triggering the ROLLBACK), so you should be ready to
-
# catch those in your application code.
-
#
-
# One exception is the <tt>ActiveRecord::Rollback</tt> exception, which will trigger
-
# a ROLLBACK when raised, but not be re-raised by the transaction block.
-
#
-
# *Warning*: one should not catch <tt>ActiveRecord::StatementInvalid</tt> exceptions
-
# inside a transaction block. <tt>ActiveRecord::StatementInvalid</tt> exceptions indicate that an
-
# error occurred at the database level, for example when a unique constraint
-
# is violated. On some database systems, such as PostgreSQL, database errors
-
# inside a transaction cause the entire transaction to become unusable
-
# until it's restarted from the beginning. Here is an example which
-
# demonstrates the problem:
-
#
-
# # Suppose that we have a Number model with a unique column called 'i'.
-
# Number.transaction do
-
# Number.create(i: 0)
-
# begin
-
# # This will raise a unique constraint error...
-
# Number.create(i: 0)
-
# rescue ActiveRecord::StatementInvalid
-
# # ...which we ignore.
-
# end
-
#
-
# # On PostgreSQL, the transaction is now unusable. The following
-
# # statement will cause a PostgreSQL error, even though the unique
-
# # constraint is no longer violated:
-
# Number.create(i: 1)
-
# # => "PGError: ERROR: current transaction is aborted, commands
-
# # ignored until end of transaction block"
-
# end
-
#
-
# One should restart the entire transaction if an
-
# <tt>ActiveRecord::StatementInvalid</tt> occurred.
-
#
-
# == Nested transactions
-
#
-
# +transaction+ calls can be nested. By default, this makes all database
-
# statements in the nested transaction block become part of the parent
-
# transaction. For example, the following behavior may be surprising:
-
#
-
# User.transaction do
-
# User.create(username: 'Kotori')
-
# User.transaction do
-
# User.create(username: 'Nemu')
-
# raise ActiveRecord::Rollback
-
# end
-
# end
-
#
-
# creates both "Kotori" and "Nemu". Reason is the <tt>ActiveRecord::Rollback</tt>
-
# exception in the nested block does not issue a ROLLBACK. Since these exceptions
-
# are captured in transaction blocks, the parent block does not see it and the
-
# real transaction is committed.
-
#
-
# In order to get a ROLLBACK for the nested transaction you may ask for a real
-
# sub-transaction by passing <tt>requires_new: true</tt>. If anything goes wrong,
-
# the database rolls back to the beginning of the sub-transaction without rolling
-
# back the parent transaction. If we add it to the previous example:
-
#
-
# User.transaction do
-
# User.create(username: 'Kotori')
-
# User.transaction(requires_new: true) do
-
# User.create(username: 'Nemu')
-
# raise ActiveRecord::Rollback
-
# end
-
# end
-
#
-
# only "Kotori" is created. This works on MySQL and PostgreSQL. SQLite3 version >= '3.6.8' also supports it.
-
#
-
# Most databases don't support true nested transactions. At the time of
-
# writing, the only database that we're aware of that supports true nested
-
# transactions, is MS-SQL. Because of this, Active Record emulates nested
-
# transactions by using savepoints on MySQL and PostgreSQL. See
-
# http://dev.mysql.com/doc/refman/5.6/en/savepoint.html
-
# for more information about savepoints.
-
#
-
# === Callbacks
-
#
-
# There are two types of callbacks associated with committing and rolling back transactions:
-
# +after_commit+ and +after_rollback+.
-
#
-
# +after_commit+ callbacks are called on every record saved or destroyed within a
-
# transaction immediately after the transaction is committed. +after_rollback+ callbacks
-
# are called on every record saved or destroyed within a transaction immediately after the
-
# transaction or savepoint is rolled back.
-
#
-
# These callbacks are useful for interacting with other systems since you will be guaranteed
-
# that the callback is only executed when the database is in a permanent state. For example,
-
# +after_commit+ is a good spot to put in a hook to clearing a cache since clearing it from
-
# within a transaction could trigger the cache to be regenerated before the database is updated.
-
#
-
# === Caveats
-
#
-
# If you're on MySQL, then do not use DDL operations in nested transactions
-
# blocks that are emulated with savepoints. That is, do not execute statements
-
# like 'CREATE TABLE' inside such blocks. This is because MySQL automatically
-
# releases all savepoints upon executing a DDL operation. When +transaction+
-
# is finished and tries to release the savepoint it created earlier, a
-
# database error will occur because the savepoint has already been
-
# automatically released. The following example demonstrates the problem:
-
#
-
# Model.connection.transaction do # BEGIN
-
# Model.connection.transaction(requires_new: true) do # CREATE SAVEPOINT active_record_1
-
# Model.connection.create_table(...) # active_record_1 now automatically released
-
# end # RELEASE savepoint active_record_1
-
# # ^^^^ BOOM! database error!
-
# end
-
#
-
# Note that "TRUNCATE" is also a MySQL DDL statement!
-
1
module ClassMethods
-
# See ActiveRecord::Transactions::ClassMethods for detailed documentation.
-
1
def transaction(options = {}, &block)
-
# See the ConnectionAdapters::DatabaseStatements#transaction API docs.
-
connection.transaction(options, &block)
-
end
-
-
# This callback is called after a record has been created, updated, or destroyed.
-
#
-
# You can specify that the callback should only be fired by a certain action with
-
# the +:on+ option:
-
#
-
# after_commit :do_foo, on: :create
-
# after_commit :do_bar, on: :update
-
# after_commit :do_baz, on: :destroy
-
#
-
# after_commit :do_foo_bar, on: [:create, :update]
-
# after_commit :do_bar_baz, on: [:update, :destroy]
-
#
-
# Note that transactional fixtures do not play well with this feature. Please
-
# use the +test_after_commit+ gem to have these hooks fired in tests.
-
1
def after_commit(*args, &block)
-
2
set_options_for_callbacks!(args)
-
2
set_callback(:commit, :after, *args, &block)
-
end
-
-
# This callback is called after a create, update, or destroy are rolled back.
-
#
-
# Please check the documentation of +after_commit+ for options.
-
1
def after_rollback(*args, &block)
-
set_options_for_callbacks!(args)
-
set_callback(:rollback, :after, *args, &block)
-
end
-
-
1
private
-
-
1
def set_options_for_callbacks!(args)
-
2
options = args.last
-
2
if options.is_a?(Hash) && options[:on]
-
2
fire_on = Array(options[:on])
-
2
assert_valid_transaction_action(fire_on)
-
2
options[:if] = Array(options[:if])
-
2
options[:if] << "transaction_include_any_action?(#{fire_on})"
-
end
-
end
-
-
1
def assert_valid_transaction_action(actions)
-
2
if (actions - ACTIONS).any?
-
raise ArgumentError, ":on conditions for after_commit and after_rollback callbacks have to be one of #{ACTIONS.join(",")}"
-
end
-
end
-
end
-
-
# See ActiveRecord::Transactions::ClassMethods for detailed documentation.
-
1
def transaction(options = {}, &block)
-
self.class.transaction(options, &block)
-
end
-
-
1
def destroy #:nodoc:
-
with_transaction_returning_status { super }
-
end
-
-
1
def save(*) #:nodoc:
-
rollback_active_record_state! do
-
with_transaction_returning_status { super }
-
end
-
end
-
-
1
def save!(*) #:nodoc:
-
with_transaction_returning_status { super }
-
end
-
-
1
def touch(*) #:nodoc:
-
with_transaction_returning_status { super }
-
end
-
-
# Reset id and @new_record if the transaction rolls back.
-
1
def rollback_active_record_state!
-
remember_transaction_record_state
-
yield
-
rescue Exception
-
restore_transaction_record_state
-
raise
-
ensure
-
clear_transaction_record_state
-
end
-
-
# Call the +after_commit+ callbacks.
-
#
-
# Ensure that it is not called if the object was never persisted (failed create),
-
# but call it after the commit of a destroyed object.
-
1
def committed! #:nodoc:
-
run_callbacks :commit if destroyed? || persisted?
-
ensure
-
@_start_transaction_state.clear
-
end
-
-
# Call the +after_rollback+ callbacks. The +force_restore_state+ argument indicates if the record
-
# state should be rolled back to the beginning or just to the last savepoint.
-
1
def rolledback!(force_restore_state = false) #:nodoc:
-
run_callbacks :rollback
-
ensure
-
restore_transaction_record_state(force_restore_state)
-
clear_transaction_record_state
-
end
-
-
# Add the record to the current transaction so that the +after_rollback+ and +after_commit+ callbacks
-
# can be called.
-
1
def add_to_transaction
-
if self.class.connection.add_transaction_record(self)
-
remember_transaction_record_state
-
end
-
end
-
-
# Executes +method+ within a transaction and captures its return value as a
-
# status flag. If the status is true the transaction is committed, otherwise
-
# a ROLLBACK is issued. In any case the status flag is returned.
-
#
-
# This method is available within the context of an ActiveRecord::Base
-
# instance.
-
1
def with_transaction_returning_status
-
status = nil
-
self.class.transaction do
-
add_to_transaction
-
begin
-
status = yield
-
rescue ActiveRecord::Rollback
-
@_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1
-
status = nil
-
end
-
-
raise ActiveRecord::Rollback unless status
-
end
-
status
-
end
-
-
1
protected
-
-
# Save the new record state and id of a record so it can be restored later if a transaction fails.
-
1
def remember_transaction_record_state #:nodoc:
-
@_start_transaction_state[:id] = id if has_attribute?(self.class.primary_key)
-
unless @_start_transaction_state.include?(:new_record)
-
@_start_transaction_state[:new_record] = @new_record
-
end
-
unless @_start_transaction_state.include?(:destroyed)
-
@_start_transaction_state[:destroyed] = @destroyed
-
end
-
@_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) + 1
-
@_start_transaction_state[:frozen?] = @attributes.frozen?
-
end
-
-
# Clear the new record state and id of a record.
-
1
def clear_transaction_record_state #:nodoc:
-
@_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1
-
@_start_transaction_state.clear if @_start_transaction_state[:level] < 1
-
end
-
-
# Restore the new record state and id of a record that was previously saved by a call to save_record_state.
-
1
def restore_transaction_record_state(force = false) #:nodoc:
-
unless @_start_transaction_state.empty?
-
transaction_level = (@_start_transaction_state[:level] || 0) - 1
-
if transaction_level < 1 || force
-
restore_state = @_start_transaction_state
-
was_frozen = restore_state[:frozen?]
-
@attributes = @attributes.dup if @attributes.frozen?
-
@new_record = restore_state[:new_record]
-
@destroyed = restore_state[:destroyed]
-
if restore_state.has_key?(:id)
-
self.id = restore_state[:id]
-
else
-
@attributes.delete(self.class.primary_key)
-
@attributes_cache.delete(self.class.primary_key)
-
end
-
@attributes.freeze if was_frozen
-
end
-
end
-
end
-
-
# Determine if a record was created or destroyed in a transaction. State should be one of :new_record or :destroyed.
-
1
def transaction_record_state(state) #:nodoc:
-
@_start_transaction_state[state]
-
end
-
-
# Determine if a transaction included an action for :create, :update, or :destroy. Used in filtering callbacks.
-
1
def transaction_include_any_action?(actions) #:nodoc:
-
actions.any? do |action|
-
case action
-
when :create
-
transaction_record_state(:new_record)
-
when :destroy
-
destroyed?
-
when :update
-
!(transaction_record_state(:new_record) || destroyed?)
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Translation
-
1
include ActiveModel::Translation
-
-
# Set the lookup ancestors for ActiveModel.
-
1
def lookup_ancestors #:nodoc:
-
klass = self
-
classes = [klass]
-
return classes if klass == ActiveRecord::Base
-
-
while klass != klass.base_class
-
classes << klass = klass.superclass
-
end
-
classes
-
end
-
-
# Set the i18n scope to overwrite ActiveModel.
-
1
def i18n_scope #:nodoc:
-
:activerecord
-
end
-
end
-
end
-
1
module ActiveRecord
-
# = Active Record RecordInvalid
-
#
-
# Raised by <tt>save!</tt> and <tt>create!</tt> when the record is invalid. Use the
-
# +record+ method to retrieve the record which did not validate.
-
#
-
# begin
-
# complex_operation_that_calls_save!_internally
-
# rescue ActiveRecord::RecordInvalid => invalid
-
# puts invalid.record.errors
-
# end
-
1
class RecordInvalid < ActiveRecordError
-
1
attr_reader :record # :nodoc:
-
1
def initialize(record) # :nodoc:
-
@record = record
-
errors = @record.errors.full_messages.join(", ")
-
super(I18n.t(:"#{@record.class.i18n_scope}.errors.messages.record_invalid", :errors => errors, :default => :"errors.messages.record_invalid"))
-
end
-
end
-
-
# = Active Record Validations
-
#
-
# Active Record includes the majority of its validations from <tt>ActiveModel::Validations</tt>
-
# all of which accept the <tt>:on</tt> argument to define the context where the
-
# validations are active. Active Record will always supply either the context of
-
# <tt>:create</tt> or <tt>:update</tt> dependent on whether the model is a
-
# <tt>new_record?</tt>.
-
1
module Validations
-
1
extend ActiveSupport::Concern
-
1
include ActiveModel::Validations
-
-
1
module ClassMethods
-
# Creates an object just like Base.create but calls <tt>save!</tt> instead of +save+
-
# so an exception is raised if the record is invalid.
-
1
def create!(attributes = nil, &block)
-
if attributes.is_a?(Array)
-
attributes.collect { |attr| create!(attr, &block) }
-
else
-
object = new(attributes)
-
yield(object) if block_given?
-
object.save!
-
object
-
end
-
end
-
end
-
-
# The validation process on save can be skipped by passing <tt>validate: false</tt>.
-
# The regular Base#save method is replaced with this when the validations
-
# module is mixed in, which it is by default.
-
1
def save(options={})
-
perform_validations(options) ? super : false
-
end
-
-
# Attempts to save the record just like Base#save but will raise a +RecordInvalid+
-
# exception instead of returning +false+ if the record is not valid.
-
1
def save!(options={})
-
perform_validations(options) ? super : raise(RecordInvalid.new(self))
-
end
-
-
# Runs all the validations within the specified context. Returns +true+ if
-
# no errors are found, +false+ otherwise.
-
#
-
# If the argument is +false+ (default is +nil+), the context is set to <tt>:create</tt> if
-
# <tt>new_record?</tt> is +true+, and to <tt>:update</tt> if it is not.
-
#
-
# Validations with no <tt>:on</tt> option will run no matter the context. Validations with
-
# some <tt>:on</tt> option will only run in the specified context.
-
1
def valid?(context = nil)
-
context ||= (new_record? ? :create : :update)
-
output = super(context)
-
errors.empty? && output
-
end
-
-
1
protected
-
-
1
def perform_validations(options={}) # :nodoc:
-
options[:validate] == false || valid?(options[:context])
-
end
-
end
-
end
-
-
1
require "active_record/validations/associated"
-
1
require "active_record/validations/uniqueness"
-
1
require "active_record/validations/presence"
-
1
module ActiveRecord
-
1
module Validations
-
1
class AssociatedValidator < ActiveModel::EachValidator #:nodoc:
-
1
def validate_each(record, attribute, value)
-
if Array.wrap(value).reject {|r| r.marked_for_destruction? || r.valid?}.any?
-
record.errors.add(attribute, :invalid, options.merge(:value => value))
-
end
-
end
-
end
-
-
1
module ClassMethods
-
# Validates whether the associated object or objects are all valid.
-
# Works with any kind of association.
-
#
-
# class Book < ActiveRecord::Base
-
# has_many :pages
-
# belongs_to :library
-
#
-
# validates_associated :pages, :library
-
# end
-
#
-
# WARNING: This validation must not be used on both ends of an association.
-
# Doing so will lead to a circular dependency and cause infinite recursion.
-
#
-
# NOTE: This validation will not fail if the association hasn't been
-
# assigned. If you want to ensure that the association is both present and
-
# guaranteed to be valid, you also need to use +validates_presence_of+.
-
#
-
# Configuration options:
-
#
-
# * <tt>:message</tt> - A custom error message (default is: "is invalid").
-
# * <tt>:on</tt> - Specifies when this validation is active. Runs in all
-
# validation contexts by default (+nil+), other options are <tt>:create</tt>
-
# and <tt>:update</tt>.
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
-
# or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
-
# proc or string should return or evaluate to a +true+ or +false+ value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to
-
# determine if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>,
-
# or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The
-
# method, proc or string should return or evaluate to a +true+ or +false+
-
# value.
-
1
def validates_associated(*attr_names)
-
validates_with AssociatedValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Validations
-
1
class PresenceValidator < ActiveModel::Validations::PresenceValidator # :nodoc:
-
1
def validate(record)
-
super
-
attributes.each do |attribute|
-
next unless record.class.reflect_on_association(attribute)
-
associated_records = Array.wrap(record.send(attribute))
-
-
# Superclass validates presence. Ensure present records aren't about to be destroyed.
-
if associated_records.present? && associated_records.all? { |r| r.marked_for_destruction? }
-
record.errors.add(attribute, :blank, options)
-
end
-
end
-
end
-
end
-
-
1
module ClassMethods
-
# Validates that the specified attributes are not blank (as defined by
-
# Object#blank?), and, if the attribute is an association, that the
-
# associated object is not marked for destruction. Happens by default
-
# on save.
-
#
-
# class Person < ActiveRecord::Base
-
# has_one :face
-
# validates_presence_of :face
-
# end
-
#
-
# The face attribute must be in the object and it cannot be blank or marked
-
# for destruction.
-
#
-
# If you want to validate the presence of a boolean field (where the real values
-
# are true and false), you will want to use
-
# <tt>validates_inclusion_of :field_name, in: [true, false]</tt>.
-
#
-
# This is due to the way Object#blank? handles boolean values:
-
# <tt>false.blank? # => true</tt>.
-
#
-
# This validator defers to the ActiveModel validation for presence, adding the
-
# check to see that an associated object is not marked for destruction. This
-
# prevents the parent object from validating successfully and saving, which then
-
# deletes the associated object, thus putting the parent object into an invalid
-
# state.
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "can't be blank").
-
# * <tt>:on</tt> - Specifies when this validation is active. Runs in all
-
# validation contexts by default (+nil+), other options are <tt>:create</tt>
-
# and <tt>:update</tt>.
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if
-
# the validation should occur (e.g. <tt>if: :allow_validation</tt>, or
-
# <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method, proc
-
# or string should return or evaluate to a +true+ or +false+ value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>,
-
# or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The method,
-
# proc or string should return or evaluate to a +true+ or +false+ value.
-
# * <tt>:strict</tt> - Specifies whether validation should be strict.
-
# See <tt>ActiveModel::Validation#validates!</tt> for more information.
-
1
def validates_presence_of(*attr_names)
-
3
validates_with PresenceValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Validations
-
1
class UniquenessValidator < ActiveModel::EachValidator # :nodoc:
-
1
def initialize(options)
-
2
if options[:conditions] && !options[:conditions].respond_to?(:call)
-
raise ArgumentError, "#{options[:conditions]} was passed as :conditions but is not callable. " \
-
"Pass a callable instead: `conditions: -> { where(approved: true) }`"
-
end
-
2
super({ case_sensitive: true }.merge!(options))
-
2
@klass = options[:class]
-
end
-
-
1
def validate_each(record, attribute, value)
-
finder_class = find_finder_class_for(record)
-
table = finder_class.arel_table
-
value = map_enum_attribute(finder_class,attribute,value)
-
value = deserialize_attribute(record, attribute, value)
-
-
relation = build_relation(finder_class, table, attribute, value)
-
relation = relation.and(table[finder_class.primary_key.to_sym].not_eq(record.id)) if record.persisted?
-
relation = scope_relation(record, table, relation)
-
relation = finder_class.unscoped.where(relation)
-
relation = relation.merge(options[:conditions]) if options[:conditions]
-
-
if relation.exists?
-
error_options = options.except(:case_sensitive, :scope, :conditions)
-
error_options[:value] = value
-
-
record.errors.add(attribute, :taken, error_options)
-
end
-
end
-
-
1
protected
-
# The check for an existing value should be run from a class that
-
# isn't abstract. This means working down from the current class
-
# (self), to the first non-abstract class. Since classes don't know
-
# their subclasses, we have to build the hierarchy between self and
-
# the record's class.
-
1
def find_finder_class_for(record) #:nodoc:
-
class_hierarchy = [record.class]
-
-
while class_hierarchy.first != @klass
-
class_hierarchy.unshift(class_hierarchy.first.superclass)
-
end
-
-
class_hierarchy.detect { |klass| !klass.abstract_class? }
-
end
-
-
1
def build_relation(klass, table, attribute, value) #:nodoc:
-
if reflection = klass.reflect_on_association(attribute)
-
attribute = reflection.foreign_key
-
value = value.attributes[reflection.primary_key_column.name] unless value.nil?
-
end
-
-
attribute_name = attribute.to_s
-
-
# the attribute may be an aliased attribute
-
if klass.attribute_aliases[attribute_name]
-
attribute = klass.attribute_aliases[attribute_name]
-
attribute_name = attribute.to_s
-
end
-
-
column = klass.columns_hash[attribute_name]
-
value = klass.connection.type_cast(value, column)
-
value = value.to_s[0, column.limit] if value && column.limit && column.text?
-
-
if !options[:case_sensitive] && value && column.text?
-
# will use SQL LOWER function before comparison, unless it detects a case insensitive collation
-
klass.connection.case_insensitive_comparison(table, attribute, column, value)
-
else
-
value = klass.connection.case_sensitive_modifier(value) unless value.nil?
-
table[attribute].eq(value)
-
end
-
end
-
-
1
def scope_relation(record, table, relation)
-
Array(options[:scope]).each do |scope_item|
-
if reflection = record.class.reflect_on_association(scope_item)
-
scope_value = record.send(reflection.foreign_key)
-
scope_item = reflection.foreign_key
-
else
-
scope_value = record.read_attribute(scope_item)
-
end
-
relation = relation.and(table[scope_item].eq(scope_value))
-
end
-
-
relation
-
end
-
-
1
def deserialize_attribute(record, attribute, value)
-
coder = record.class.serialized_attributes[attribute.to_s]
-
value = coder.dump value if value && coder
-
value
-
end
-
-
1
def map_enum_attribute(klass, attribute, value)
-
mapping = klass.defined_enums[attribute.to_s]
-
value = mapping[value] if value && mapping
-
value
-
end
-
end
-
-
1
module ClassMethods
-
# Validates whether the value of the specified attributes are unique
-
# across the system. Useful for making sure that only one user
-
# can be named "davidhh".
-
#
-
# class Person < ActiveRecord::Base
-
# validates_uniqueness_of :user_name
-
# end
-
#
-
# It can also validate whether the value of the specified attributes are
-
# unique based on a <tt>:scope</tt> parameter:
-
#
-
# class Person < ActiveRecord::Base
-
# validates_uniqueness_of :user_name, scope: :account_id
-
# end
-
#
-
# Or even multiple scope parameters. For example, making sure that a
-
# teacher can only be on the schedule once per semester for a particular
-
# class.
-
#
-
# class TeacherSchedule < ActiveRecord::Base
-
# validates_uniqueness_of :teacher_id, scope: [:semester_id, :class_id]
-
# end
-
#
-
# It is also possible to limit the uniqueness constraint to a set of
-
# records matching certain conditions. In this example archived articles
-
# are not being taken into consideration when validating uniqueness
-
# of the title attribute:
-
#
-
# class Article < ActiveRecord::Base
-
# validates_uniqueness_of :title, conditions: -> { where.not(status: 'archived') }
-
# end
-
#
-
# When the record is created, a check is performed to make sure that no
-
# record exists in the database with the given value for the specified
-
# attribute (that maps to a column). When the record is updated,
-
# the same check is made but disregarding the record itself.
-
#
-
# Configuration options:
-
#
-
# * <tt>:message</tt> - Specifies a custom error message (default is:
-
# "has already been taken").
-
# * <tt>:scope</tt> - One or more columns by which to limit the scope of
-
# the uniqueness constraint.
-
# * <tt>:conditions</tt> - Specify the conditions to be included as a
-
# <tt>WHERE</tt> SQL fragment to limit the uniqueness constraint lookup
-
# (e.g. <tt>conditions: -> { where(status: 'active') }</tt>).
-
# * <tt>:case_sensitive</tt> - Looks for an exact match. Ignored by
-
# non-text columns (+true+ by default).
-
# * <tt>:allow_nil</tt> - If set to +true+, skips this validation if the
-
# attribute is +nil+ (default is +false+).
-
# * <tt>:allow_blank</tt> - If set to +true+, skips this validation if the
-
# attribute is blank (default is +false+).
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
-
# or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
-
# proc or string should return or evaluate to a +true+ or +false+ value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to
-
# determine if the validation should ot occur (e.g. <tt>unless: :skip_validation</tt>,
-
# or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The
-
# method, proc or string should return or evaluate to a +true+ or +false+
-
# value.
-
#
-
# === Concurrency and integrity
-
#
-
# Using this validation method in conjunction with ActiveRecord::Base#save
-
# does not guarantee the absence of duplicate record insertions, because
-
# uniqueness checks on the application level are inherently prone to race
-
# conditions. For example, suppose that two users try to post a Comment at
-
# the same time, and a Comment's title must be unique. At the database-level,
-
# the actions performed by these users could be interleaved in the following manner:
-
#
-
# User 1 | User 2
-
# ------------------------------------+--------------------------------------
-
# # User 1 checks whether there's |
-
# # already a comment with the title |
-
# # 'My Post'. This is not the case. |
-
# SELECT * FROM comments |
-
# WHERE title = 'My Post' |
-
# |
-
# | # User 2 does the same thing and also
-
# | # infers that their title is unique.
-
# | SELECT * FROM comments
-
# | WHERE title = 'My Post'
-
# |
-
# # User 1 inserts their comment. |
-
# INSERT INTO comments |
-
# (title, content) VALUES |
-
# ('My Post', 'hi!') |
-
# |
-
# | # User 2 does the same thing.
-
# | INSERT INTO comments
-
# | (title, content) VALUES
-
# | ('My Post', 'hello!')
-
# |
-
# | # ^^^^^^
-
# | # Boom! We now have a duplicate
-
# | # title!
-
#
-
# This could even happen if you use transactions with the 'serializable'
-
# isolation level. The best way to work around this problem is to add a unique
-
# index to the database table using
-
# ActiveRecord::ConnectionAdapters::SchemaStatements#add_index. In the
-
# rare case that a race condition occurs, the database will guarantee
-
# the field's uniqueness.
-
#
-
# When the database catches such a duplicate insertion,
-
# ActiveRecord::Base#save will raise an ActiveRecord::StatementInvalid
-
# exception. You can either choose to let this error propagate (which
-
# will result in the default Rails exception page being shown), or you
-
# can catch it and restart the transaction (e.g. by telling the user
-
# that the title already exists, and asking them to re-enter the title).
-
# This technique is also known as
-
# {optimistic concurrency control}[http://en.wikipedia.org/wiki/Optimistic_concurrency_control].
-
#
-
# The bundled ActiveRecord::ConnectionAdapters distinguish unique index
-
# constraint errors from other types of database errors by throwing an
-
# ActiveRecord::RecordNotUnique exception. For other adapters you will
-
# have to parse the (database-specific) exception message to detect such
-
# a case.
-
#
-
# The following bundled adapters throw the ActiveRecord::RecordNotUnique exception:
-
#
-
# * ActiveRecord::ConnectionAdapters::MysqlAdapter.
-
# * ActiveRecord::ConnectionAdapters::Mysql2Adapter.
-
# * ActiveRecord::ConnectionAdapters::SQLite3Adapter.
-
# * ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.
-
1
def validates_uniqueness_of(*attr_names)
-
2
validates_with UniquenessValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
1
require_relative 'gem_version'
-
-
1
module ActiveRecord
-
# Returns the version of the currently loaded ActiveRecord as a <tt>Gem::Version</tt>
-
1
def self.version
-
gem_version
-
end
-
end
-
#--
-
# Copyright (c) 2005-2014 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
1
require 'securerandom'
-
1
require "active_support/dependencies/autoload"
-
1
require "active_support/version"
-
1
require "active_support/logger"
-
1
require "active_support/lazy_load_hooks"
-
-
1
module ActiveSupport
-
1
extend ActiveSupport::Autoload
-
-
1
autoload :Concern
-
1
autoload :Dependencies
-
1
autoload :DescendantsTracker
-
1
autoload :FileUpdateChecker
-
1
autoload :LogSubscriber
-
1
autoload :Notifications
-
-
1
eager_autoload do
-
1
autoload :BacktraceCleaner
-
1
autoload :ProxyObject
-
1
autoload :Benchmarkable
-
1
autoload :Cache
-
1
autoload :Callbacks
-
1
autoload :Configurable
-
1
autoload :Deprecation
-
1
autoload :Gzip
-
1
autoload :Inflector
-
1
autoload :JSON
-
1
autoload :KeyGenerator
-
1
autoload :MessageEncryptor
-
1
autoload :MessageVerifier
-
1
autoload :Multibyte
-
1
autoload :NumberHelper
-
1
autoload :OptionMerger
-
1
autoload :OrderedHash
-
1
autoload :OrderedOptions
-
1
autoload :StringInquirer
-
1
autoload :TaggedLogging
-
1
autoload :XmlMini
-
end
-
-
1
autoload :Rescuable
-
1
autoload :SafeBuffer, "active_support/core_ext/string/output_safety"
-
1
autoload :TestCase
-
-
1
def self.eager_load!
-
super
-
-
NumberHelper.eager_load!
-
end
-
end
-
-
1
autoload :I18n, "active_support/i18n"
-
1
require 'active_support'
-
1
require 'active_support/time'
-
1
require 'active_support/core_ext'
-
1
require 'active_support/core_ext/benchmark'
-
1
require 'active_support/core_ext/hash/keys'
-
-
1
module ActiveSupport
-
1
module Benchmarkable
-
# Allows you to measure the execution time of a block in a template and
-
# records the result to the log. Wrap this block around expensive operations
-
# or possible bottlenecks to get a time reading for the operation. For
-
# example, let's say you thought your file processing method was taking too
-
# long; you could wrap it in a benchmark block.
-
#
-
# <% benchmark 'Process data files' do %>
-
# <%= expensive_files_operation %>
-
# <% end %>
-
#
-
# That would add something like "Process data files (345.2ms)" to the log,
-
# which you can then use to compare timings when optimizing your code.
-
#
-
# You may give an optional logger level (<tt>:debug</tt>, <tt>:info</tt>,
-
# <tt>:warn</tt>, <tt>:error</tt>) as the <tt>:level</tt> option. The
-
# default logger level value is <tt>:info</tt>.
-
#
-
# <% benchmark 'Low-level files', level: :debug do %>
-
# <%= lowlevel_files_operation %>
-
# <% end %>
-
#
-
# Finally, you can pass true as the third argument to silence all log
-
# activity (other than the timing information) from inside the block. This
-
# is great for boiling down a noisy block to just a single statement that
-
# produces one log line:
-
#
-
# <% benchmark 'Process data files', level: :info, silence: true do %>
-
# <%= expensive_and_chatty_files_operation %>
-
# <% end %>
-
1
def benchmark(message = "Benchmarking", options = {})
-
if logger
-
options.assert_valid_keys(:level, :silence)
-
options[:level] ||= :info
-
-
result = nil
-
ms = Benchmark.ms { result = options[:silence] ? silence { yield } : yield }
-
logger.send(options[:level], '%s (%.1fms)' % [ message, ms ])
-
result
-
else
-
yield
-
end
-
end
-
end
-
end
-
1
require 'benchmark'
-
1
require 'zlib'
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'active_support/core_ext/array/wrap'
-
1
require 'active_support/core_ext/benchmark'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/numeric/bytes'
-
1
require 'active_support/core_ext/numeric/time'
-
1
require 'active_support/core_ext/object/to_param'
-
1
require 'active_support/core_ext/string/inflections'
-
-
1
module ActiveSupport
-
# See ActiveSupport::Cache::Store for documentation.
-
1
module Cache
-
1
autoload :FileStore, 'active_support/cache/file_store'
-
1
autoload :MemoryStore, 'active_support/cache/memory_store'
-
1
autoload :MemCacheStore, 'active_support/cache/mem_cache_store'
-
1
autoload :NullStore, 'active_support/cache/null_store'
-
-
# These options mean something to all cache implementations. Individual cache
-
# implementations may support additional options.
-
1
UNIVERSAL_OPTIONS = [:namespace, :compress, :compress_threshold, :expires_in, :race_condition_ttl]
-
-
1
module Strategy
-
1
autoload :LocalCache, 'active_support/cache/strategy/local_cache'
-
end
-
-
1
class << self
-
# Creates a new CacheStore object according to the given options.
-
#
-
# If no arguments are passed to this method, then a new
-
# ActiveSupport::Cache::MemoryStore object will be returned.
-
#
-
# If you pass a Symbol as the first argument, then a corresponding cache
-
# store class under the ActiveSupport::Cache namespace will be created.
-
# For example:
-
#
-
# ActiveSupport::Cache.lookup_store(:memory_store)
-
# # => returns a new ActiveSupport::Cache::MemoryStore object
-
#
-
# ActiveSupport::Cache.lookup_store(:mem_cache_store)
-
# # => returns a new ActiveSupport::Cache::MemCacheStore object
-
#
-
# Any additional arguments will be passed to the corresponding cache store
-
# class's constructor:
-
#
-
# ActiveSupport::Cache.lookup_store(:file_store, '/tmp/cache')
-
# # => same as: ActiveSupport::Cache::FileStore.new('/tmp/cache')
-
#
-
# If the first argument is not a Symbol, then it will simply be returned:
-
#
-
# ActiveSupport::Cache.lookup_store(MyOwnCacheStore.new)
-
# # => returns MyOwnCacheStore.new
-
1
def lookup_store(*store_option)
-
2
store, *parameters = *Array.wrap(store_option).flatten
-
-
2
case store
-
when Symbol
-
1
retrieve_store_class(store).new(*parameters)
-
when nil
-
ActiveSupport::Cache::MemoryStore.new
-
else
-
1
store
-
end
-
end
-
-
# Expands out the +key+ argument into a key that can be used for the
-
# cache store. Optionally accepts a namespace, and all keys will be
-
# scoped within that namespace.
-
#
-
# If the +key+ argument provided is an array, or responds to +to_a+, then
-
# each of elements in the array will be turned into parameters/keys and
-
# concatenated into a single key. For example:
-
#
-
# expand_cache_key([:foo, :bar]) # => "foo/bar"
-
# expand_cache_key([:foo, :bar], "namespace") # => "namespace/foo/bar"
-
#
-
# The +key+ argument can also respond to +cache_key+ or +to_param+.
-
1
def expand_cache_key(key, namespace = nil)
-
expanded_cache_key = namespace ? "#{namespace}/" : ""
-
-
if prefix = ENV["RAILS_CACHE_ID"] || ENV["RAILS_APP_VERSION"]
-
expanded_cache_key << "#{prefix}/"
-
end
-
-
expanded_cache_key << retrieve_cache_key(key)
-
expanded_cache_key
-
end
-
-
1
private
-
1
def retrieve_cache_key(key)
-
case
-
when key.respond_to?(:cache_key) then key.cache_key
-
when key.is_a?(Array) then key.map { |element| retrieve_cache_key(element) }.to_param
-
when key.respond_to?(:to_a) then retrieve_cache_key(key.to_a)
-
else key.to_param
-
end.to_s
-
end
-
-
# Obtains the specified cache store class, given the name of the +store+.
-
# Raises an error when the store class cannot be found.
-
1
def retrieve_store_class(store)
-
1
require "active_support/cache/#{store}"
-
rescue LoadError => e
-
raise "Could not find cache store adapter for #{store} (#{e})"
-
else
-
1
ActiveSupport::Cache.const_get(store.to_s.camelize)
-
end
-
end
-
-
# An abstract cache store class. There are multiple cache store
-
# implementations, each having its own additional features. See the classes
-
# under the ActiveSupport::Cache module, e.g.
-
# ActiveSupport::Cache::MemCacheStore. MemCacheStore is currently the most
-
# popular cache store for large production websites.
-
#
-
# Some implementations may not support all methods beyond the basic cache
-
# methods of +fetch+, +write+, +read+, +exist?+, and +delete+.
-
#
-
# ActiveSupport::Cache::Store can store any serializable Ruby object.
-
#
-
# cache = ActiveSupport::Cache::MemoryStore.new
-
#
-
# cache.read('city') # => nil
-
# cache.write('city', "Duckburgh")
-
# cache.read('city') # => "Duckburgh"
-
#
-
# Keys are always translated into Strings and are case sensitive. When an
-
# object is specified as a key and has a +cache_key+ method defined, this
-
# method will be called to define the key. Otherwise, the +to_param+
-
# method will be called. Hashes and Arrays can also be used as keys. The
-
# elements will be delimited by slashes, and the elements within a Hash
-
# will be sorted by key so they are consistent.
-
#
-
# cache.read('city') == cache.read(:city) # => true
-
#
-
# Nil values can be cached.
-
#
-
# If your cache is on a shared infrastructure, you can define a namespace
-
# for your cache entries. If a namespace is defined, it will be prefixed on
-
# to every key. The namespace can be either a static value or a Proc. If it
-
# is a Proc, it will be invoked when each key is evaluated so that you can
-
# use application logic to invalidate keys.
-
#
-
# cache.namespace = -> { @last_mod_time } # Set the namespace to a variable
-
# @last_mod_time = Time.now # Invalidate the entire cache by changing namespace
-
#
-
# Caches can also store values in a compressed format to save space and
-
# reduce time spent sending data. Since there is overhead, values must be
-
# large enough to warrant compression. To turn on compression either pass
-
# <tt>compress: true</tt> in the initializer or as an option to +fetch+
-
# or +write+. To specify the threshold at which to compress values, set the
-
# <tt>:compress_threshold</tt> option. The default threshold is 16K.
-
1
class Store
-
1
cattr_accessor :logger, :instance_writer => true
-
-
1
attr_reader :silence, :options
-
1
alias :silence? :silence
-
-
# Create a new cache. The options will be passed to any write method calls
-
# except for <tt>:namespace</tt> which can be used to set the global
-
# namespace for the cache.
-
1
def initialize(options = nil)
-
1
@options = options ? options.dup : {}
-
end
-
-
# Silence the logger.
-
1
def silence!
-
@silence = true
-
self
-
end
-
-
# Silence the logger within a block.
-
1
def mute
-
previous_silence, @silence = defined?(@silence) && @silence, true
-
yield
-
ensure
-
@silence = previous_silence
-
end
-
-
# Set to +true+ if cache stores should be instrumented.
-
# Default is +false+.
-
1
def self.instrument=(boolean)
-
Thread.current[:instrument_cache_store] = boolean
-
end
-
-
1
def self.instrument
-
Thread.current[:instrument_cache_store] || false
-
end
-
-
# Fetches data from the cache, using the given key. If there is data in
-
# the cache with the given key, then that data is returned.
-
#
-
# If there is no such data in the cache (a cache miss), then +nil+ will be
-
# returned. However, if a block has been passed, that block will be passed
-
# the key and executed in the event of a cache miss. The return value of the
-
# block will be written to the cache under the given cache key, and that
-
# return value will be returned.
-
#
-
# cache.write('today', 'Monday')
-
# cache.fetch('today') # => "Monday"
-
#
-
# cache.fetch('city') # => nil
-
# cache.fetch('city') do
-
# 'Duckburgh'
-
# end
-
# cache.fetch('city') # => "Duckburgh"
-
#
-
# You may also specify additional options via the +options+ argument.
-
# Setting <tt>force: true</tt> will force a cache miss:
-
#
-
# cache.write('today', 'Monday')
-
# cache.fetch('today', force: true) # => nil
-
#
-
# Setting <tt>:compress</tt> will store a large cache entry set by the call
-
# in a compressed format.
-
#
-
# Setting <tt>:expires_in</tt> will set an expiration time on the cache.
-
# All caches support auto-expiring content after a specified number of
-
# seconds. This value can be specified as an option to the constructor
-
# (in which case all entries will be affected), or it can be supplied to
-
# the +fetch+ or +write+ method to effect just one entry.
-
#
-
# cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 5.minutes)
-
# cache.write(key, value, expires_in: 1.minute) # Set a lower value for one entry
-
#
-
# Setting <tt>:race_condition_ttl</tt> is very useful in situations where
-
# a cache entry is used very frequently and is under heavy load. If a
-
# cache expires and due to heavy load several different processes will try
-
# to read data natively and then they all will try to write to cache. To
-
# avoid that case the first process to find an expired cache entry will
-
# bump the cache expiration time by the value set in <tt>:race_condition_ttl</tt>.
-
# Yes, this process is extending the time for a stale value by another few
-
# seconds. Because of extended life of the previous cache, other processes
-
# will continue to use slightly stale data for a just a bit longer. In the
-
# meantime that first process will go ahead and will write into cache the
-
# new value. After that all the processes will start getting new value.
-
# The key is to keep <tt>:race_condition_ttl</tt> small.
-
#
-
# If the process regenerating the entry errors out, the entry will be
-
# regenerated after the specified number of seconds. Also note that the
-
# life of stale cache is extended only if it expired recently. Otherwise
-
# a new value is generated and <tt>:race_condition_ttl</tt> does not play
-
# any role.
-
#
-
# # Set all values to expire after one minute.
-
# cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 1.minute)
-
#
-
# cache.write('foo', 'original value')
-
# val_1 = nil
-
# val_2 = nil
-
# sleep 60
-
#
-
# Thread.new do
-
# val_1 = cache.fetch('foo', race_condition_ttl: 10) do
-
# sleep 1
-
# 'new value 1'
-
# end
-
# end
-
#
-
# Thread.new do
-
# val_2 = cache.fetch('foo', race_condition_ttl: 10) do
-
# 'new value 2'
-
# end
-
# end
-
#
-
# # val_1 => "new value 1"
-
# # val_2 => "original value"
-
# # sleep 10 # First thread extend the life of cache by another 10 seconds
-
# # cache.fetch('foo') => "new value 1"
-
#
-
# Other options will be handled by the specific cache store implementation.
-
# Internally, #fetch calls #read_entry, and calls #write_entry on a cache
-
# miss. +options+ will be passed to the #read and #write calls.
-
#
-
# For example, MemCacheStore's #write method supports the +:raw+
-
# option, which tells the memcached server to store all values as strings.
-
# We can use this option with #fetch too:
-
#
-
# cache = ActiveSupport::Cache::MemCacheStore.new
-
# cache.fetch("foo", force: true, raw: true) do
-
# :bar
-
# end
-
# cache.fetch('foo') # => "bar"
-
1
def fetch(name, options = nil)
-
if block_given?
-
options = merged_options(options)
-
key = namespaced_key(name, options)
-
-
cached_entry = find_cached_entry(key, name, options) unless options[:force]
-
entry = handle_expired_entry(cached_entry, key, options)
-
-
if entry
-
get_entry_value(entry, name, options)
-
else
-
save_block_result_to_cache(name, options) { |_name| yield _name }
-
end
-
else
-
read(name, options)
-
end
-
end
-
-
# Fetches data from the cache, using the given key. If there is data in
-
# the cache with the given key, then that data is returned. Otherwise,
-
# +nil+ is returned.
-
#
-
# Options are passed to the underlying cache implementation.
-
1
def read(name, options = nil)
-
options = merged_options(options)
-
key = namespaced_key(name, options)
-
instrument(:read, name, options) do |payload|
-
entry = read_entry(key, options)
-
if entry
-
if entry.expired?
-
delete_entry(key, options)
-
payload[:hit] = false if payload
-
nil
-
else
-
payload[:hit] = true if payload
-
entry.value
-
end
-
else
-
payload[:hit] = false if payload
-
nil
-
end
-
end
-
end
-
-
# Read multiple values at once from the cache. Options can be passed
-
# in the last argument.
-
#
-
# Some cache implementation may optimize this method.
-
#
-
# Returns a hash mapping the names provided to the values found.
-
1
def read_multi(*names)
-
options = names.extract_options!
-
options = merged_options(options)
-
results = {}
-
names.each do |name|
-
key = namespaced_key(name, options)
-
entry = read_entry(key, options)
-
if entry
-
if entry.expired?
-
delete_entry(key, options)
-
else
-
results[name] = entry.value
-
end
-
end
-
end
-
results
-
end
-
-
# Fetches data from the cache, using the given keys. If there is data in
-
# the cache with the given keys, then that data is returned. Otherwise,
-
# the supplied block is called for each key for which there was no data,
-
# and the result will be written to the cache and returned.
-
#
-
# Options are passed to the underlying cache implementation.
-
#
-
# Returns an array with the data for each of the names. For example:
-
#
-
# cache.write("bim", "bam")
-
# cache.fetch_multi("bim", "boom") {|key| key * 2 }
-
# # => ["bam", "boomboom"]
-
#
-
1
def fetch_multi(*names)
-
options = names.extract_options!
-
options = merged_options(options)
-
-
results = read_multi(*names, options)
-
-
names.map do |name|
-
results.fetch(name) do
-
value = yield name
-
write(name, value, options)
-
value
-
end
-
end
-
end
-
-
# Writes the value to the cache, with the key.
-
#
-
# Options are passed to the underlying cache implementation.
-
1
def write(name, value, options = nil)
-
options = merged_options(options)
-
-
instrument(:write, name, options) do
-
entry = Entry.new(value, options)
-
write_entry(namespaced_key(name, options), entry, options)
-
end
-
end
-
-
# Deletes an entry in the cache. Returns +true+ if an entry is deleted.
-
#
-
# Options are passed to the underlying cache implementation.
-
1
def delete(name, options = nil)
-
options = merged_options(options)
-
-
instrument(:delete, name) do
-
delete_entry(namespaced_key(name, options), options)
-
end
-
end
-
-
# Returns +true+ if the cache contains an entry for the given key.
-
#
-
# Options are passed to the underlying cache implementation.
-
1
def exist?(name, options = nil)
-
options = merged_options(options)
-
-
instrument(:exist?, name) do
-
entry = read_entry(namespaced_key(name, options), options)
-
(entry && !entry.expired?) || false
-
end
-
end
-
-
# Delete all entries with keys matching the pattern.
-
#
-
# Options are passed to the underlying cache implementation.
-
#
-
# All implementations may not support this method.
-
1
def delete_matched(matcher, options = nil)
-
raise NotImplementedError.new("#{self.class.name} does not support delete_matched")
-
end
-
-
# Increment an integer value in the cache.
-
#
-
# Options are passed to the underlying cache implementation.
-
#
-
# All implementations may not support this method.
-
1
def increment(name, amount = 1, options = nil)
-
raise NotImplementedError.new("#{self.class.name} does not support increment")
-
end
-
-
# Decrement an integer value in the cache.
-
#
-
# Options are passed to the underlying cache implementation.
-
#
-
# All implementations may not support this method.
-
1
def decrement(name, amount = 1, options = nil)
-
raise NotImplementedError.new("#{self.class.name} does not support decrement")
-
end
-
-
# Cleanup the cache by removing expired entries.
-
#
-
# Options are passed to the underlying cache implementation.
-
#
-
# All implementations may not support this method.
-
1
def cleanup(options = nil)
-
raise NotImplementedError.new("#{self.class.name} does not support cleanup")
-
end
-
-
# Clear the entire cache. Be careful with this method since it could
-
# affect other processes if shared cache is being used.
-
#
-
# The options hash is passed to the underlying cache implementation.
-
#
-
# All implementations may not support this method.
-
1
def clear(options = nil)
-
raise NotImplementedError.new("#{self.class.name} does not support clear")
-
end
-
-
1
protected
-
# Add the namespace defined in the options to a pattern designed to
-
# match keys. Implementations that support delete_matched should call
-
# this method to translate a pattern that matches names into one that
-
# matches namespaced keys.
-
1
def key_matcher(pattern, options)
-
prefix = options[:namespace].is_a?(Proc) ? options[:namespace].call : options[:namespace]
-
if prefix
-
source = pattern.source
-
if source.start_with?('^')
-
source = source[1, source.length]
-
else
-
source = ".*#{source[0, source.length]}"
-
end
-
Regexp.new("^#{Regexp.escape(prefix)}:#{source}", pattern.options)
-
else
-
pattern
-
end
-
end
-
-
# Read an entry from the cache implementation. Subclasses must implement
-
# this method.
-
1
def read_entry(key, options) # :nodoc:
-
raise NotImplementedError.new
-
end
-
-
# Write an entry to the cache implementation. Subclasses must implement
-
# this method.
-
1
def write_entry(key, entry, options) # :nodoc:
-
raise NotImplementedError.new
-
end
-
-
# Delete an entry from the cache implementation. Subclasses must
-
# implement this method.
-
1
def delete_entry(key, options) # :nodoc:
-
raise NotImplementedError.new
-
end
-
-
1
private
-
# Merge the default options with ones specific to a method call.
-
1
def merged_options(call_options) # :nodoc:
-
if call_options
-
options.merge(call_options)
-
else
-
options.dup
-
end
-
end
-
-
# Expand key to be a consistent string value. Invoke +cache_key+ if
-
# object responds to +cache_key+. Otherwise, +to_param+ method will be
-
# called. If the key is a Hash, then keys will be sorted alphabetically.
-
1
def expanded_key(key) # :nodoc:
-
return key.cache_key.to_s if key.respond_to?(:cache_key)
-
-
case key
-
when Array
-
if key.size > 1
-
key = key.collect{|element| expanded_key(element)}
-
else
-
key = key.first
-
end
-
when Hash
-
key = key.sort_by { |k,_| k.to_s }.collect{|k,v| "#{k}=#{v}"}
-
end
-
-
key.to_param
-
end
-
-
# Prefix a key with the namespace. Namespace and key will be delimited
-
# with a colon.
-
1
def namespaced_key(key, options)
-
key = expanded_key(key)
-
namespace = options[:namespace] if options
-
prefix = namespace.is_a?(Proc) ? namespace.call : namespace
-
key = "#{prefix}:#{key}" if prefix
-
key
-
end
-
-
1
def instrument(operation, key, options = nil)
-
log(operation, key, options)
-
-
if self.class.instrument
-
payload = { :key => key }
-
payload.merge!(options) if options.is_a?(Hash)
-
ActiveSupport::Notifications.instrument("cache_#{operation}.active_support", payload){ yield(payload) }
-
else
-
yield(nil)
-
end
-
end
-
-
1
def log(operation, key, options = nil)
-
return unless logger && logger.debug? && !silence?
-
logger.debug("Cache #{operation}: #{key}#{options.blank? ? "" : " (#{options.inspect})"}")
-
end
-
-
1
def find_cached_entry(key, name, options)
-
instrument(:read, name, options) do |payload|
-
payload[:super_operation] = :fetch if payload
-
read_entry(key, options)
-
end
-
end
-
-
1
def handle_expired_entry(entry, key, options)
-
if entry && entry.expired?
-
race_ttl = options[:race_condition_ttl].to_i
-
if race_ttl && (Time.now.to_f - entry.expires_at <= race_ttl)
-
# When an entry has :race_condition_ttl defined, put the stale entry back into the cache
-
# for a brief period while the entry is begin recalculated.
-
entry.expires_at = Time.now + race_ttl
-
write_entry(key, entry, :expires_in => race_ttl * 2)
-
else
-
delete_entry(key, options)
-
end
-
entry = nil
-
end
-
entry
-
end
-
-
1
def get_entry_value(entry, name, options)
-
instrument(:fetch_hit, name, options) { |payload| }
-
entry.value
-
end
-
-
1
def save_block_result_to_cache(name, options)
-
result = instrument(:generate, name, options) do |payload|
-
yield(name)
-
end
-
-
write(name, result, options)
-
result
-
end
-
end
-
-
# This class is used to represent cache entries. Cache entries have a value and an optional
-
# expiration time. The expiration time is used to support the :race_condition_ttl option
-
# on the cache.
-
#
-
# Since cache entries in most instances will be serialized, the internals of this class are highly optimized
-
# using short instance variable names that are lazily defined.
-
1
class Entry # :nodoc:
-
1
DEFAULT_COMPRESS_LIMIT = 16.kilobytes
-
-
# Create a new cache entry for the specified value. Options supported are
-
# +:compress+, +:compress_threshold+, and +:expires_in+.
-
1
def initialize(value, options = {})
-
if should_compress?(value, options)
-
@value = compress(value)
-
@compressed = true
-
else
-
@value = value
-
end
-
-
@created_at = Time.now.to_f
-
@expires_in = options[:expires_in]
-
@expires_in = @expires_in.to_f if @expires_in
-
end
-
-
1
def value
-
convert_version_4beta1_entry! if defined?(@v)
-
compressed? ? uncompress(@value) : @value
-
end
-
-
# Check if the entry is expired. The +expires_in+ parameter can override
-
# the value set when the entry was created.
-
1
def expired?
-
convert_version_4beta1_entry! if defined?(@value)
-
@expires_in && @created_at + @expires_in <= Time.now.to_f
-
end
-
-
1
def expires_at
-
@expires_in ? @created_at + @expires_in : nil
-
end
-
-
1
def expires_at=(value)
-
if value
-
@expires_in = value.to_f - @created_at
-
else
-
@expires_in = nil
-
end
-
end
-
-
# Returns the size of the cached value. This could be less than
-
# <tt>value.size</tt> if the data is compressed.
-
1
def size
-
if defined?(@s)
-
@s
-
else
-
case value
-
when NilClass
-
0
-
when String
-
@value.bytesize
-
else
-
@s = Marshal.dump(@value).bytesize
-
end
-
end
-
end
-
-
# Duplicate the value in a class. This is used by cache implementations that don't natively
-
# serialize entries to protect against accidental cache modifications.
-
1
def dup_value!
-
convert_version_4beta1_entry! if defined?(@v)
-
-
if @value && !compressed? && !(@value.is_a?(Numeric) || @value == true || @value == false)
-
if @value.is_a?(String)
-
@value = @value.dup
-
else
-
@value = Marshal.load(Marshal.dump(@value))
-
end
-
end
-
end
-
-
1
private
-
1
def should_compress?(value, options)
-
if value && options[:compress]
-
compress_threshold = options[:compress_threshold] || DEFAULT_COMPRESS_LIMIT
-
serialized_value_size = (value.is_a?(String) ? value : Marshal.dump(value)).bytesize
-
-
return true if serialized_value_size >= compress_threshold
-
end
-
-
false
-
end
-
-
1
def compressed?
-
defined?(@compressed) ? @compressed : false
-
end
-
-
1
def compress(value)
-
Zlib::Deflate.deflate(Marshal.dump(value))
-
end
-
-
1
def uncompress(value)
-
Marshal.load(Zlib::Inflate.inflate(value))
-
end
-
-
# The internals of this method changed between Rails 3.x and 4.0. This method provides the glue
-
# to ensure that cache entries created under the old version still work with the new class definition.
-
1
def convert_version_4beta1_entry!
-
if defined?(@v)
-
@value = @v
-
remove_instance_variable(:@v)
-
end
-
-
if defined?(@c)
-
@compressed = @c
-
remove_instance_variable(:@c)
-
end
-
-
if defined?(@x) && @x
-
@created_at ||= Time.now.to_f
-
@expires_in = @x - @created_at
-
remove_instance_variable(:@x)
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/marshal'
-
1
require 'active_support/core_ext/file/atomic'
-
1
require 'active_support/core_ext/string/conversions'
-
1
require 'uri/common'
-
-
1
module ActiveSupport
-
1
module Cache
-
# A cache store implementation which stores everything on the filesystem.
-
#
-
# FileStore implements the Strategy::LocalCache strategy which implements
-
# an in-memory cache inside of a block.
-
1
class FileStore < Store
-
1
attr_reader :cache_path
-
-
1
DIR_FORMATTER = "%03X"
-
1
FILENAME_MAX_SIZE = 228 # max filename size on file system is 255, minus room for timestamp and random characters appended by Tempfile (used by atomic write)
-
1
EXCLUDED_DIRS = ['.', '..'].freeze
-
-
1
def initialize(cache_path, options = nil)
-
1
super(options)
-
1
@cache_path = cache_path.to_s
-
1
extend Strategy::LocalCache
-
end
-
-
# Deletes all items from the cache. In this case it deletes all the entries in the specified
-
# file store directory except for .gitkeep. Be careful which directory is specified in your
-
# config file when using +FileStore+ because everything in that directory will be deleted.
-
1
def clear(options = nil)
-
root_dirs = Dir.entries(cache_path).reject {|f| (EXCLUDED_DIRS + [".gitkeep"]).include?(f)}
-
FileUtils.rm_r(root_dirs.collect{|f| File.join(cache_path, f)})
-
end
-
-
# Preemptively iterates through all stored keys and removes the ones which have expired.
-
1
def cleanup(options = nil)
-
options = merged_options(options)
-
search_dir(cache_path) do |fname|
-
key = file_path_key(fname)
-
entry = read_entry(key, options)
-
delete_entry(key, options) if entry && entry.expired?
-
end
-
end
-
-
# Increments an already existing integer value that is stored in the cache.
-
# If the key is not found nothing is done.
-
1
def increment(name, amount = 1, options = nil)
-
modify_value(name, amount, options)
-
end
-
-
# Decrements an already existing integer value that is stored in the cache.
-
# If the key is not found nothing is done.
-
1
def decrement(name, amount = 1, options = nil)
-
modify_value(name, -amount, options)
-
end
-
-
1
def delete_matched(matcher, options = nil)
-
options = merged_options(options)
-
instrument(:delete_matched, matcher.inspect) do
-
matcher = key_matcher(matcher, options)
-
search_dir(cache_path) do |path|
-
key = file_path_key(path)
-
delete_entry(key, options) if key.match(matcher)
-
end
-
end
-
end
-
-
1
protected
-
-
1
def read_entry(key, options)
-
file_name = key_file_path(key)
-
if File.exist?(file_name)
-
File.open(file_name) { |f| Marshal.load(f) }
-
end
-
rescue => e
-
logger.error("FileStoreError (#{e}): #{e.message}") if logger
-
nil
-
end
-
-
1
def write_entry(key, entry, options)
-
file_name = key_file_path(key)
-
return false if options[:unless_exist] && File.exist?(file_name)
-
ensure_cache_path(File.dirname(file_name))
-
File.atomic_write(file_name, cache_path) {|f| Marshal.dump(entry, f)}
-
true
-
end
-
-
1
def delete_entry(key, options)
-
file_name = key_file_path(key)
-
if File.exist?(file_name)
-
begin
-
File.delete(file_name)
-
delete_empty_directories(File.dirname(file_name))
-
true
-
rescue => e
-
# Just in case the error was caused by another process deleting the file first.
-
raise e if File.exist?(file_name)
-
false
-
end
-
end
-
end
-
-
1
private
-
# Lock a file for a block so only one process can modify it at a time.
-
1
def lock_file(file_name, &block) # :nodoc:
-
if File.exist?(file_name)
-
File.open(file_name, 'r+') do |f|
-
begin
-
f.flock File::LOCK_EX
-
yield
-
ensure
-
f.flock File::LOCK_UN
-
end
-
end
-
else
-
yield
-
end
-
end
-
-
# Translate a key into a file path.
-
1
def key_file_path(key)
-
fname = URI.encode_www_form_component(key)
-
hash = Zlib.adler32(fname)
-
hash, dir_1 = hash.divmod(0x1000)
-
dir_2 = hash.modulo(0x1000)
-
fname_paths = []
-
-
# Make sure file name doesn't exceed file system limits.
-
begin
-
fname_paths << fname[0, FILENAME_MAX_SIZE]
-
fname = fname[FILENAME_MAX_SIZE..-1]
-
end until fname.blank?
-
-
File.join(cache_path, DIR_FORMATTER % dir_1, DIR_FORMATTER % dir_2, *fname_paths)
-
end
-
-
# Translate a file path into a key.
-
1
def file_path_key(path)
-
fname = path[cache_path.to_s.size..-1].split(File::SEPARATOR, 4).last
-
URI.decode_www_form_component(fname, Encoding::UTF_8)
-
end
-
-
# Delete empty directories in the cache.
-
1
def delete_empty_directories(dir)
-
return if File.realpath(dir) == File.realpath(cache_path)
-
if Dir.entries(dir).reject {|f| EXCLUDED_DIRS.include?(f)}.empty?
-
Dir.delete(dir) rescue nil
-
delete_empty_directories(File.dirname(dir))
-
end
-
end
-
-
# Make sure a file path's directories exist.
-
1
def ensure_cache_path(path)
-
FileUtils.makedirs(path) unless File.exist?(path)
-
end
-
-
1
def search_dir(dir, &callback)
-
return if !File.exist?(dir)
-
Dir.foreach(dir) do |d|
-
next if EXCLUDED_DIRS.include?(d)
-
name = File.join(dir, d)
-
if File.directory?(name)
-
search_dir(name, &callback)
-
else
-
callback.call name
-
end
-
end
-
end
-
-
# Modifies the amount of an already existing integer value that is stored in the cache.
-
# If the key is not found nothing is done.
-
1
def modify_value(name, amount, options)
-
file_name = key_file_path(namespaced_key(name, options))
-
-
lock_file(file_name) do
-
options = merged_options(options)
-
-
if num = read(name, options)
-
num = num.to_i + amount
-
write(name, num, options)
-
num
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/object/duplicable'
-
1
require 'active_support/core_ext/string/inflections'
-
-
1
module ActiveSupport
-
1
module Cache
-
1
module Strategy
-
# Caches that implement LocalCache will be backed by an in-memory cache for the
-
# duration of a block. Repeated calls to the cache for the same key will hit the
-
# in-memory cache for faster access.
-
1
module LocalCache
-
1
autoload :Middleware, 'active_support/cache/strategy/local_cache_middleware'
-
-
# Class for storing and registering the local caches.
-
1
class LocalCacheRegistry # :nodoc:
-
1
extend ActiveSupport::PerThreadRegistry
-
-
1
def initialize
-
@registry = {}
-
end
-
-
1
def cache_for(local_cache_key)
-
@registry[local_cache_key]
-
end
-
-
1
def set_cache_for(local_cache_key, value)
-
@registry[local_cache_key] = value
-
end
-
-
1
def self.set_cache_for(l, v); instance.set_cache_for l, v; end
-
1
def self.cache_for(l); instance.cache_for l; end
-
end
-
-
# Simple memory backed cache. This cache is not thread safe and is intended only
-
# for serving as a temporary memory cache for a single thread.
-
1
class LocalStore < Store
-
1
def initialize
-
super
-
@data = {}
-
end
-
-
# Don't allow synchronizing since it isn't thread safe,
-
1
def synchronize # :nodoc:
-
yield
-
end
-
-
1
def clear(options = nil)
-
@data.clear
-
end
-
-
1
def read_entry(key, options)
-
@data[key]
-
end
-
-
1
def write_entry(key, value, options)
-
@data[key] = value
-
true
-
end
-
-
1
def delete_entry(key, options)
-
!!@data.delete(key)
-
end
-
end
-
-
# Use a local cache for the duration of block.
-
1
def with_local_cache
-
use_temporary_local_cache(LocalStore.new) { yield }
-
end
-
# Middleware class can be inserted as a Rack handler to be local cache for the
-
# duration of request.
-
1
def middleware
-
@middleware ||= Middleware.new(
-
"ActiveSupport::Cache::Strategy::LocalCache",
-
1
local_cache_key)
-
end
-
-
1
def clear(options = nil) # :nodoc:
-
local_cache.clear(options) if local_cache
-
super
-
end
-
-
1
def cleanup(options = nil) # :nodoc:
-
local_cache.clear(options) if local_cache
-
super
-
end
-
-
1
def increment(name, amount = 1, options = nil) # :nodoc:
-
value = bypass_local_cache{super}
-
increment_or_decrement(value, name, amount, options)
-
value
-
end
-
-
1
def decrement(name, amount = 1, options = nil) # :nodoc:
-
value = bypass_local_cache{super}
-
increment_or_decrement(value, name, amount, options)
-
value
-
end
-
-
1
protected
-
1
def read_entry(key, options) # :nodoc:
-
if local_cache
-
entry = local_cache.read_entry(key, options)
-
unless entry
-
entry = super
-
local_cache.write_entry(key, entry, options)
-
end
-
entry
-
else
-
super
-
end
-
end
-
-
1
def write_entry(key, entry, options) # :nodoc:
-
local_cache.write_entry(key, entry, options) if local_cache
-
super
-
end
-
-
1
def delete_entry(key, options) # :nodoc:
-
local_cache.delete_entry(key, options) if local_cache
-
super
-
end
-
-
1
private
-
1
def increment_or_decrement(value, name, amount, options)
-
if local_cache
-
local_cache.mute do
-
if value
-
local_cache.write(name, value, options)
-
else
-
local_cache.delete(name, options)
-
end
-
end
-
end
-
end
-
-
1
def local_cache_key
-
1
@local_cache_key ||= "#{self.class.name.underscore}_local_cache_#{object_id}".gsub(/[\/-]/, '_').to_sym
-
end
-
-
1
def local_cache
-
LocalCacheRegistry.cache_for(local_cache_key)
-
end
-
-
1
def bypass_local_cache
-
use_temporary_local_cache(nil) { yield }
-
end
-
-
1
def use_temporary_local_cache(temporary_cache)
-
save_cache = LocalCacheRegistry.cache_for(local_cache_key)
-
begin
-
LocalCacheRegistry.set_cache_for(local_cache_key, temporary_cache)
-
yield
-
ensure
-
LocalCacheRegistry.set_cache_for(local_cache_key, save_cache)
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'rack/body_proxy'
-
1
module ActiveSupport
-
1
module Cache
-
1
module Strategy
-
1
module LocalCache
-
-
#--
-
# This class wraps up local storage for middlewares. Only the middleware method should
-
# construct them.
-
1
class Middleware # :nodoc:
-
1
attr_reader :name, :local_cache_key
-
-
1
def initialize(name, local_cache_key)
-
1
@name = name
-
1
@local_cache_key = local_cache_key
-
1
@app = nil
-
end
-
-
1
def new(app)
-
1
@app = app
-
1
self
-
end
-
-
1
def call(env)
-
LocalCacheRegistry.set_cache_for(local_cache_key, LocalStore.new)
-
response = @app.call(env)
-
response[2] = ::Rack::BodyProxy.new(response[2]) do
-
LocalCacheRegistry.set_cache_for(local_cache_key, nil)
-
end
-
response
-
rescue Exception
-
LocalCacheRegistry.set_cache_for(local_cache_key, nil)
-
raise
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/concern'
-
1
require 'active_support/descendants_tracker'
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'active_support/core_ext/class/attribute'
-
1
require 'active_support/core_ext/kernel/reporting'
-
1
require 'active_support/core_ext/kernel/singleton_class'
-
1
require 'thread'
-
-
1
module ActiveSupport
-
# Callbacks are code hooks that are run at key points in an object's life cycle.
-
# The typical use case is to have a base class define a set of callbacks
-
# relevant to the other functionality it supplies, so that subclasses can
-
# install callbacks that enhance or modify the base functionality without
-
# needing to override or redefine methods of the base class.
-
#
-
# Mixing in this module allows you to define the events in the object's
-
# life cycle that will support callbacks (via +ClassMethods.define_callbacks+),
-
# set the instance methods, procs, or callback objects to be called (via
-
# +ClassMethods.set_callback+), and run the installed callbacks at the
-
# appropriate times (via +run_callbacks+).
-
#
-
# Three kinds of callbacks are supported: before callbacks, run before a
-
# certain event; after callbacks, run after the event; and around callbacks,
-
# blocks that surround the event, triggering it when they yield. Callback code
-
# can be contained in instance methods, procs or lambdas, or callback objects
-
# that respond to certain predetermined methods. See +ClassMethods.set_callback+
-
# for details.
-
#
-
# class Record
-
# include ActiveSupport::Callbacks
-
# define_callbacks :save
-
#
-
# def save
-
# run_callbacks :save do
-
# puts "- save"
-
# end
-
# end
-
# end
-
#
-
# class PersonRecord < Record
-
# set_callback :save, :before, :saving_message
-
# def saving_message
-
# puts "saving..."
-
# end
-
#
-
# set_callback :save, :after do |object|
-
# puts "saved"
-
# end
-
# end
-
#
-
# person = PersonRecord.new
-
# person.save
-
#
-
# Output:
-
# saving...
-
# - save
-
# saved
-
1
module Callbacks
-
1
extend Concern
-
-
1
included do
-
7
extend ActiveSupport::DescendantsTracker
-
end
-
-
1
CALLBACK_FILTER_TYPES = [:before, :after, :around]
-
-
# Runs the callbacks for the given event.
-
#
-
# Calls the before and around callbacks in the order they were set, yields
-
# the block (if given one), and then runs the after callbacks in reverse
-
# order.
-
#
-
# If the callback chain was halted, returns +false+. Otherwise returns the
-
# result of the block, or +true+ if no block is given.
-
#
-
# run_callbacks :save do
-
# save
-
# end
-
1
def run_callbacks(kind, &block)
-
2
cbs = send("_#{kind}_callbacks")
-
2
if cbs.empty?
-
1
yield if block_given?
-
else
-
1
runner = cbs.compile
-
1
e = Filters::Environment.new(self, false, nil, block)
-
1
runner.call(e).value
-
end
-
end
-
-
1
private
-
-
# A hook invoked every time a before callback is halted.
-
# This can be overridden in AS::Callback implementors in order
-
# to provide better debugging/logging.
-
1
def halted_callback_hook(filter)
-
end
-
-
1
module Conditionals # :nodoc:
-
1
class Value
-
1
def initialize(&block)
-
19
@block = block
-
end
-
1
def call(target, value); @block.call(value); end
-
end
-
end
-
-
1
module Filters
-
1
Environment = Struct.new(:target, :halted, :value, :run_block)
-
-
1
class End
-
1
def call(env)
-
1
block = env.run_block
-
1
env.value = !env.halted && (!block || block.call)
-
1
env
-
end
-
end
-
1
ENDING = End.new
-
-
1
class Before
-
1
def self.build(next_callback, user_callback, user_conditions, chain_config, filter)
-
1
halted_lambda = chain_config[:terminator]
-
-
1
if chain_config.key?(:terminator) && user_conditions.any?
-
halting_and_conditional(next_callback, user_callback, user_conditions, halted_lambda, filter)
-
1
elsif chain_config.key? :terminator
-
halting(next_callback, user_callback, halted_lambda, filter)
-
1
elsif user_conditions.any?
-
conditional(next_callback, user_callback, user_conditions)
-
else
-
1
simple next_callback, user_callback
-
end
-
end
-
-
1
private
-
-
1
def self.halting_and_conditional(next_callback, user_callback, user_conditions, halted_lambda, filter)
-
lambda { |env|
-
target = env.target
-
value = env.value
-
halted = env.halted
-
-
if !halted && user_conditions.all? { |c| c.call(target, value) }
-
result = user_callback.call target, value
-
env.halted = halted_lambda.call(target, result)
-
if env.halted
-
target.send :halted_callback_hook, filter
-
end
-
end
-
next_callback.call env
-
}
-
end
-
-
1
def self.halting(next_callback, user_callback, halted_lambda, filter)
-
lambda { |env|
-
target = env.target
-
value = env.value
-
halted = env.halted
-
-
unless halted
-
result = user_callback.call target, value
-
env.halted = halted_lambda.call(target, result)
-
if env.halted
-
target.send :halted_callback_hook, filter
-
end
-
end
-
next_callback.call env
-
}
-
end
-
-
1
def self.conditional(next_callback, user_callback, user_conditions)
-
lambda { |env|
-
target = env.target
-
value = env.value
-
-
if user_conditions.all? { |c| c.call(target, value) }
-
user_callback.call target, value
-
end
-
next_callback.call env
-
}
-
end
-
-
1
def self.simple(next_callback, user_callback)
-
1
lambda { |env|
-
1
user_callback.call env.target, env.value
-
1
next_callback.call env
-
}
-
end
-
end
-
-
1
class After
-
1
def self.build(next_callback, user_callback, user_conditions, chain_config)
-
if chain_config[:skip_after_callbacks_if_terminated]
-
if chain_config.key?(:terminator) && user_conditions.any?
-
halting_and_conditional(next_callback, user_callback, user_conditions)
-
elsif chain_config.key?(:terminator)
-
halting(next_callback, user_callback)
-
elsif user_conditions.any?
-
conditional next_callback, user_callback, user_conditions
-
else
-
simple next_callback, user_callback
-
end
-
else
-
if user_conditions.any?
-
conditional next_callback, user_callback, user_conditions
-
else
-
simple next_callback, user_callback
-
end
-
end
-
end
-
-
1
private
-
-
1
def self.halting_and_conditional(next_callback, user_callback, user_conditions)
-
lambda { |env|
-
env = next_callback.call env
-
target = env.target
-
value = env.value
-
halted = env.halted
-
-
if !halted && user_conditions.all? { |c| c.call(target, value) }
-
user_callback.call target, value
-
end
-
env
-
}
-
end
-
-
1
def self.halting(next_callback, user_callback)
-
lambda { |env|
-
env = next_callback.call env
-
unless env.halted
-
user_callback.call env.target, env.value
-
end
-
env
-
}
-
end
-
-
1
def self.conditional(next_callback, user_callback, user_conditions)
-
lambda { |env|
-
env = next_callback.call env
-
target = env.target
-
value = env.value
-
-
if user_conditions.all? { |c| c.call(target, value) }
-
user_callback.call target, value
-
end
-
env
-
}
-
end
-
-
1
def self.simple(next_callback, user_callback)
-
lambda { |env|
-
env = next_callback.call env
-
user_callback.call env.target, env.value
-
env
-
}
-
end
-
end
-
-
1
class Around
-
1
def self.build(next_callback, user_callback, user_conditions, chain_config)
-
if chain_config.key?(:terminator) && user_conditions.any?
-
halting_and_conditional(next_callback, user_callback, user_conditions)
-
elsif chain_config.key? :terminator
-
halting(next_callback, user_callback)
-
elsif user_conditions.any?
-
conditional(next_callback, user_callback, user_conditions)
-
else
-
simple(next_callback, user_callback)
-
end
-
end
-
-
1
private
-
-
1
def self.halting_and_conditional(next_callback, user_callback, user_conditions)
-
lambda { |env|
-
target = env.target
-
value = env.value
-
halted = env.halted
-
-
if !halted && user_conditions.all? { |c| c.call(target, value) }
-
user_callback.call(target, value) {
-
env = next_callback.call env
-
env.value
-
}
-
env
-
else
-
next_callback.call env
-
end
-
}
-
end
-
-
1
def self.halting(next_callback, user_callback)
-
lambda { |env|
-
target = env.target
-
value = env.value
-
-
unless env.halted
-
user_callback.call(target, value) {
-
env = next_callback.call env
-
env.value
-
}
-
env
-
else
-
next_callback.call env
-
end
-
}
-
end
-
-
1
def self.conditional(next_callback, user_callback, user_conditions)
-
lambda { |env|
-
target = env.target
-
value = env.value
-
-
if user_conditions.all? { |c| c.call(target, value) }
-
user_callback.call(target, value) {
-
env = next_callback.call env
-
env.value
-
}
-
env
-
else
-
next_callback.call env
-
end
-
}
-
end
-
-
1
def self.simple(next_callback, user_callback)
-
lambda { |env|
-
user_callback.call(env.target, env.value) {
-
env = next_callback.call env
-
env.value
-
}
-
env
-
}
-
end
-
end
-
end
-
-
1
class Callback #:nodoc:#
-
1
def self.build(chain, filter, kind, options)
-
71
new chain.name, filter, kind, options, chain.config
-
end
-
-
1
attr_accessor :kind, :name
-
1
attr_reader :chain_config
-
-
1
def initialize(name, filter, kind, options, chain_config)
-
71
@chain_config = chain_config
-
71
@name = name
-
71
@kind = kind
-
71
@filter = filter
-
71
@key = compute_identifier filter
-
71
@if = Array(options[:if])
-
71
@unless = Array(options[:unless])
-
end
-
-
238
def filter; @key; end
-
1
def raw_filter; @filter; end
-
-
1
def merge(chain, new_options)
-
options = {
-
:if => @if.dup,
-
:unless => @unless.dup
-
}
-
-
options[:if].concat Array(new_options.fetch(:unless, []))
-
options[:unless].concat Array(new_options.fetch(:if, []))
-
-
self.class.build chain, @filter, @kind, options
-
end
-
-
1
def matches?(_kind, _filter)
-
130
@kind == _kind && filter == _filter
-
end
-
-
1
def duplicates?(other)
-
298
case @filter
-
when Symbol, String
-
130
matches?(other.kind, other.filter)
-
else
-
168
false
-
end
-
end
-
-
# Wraps code with filter
-
1
def apply(next_callback)
-
1
user_conditions = conditions_lambdas
-
1
user_callback = make_lambda @filter
-
-
1
case kind
-
when :before
-
1
Filters::Before.build(next_callback, user_callback, user_conditions, chain_config, @filter)
-
when :after
-
Filters::After.build(next_callback, user_callback, user_conditions, chain_config)
-
when :around
-
Filters::Around.build(next_callback, user_callback, user_conditions, chain_config)
-
end
-
end
-
-
1
private
-
-
1
def invert_lambda(l)
-
lambda { |*args, &blk| !l.call(*args, &blk) }
-
end
-
-
# Filters support:
-
#
-
# Symbols:: A method to call.
-
# Strings:: Some content to evaluate.
-
# Procs:: A proc to call with the object.
-
# Objects:: An object with a <tt>before_foo</tt> method on it to call.
-
#
-
# All of these objects are compiled into methods and handled
-
# the same after this point:
-
#
-
# Symbols:: Already methods.
-
# Strings:: class_eval'd into methods.
-
# Procs:: using define_method compiled into methods.
-
# Objects::
-
# a method is created that calls the before_foo method
-
# on the object.
-
1
def make_lambda(filter)
-
1
case filter
-
when Symbol
-
lambda { |target, _, &blk| target.send filter, &blk }
-
when String
-
l = eval "lambda { |value| #{filter} }"
-
lambda { |target, value| target.instance_exec(value, &l) }
-
when Conditionals::Value then filter
-
when ::Proc
-
1
if filter.arity > 1
-
return lambda { |target, _, &block|
-
raise ArgumentError unless block
-
target.instance_exec(target, block, &filter)
-
}
-
end
-
-
1
if filter.arity <= 0
-
2
lambda { |target, _| target.instance_exec(&filter) }
-
else
-
lambda { |target, _| target.instance_exec(target, &filter) }
-
end
-
else
-
scopes = Array(chain_config[:scope])
-
method_to_call = scopes.map{ |s| public_send(s) }.join("_")
-
-
lambda { |target, _, &blk|
-
filter.public_send method_to_call, target, &blk
-
}
-
end
-
end
-
-
1
def compute_identifier(filter)
-
71
case filter
-
when String, ::Proc
-
4
filter.object_id
-
else
-
67
filter
-
end
-
end
-
-
1
def conditions_lambdas
-
@if.map { |c| make_lambda c } +
-
1
@unless.map { |c| invert_lambda make_lambda c }
-
end
-
end
-
-
# An Array with a compile method.
-
1
class CallbackChain #:nodoc:#
-
1
include Enumerable
-
-
1
attr_reader :name, :config
-
-
1
def initialize(name, config)
-
20
@name = name
-
20
@config = {
-
:scope => [ :kind ]
-
}.merge!(config)
-
20
@chain = []
-
20
@callbacks = nil
-
20
@mutex = Mutex.new
-
end
-
-
1
def each(&block); @chain.each(&block); end
-
1
def index(o); @chain.index(o); end
-
3
def empty?; @chain.empty?; end
-
-
1
def insert(index, o)
-
@callbacks = nil
-
@chain.insert(index, o)
-
end
-
-
1
def delete(o)
-
@callbacks = nil
-
@chain.delete(o)
-
end
-
-
1
def clear
-
@callbacks = nil
-
@chain.clear
-
self
-
end
-
-
1
def initialize_copy(other)
-
71
@callbacks = nil
-
71
@chain = other.chain.dup
-
71
@mutex = Mutex.new
-
end
-
-
1
def compile
-
@callbacks || @mutex.synchronize do
-
@callbacks ||= @chain.reverse.inject(Filters::ENDING) do |chain, callback|
-
1
callback.apply chain
-
1
end
-
1
end
-
end
-
-
1
def append(*callbacks)
-
102
callbacks.each { |c| append_one(c) }
-
end
-
-
1
def prepend(*callbacks)
-
40
callbacks.each { |c| prepend_one(c) }
-
end
-
-
1
protected
-
72
def chain; @chain; end
-
-
1
private
-
-
1
def append_one(callback)
-
51
@callbacks = nil
-
51
remove_duplicates(callback)
-
51
@chain.push(callback)
-
end
-
-
1
def prepend_one(callback)
-
20
@callbacks = nil
-
20
remove_duplicates(callback)
-
20
@chain.unshift(callback)
-
end
-
-
1
def remove_duplicates(callback)
-
71
@callbacks = nil
-
369
@chain.delete_if { |c| callback.duplicates?(c) }
-
end
-
end
-
-
1
module ClassMethods
-
1
def normalize_callback_params(filters, block) # :nodoc:
-
71
type = CALLBACK_FILTER_TYPES.include?(filters.first) ? filters.shift : :before
-
71
options = filters.extract_options!
-
71
filters.unshift(block) if block
-
71
[type, filters, options.dup]
-
end
-
-
# This is used internally to append, prepend and skip callbacks to the
-
# CallbackChain.
-
1
def __update_callbacks(name) #:nodoc:
-
71
([self] + ActiveSupport::DescendantsTracker.descendants(self)).reverse.each do |target|
-
71
chain = target.get_callbacks name
-
71
yield target, chain.dup
-
end
-
end
-
-
# Install a callback for the given event.
-
#
-
# set_callback :save, :before, :before_meth
-
# set_callback :save, :after, :after_meth, if: :condition
-
# set_callback :save, :around, ->(r, &block) { stuff; result = block.call; stuff }
-
#
-
# The second arguments indicates whether the callback is to be run +:before+,
-
# +:after+, or +:around+ the event. If omitted, +:before+ is assumed. This
-
# means the first example above can also be written as:
-
#
-
# set_callback :save, :before_meth
-
#
-
# The callback can be specified as a symbol naming an instance method; as a
-
# proc, lambda, or block; as a string to be instance evaluated; or as an
-
# object that responds to a certain method determined by the <tt>:scope</tt>
-
# argument to +define_callbacks+.
-
#
-
# If a proc, lambda, or block is given, its body is evaluated in the context
-
# of the current object. It can also optionally accept the current object as
-
# an argument.
-
#
-
# Before and around callbacks are called in the order that they are set;
-
# after callbacks are called in the reverse order.
-
#
-
# Around callbacks can access the return value from the event, if it
-
# wasn't halted, from the +yield+ call.
-
#
-
# ===== Options
-
#
-
# * <tt>:if</tt> - A symbol naming an instance method or a proc; the
-
# callback will be called only when it returns a +true+ value.
-
# * <tt>:unless</tt> - A symbol naming an instance method or a proc; the
-
# callback will be called only when it returns a +false+ value.
-
# * <tt>:prepend</tt> - If +true+, the callback will be prepended to the
-
# existing chain rather than appended.
-
1
def set_callback(name, *filter_list, &block)
-
71
type, filters, options = normalize_callback_params(filter_list, block)
-
71
self_chain = get_callbacks name
-
71
mapped = filters.map do |filter|
-
71
Callback.build(self_chain, filter, type, options)
-
end
-
-
71
__update_callbacks(name) do |target, chain|
-
71
options[:prepend] ? chain.prepend(*mapped) : chain.append(*mapped)
-
71
target.set_callbacks name, chain
-
end
-
end
-
-
# Skip a previously set callback. Like +set_callback+, <tt>:if</tt> or
-
# <tt>:unless</tt> options may be passed in order to control when the
-
# callback is skipped.
-
#
-
# class Writer < Person
-
# skip_callback :validate, :before, :check_membership, if: -> { self.age > 18 }
-
# end
-
1
def skip_callback(name, *filter_list, &block)
-
type, filters, options = normalize_callback_params(filter_list, block)
-
-
__update_callbacks(name) do |target, chain|
-
filters.each do |filter|
-
filter = chain.find {|c| c.matches?(type, filter) }
-
-
if filter && options.any?
-
new_filter = filter.merge(chain, options)
-
chain.insert(chain.index(filter), new_filter)
-
end
-
-
chain.delete(filter)
-
end
-
target.set_callbacks name, chain
-
end
-
end
-
-
# Remove all set callbacks for the given event.
-
1
def reset_callbacks(name)
-
callbacks = get_callbacks name
-
-
ActiveSupport::DescendantsTracker.descendants(self).each do |target|
-
chain = target.get_callbacks(name).dup
-
callbacks.each { |c| chain.delete(c) }
-
target.set_callbacks name, chain
-
end
-
-
self.set_callbacks name, callbacks.dup.clear
-
end
-
-
# Define sets of events in the object life cycle that support callbacks.
-
#
-
# define_callbacks :validate
-
# define_callbacks :initialize, :save, :destroy
-
#
-
# ===== Options
-
#
-
# * <tt>:terminator</tt> - Determines when a before filter will halt the
-
# callback chain, preventing following callbacks from being called and
-
# the event from being triggered. This should be a lambda to be executed.
-
# The current object and the return result of the callback will be called
-
# with the lambda.
-
#
-
# define_callbacks :validate, terminator: ->(target, result) { result == false }
-
#
-
# In this example, if any before validate callbacks returns +false+,
-
# other callbacks are not executed. Defaults to +false+, meaning no value
-
# halts the chain.
-
#
-
# * <tt>:skip_after_callbacks_if_terminated</tt> - Determines if after
-
# callbacks should be terminated by the <tt>:terminator</tt> option. By
-
# default after callbacks executed no matter if callback chain was
-
# terminated or not. Option makes sense only when <tt>:terminator</tt>
-
# option is specified.
-
#
-
# * <tt>:scope</tt> - Indicates which methods should be executed when an
-
# object is used as a callback.
-
#
-
# class Audit
-
# def before(caller)
-
# puts 'Audit: before is called'
-
# end
-
#
-
# def before_save(caller)
-
# puts 'Audit: before_save is called'
-
# end
-
# end
-
#
-
# class Account
-
# include ActiveSupport::Callbacks
-
#
-
# define_callbacks :save
-
# set_callback :save, :before, Audit.new
-
#
-
# def save
-
# run_callbacks :save do
-
# puts 'save in main'
-
# end
-
# end
-
# end
-
#
-
# In the above case whenever you save an account the method
-
# <tt>Audit#before</tt> will be called. On the other hand
-
#
-
# define_callbacks :save, scope: [:kind, :name]
-
#
-
# would trigger <tt>Audit#before_save</tt> instead. That's constructed
-
# by calling <tt>#{kind}_#{name}</tt> on the given instance. In this
-
# case "kind" is "before" and "name" is "save". In this context +:kind+
-
# and +:name+ have special meanings: +:kind+ refers to the kind of
-
# callback (before/after/around) and +:name+ refers to the method on
-
# which callbacks are being defined.
-
#
-
# A declaration like
-
#
-
# define_callbacks :save, scope: [:name]
-
#
-
# would call <tt>Audit#save</tt>.
-
1
def define_callbacks(*names)
-
17
options = names.extract_options!
-
17
if options.key?(:terminator) && String === options[:terminator]
-
ActiveSupport::Deprecation.warn "String based terminators are deprecated, please use a lambda"
-
value = options[:terminator]
-
line = class_eval "lambda { |result| #{value} }", __FILE__, __LINE__
-
options[:terminator] = lambda { |target, result| target.instance_exec(result, &line) }
-
end
-
-
17
names.each do |name|
-
20
class_attribute "_#{name}_callbacks"
-
20
set_callbacks name, CallbackChain.new(name, options)
-
end
-
end
-
-
1
protected
-
-
1
def get_callbacks(name)
-
142
send "_#{name}_callbacks"
-
end
-
-
1
def set_callbacks(name, callbacks)
-
91
send "_#{name}_callbacks=", callbacks
-
end
-
end
-
end
-
end
-
1
module ActiveSupport
-
# A typical module looks like this:
-
#
-
# module M
-
# def self.included(base)
-
# base.extend ClassMethods
-
# base.class_eval do
-
# scope :disabled, -> { where(disabled: true) }
-
# end
-
# end
-
#
-
# module ClassMethods
-
# ...
-
# end
-
# end
-
#
-
# By using <tt>ActiveSupport::Concern</tt> the above module could instead be
-
# written as:
-
#
-
# require 'active_support/concern'
-
#
-
# module M
-
# extend ActiveSupport::Concern
-
#
-
# included do
-
# scope :disabled, -> { where(disabled: true) }
-
# end
-
#
-
# module ClassMethods
-
# ...
-
# end
-
# end
-
#
-
# Moreover, it gracefully handles module dependencies. Given a +Foo+ module
-
# and a +Bar+ module which depends on the former, we would typically write the
-
# following:
-
#
-
# module Foo
-
# def self.included(base)
-
# base.class_eval do
-
# def self.method_injected_by_foo
-
# ...
-
# end
-
# end
-
# end
-
# end
-
#
-
# module Bar
-
# def self.included(base)
-
# base.method_injected_by_foo
-
# end
-
# end
-
#
-
# class Host
-
# include Foo # We need to include this dependency for Bar
-
# include Bar # Bar is the module that Host really needs
-
# end
-
#
-
# But why should +Host+ care about +Bar+'s dependencies, namely +Foo+? We
-
# could try to hide these from +Host+ directly including +Foo+ in +Bar+:
-
#
-
# module Bar
-
# include Foo
-
# def self.included(base)
-
# base.method_injected_by_foo
-
# end
-
# end
-
#
-
# class Host
-
# include Bar
-
# end
-
#
-
# Unfortunately this won't work, since when +Foo+ is included, its <tt>base</tt>
-
# is the +Bar+ module, not the +Host+ class. With <tt>ActiveSupport::Concern</tt>,
-
# module dependencies are properly resolved:
-
#
-
# require 'active_support/concern'
-
#
-
# module Foo
-
# extend ActiveSupport::Concern
-
# included do
-
# def self.method_injected_by_foo
-
# ...
-
# end
-
# end
-
# end
-
#
-
# module Bar
-
# extend ActiveSupport::Concern
-
# include Foo
-
#
-
# included do
-
# self.method_injected_by_foo
-
# end
-
# end
-
#
-
# class Host
-
# include Bar # works, Bar takes care now of its dependencies
-
# end
-
1
module Concern
-
1
class MultipleIncludedBlocks < StandardError #:nodoc:
-
1
def initialize
-
super "Cannot define multiple 'included' blocks for a Concern"
-
end
-
end
-
-
1
def self.extended(base) #:nodoc:
-
147
base.instance_variable_set(:@_dependencies, [])
-
end
-
-
1
def append_features(base)
-
327
if base.instance_variable_defined?(:@_dependencies)
-
87
base.instance_variable_get(:@_dependencies) << self
-
87
return false
-
else
-
240
return false if base < self
-
284
@_dependencies.each { |dep| base.send(:include, dep) }
-
188
super
-
188
base.extend const_get(:ClassMethods) if const_defined?(:ClassMethods)
-
188
base.class_eval(&@_included_block) if instance_variable_defined?(:@_included_block)
-
end
-
end
-
-
1
def included(base = nil, &block)
-
417
if base.nil?
-
90
raise MultipleIncludedBlocks if instance_variable_defined?(:@_included_block)
-
-
90
@_included_block = block
-
else
-
327
super
-
end
-
end
-
end
-
end
-
1
require 'active_support/concern'
-
1
require 'active_support/ordered_options'
-
1
require 'active_support/core_ext/array/extract_options'
-
-
1
module ActiveSupport
-
# Configurable provides a <tt>config</tt> method to store and retrieve
-
# configuration options as an <tt>OrderedHash</tt>.
-
1
module Configurable
-
1
extend ActiveSupport::Concern
-
-
1
class Configuration < ActiveSupport::InheritableOptions
-
1
def compile_methods!
-
2
self.class.compile_methods!(keys)
-
end
-
-
# Compiles reader methods so we don't have to go through method_missing.
-
1
def self.compile_methods!(keys)
-
20
keys.reject { |m| method_defined?(m) }.each do |key|
-
12
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{key}; _get(#{key.inspect}); end
-
RUBY
-
end
-
end
-
end
-
-
1
module ClassMethods
-
1
def config
-
@_config ||= if respond_to?(:superclass) && superclass.respond_to?(:config)
-
3
superclass.config.inheritable_copy
-
else
-
# create a new "anonymous" class that will host the compiled reader methods
-
2
Class.new(Configuration).new
-
33
end
-
end
-
-
1
def configure
-
yield config
-
end
-
-
# Allows you to add shortcut so that you don't have to refer to attribute
-
# through config. Also look at the example for config to contrast.
-
#
-
# Defines both class and instance config accessors.
-
#
-
# class User
-
# include ActiveSupport::Configurable
-
# config_accessor :allowed_access
-
# end
-
#
-
# User.allowed_access # => nil
-
# User.allowed_access = false
-
# User.allowed_access # => false
-
#
-
# user = User.new
-
# user.allowed_access # => false
-
# user.allowed_access = true
-
# user.allowed_access # => true
-
#
-
# User.allowed_access # => false
-
#
-
# The attribute name must be a valid method name in Ruby.
-
#
-
# class User
-
# include ActiveSupport::Configurable
-
# config_accessor :"1_Badname"
-
# end
-
# # => NameError: invalid config attribute name
-
#
-
# To opt out of the instance writer method, pass <tt>instance_writer: false</tt>.
-
# To opt out of the instance reader method, pass <tt>instance_reader: false</tt>.
-
#
-
# class User
-
# include ActiveSupport::Configurable
-
# config_accessor :allowed_access, instance_reader: false, instance_writer: false
-
# end
-
#
-
# User.allowed_access = false
-
# User.allowed_access # => false
-
#
-
# User.new.allowed_access = true # => NoMethodError
-
# User.new.allowed_access # => NoMethodError
-
#
-
# Or pass <tt>instance_accessor: false</tt>, to opt out both instance methods.
-
#
-
# class User
-
# include ActiveSupport::Configurable
-
# config_accessor :allowed_access, instance_accessor: false
-
# end
-
#
-
# User.allowed_access = false
-
# User.allowed_access # => false
-
#
-
# User.new.allowed_access = true # => NoMethodError
-
# User.new.allowed_access # => NoMethodError
-
#
-
# Also you can pass a block to set up the attribute with a default value.
-
#
-
# class User
-
# include ActiveSupport::Configurable
-
# config_accessor :hair_colors do
-
# [:brown, :black, :blonde, :red]
-
# end
-
# end
-
#
-
# User.hair_colors # => [:brown, :black, :blonde, :red]
-
1
def config_accessor(*names)
-
18
options = names.extract_options!
-
-
18
names.each do |name|
-
28
raise NameError.new('invalid config attribute name') unless name =~ /\A[_A-Za-z]\w*\z/
-
-
28
reader, reader_line = "def #{name}; config.#{name}; end", __LINE__
-
28
writer, writer_line = "def #{name}=(value); config.#{name} = value; end", __LINE__
-
-
28
singleton_class.class_eval reader, __FILE__, reader_line
-
28
singleton_class.class_eval writer, __FILE__, writer_line
-
-
28
unless options[:instance_accessor] == false
-
28
class_eval reader, __FILE__, reader_line unless options[:instance_reader] == false
-
28
class_eval writer, __FILE__, writer_line unless options[:instance_writer] == false
-
end
-
28
send("#{name}=", yield) if block_given?
-
end
-
end
-
end
-
-
# Reads and writes attributes from a configuration <tt>OrderedHash</tt>.
-
#
-
# require 'active_support/configurable'
-
#
-
# class User
-
# include ActiveSupport::Configurable
-
# end
-
#
-
# user = User.new
-
#
-
# user.config.allowed_access = true
-
# user.config.level = 1
-
#
-
# user.config.allowed_access # => true
-
# user.config.level # => 1
-
1
def config
-
12
@_config ||= self.class.config.inheritable_copy
-
end
-
end
-
end
-
-
1
Dir["#{File.dirname(__FILE__)}/core_ext/*.rb"].each do |path|
-
24
require path
-
end
-
1
require 'active_support/core_ext/array/wrap'
-
1
require 'active_support/core_ext/array/access'
-
1
require 'active_support/core_ext/array/conversions'
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'active_support/core_ext/array/grouping'
-
1
require 'active_support/core_ext/array/prepend_and_append'
-
1
class Array
-
# Returns the tail of the array from +position+.
-
#
-
# %w( a b c d ).from(0) # => ["a", "b", "c", "d"]
-
# %w( a b c d ).from(2) # => ["c", "d"]
-
# %w( a b c d ).from(10) # => []
-
# %w().from(0) # => []
-
1
def from(position)
-
self[position, length] || []
-
end
-
-
# Returns the beginning of the array up to +position+.
-
#
-
# %w( a b c d ).to(0) # => ["a"]
-
# %w( a b c d ).to(2) # => ["a", "b", "c"]
-
# %w( a b c d ).to(10) # => ["a", "b", "c", "d"]
-
# %w().to(0) # => []
-
1
def to(position)
-
first position + 1
-
end
-
-
# Equal to <tt>self[1]</tt>.
-
#
-
# %w( a b c d e ).second # => "b"
-
1
def second
-
self[1]
-
end
-
-
# Equal to <tt>self[2]</tt>.
-
#
-
# %w( a b c d e ).third # => "c"
-
1
def third
-
self[2]
-
end
-
-
# Equal to <tt>self[3]</tt>.
-
#
-
# %w( a b c d e ).fourth # => "d"
-
1
def fourth
-
self[3]
-
end
-
-
# Equal to <tt>self[4]</tt>.
-
#
-
# %w( a b c d e ).fifth # => "e"
-
1
def fifth
-
self[4]
-
end
-
-
# Equal to <tt>self[41]</tt>. Also known as accessing "the reddit".
-
#
-
# (1..42).to_a.forty_two # => 42
-
1
def forty_two
-
self[41]
-
end
-
end
-
1
require 'active_support/xml_mini'
-
1
require 'active_support/core_ext/hash/keys'
-
1
require 'active_support/core_ext/string/inflections'
-
1
require 'active_support/core_ext/object/to_param'
-
1
require 'active_support/core_ext/object/to_query'
-
-
1
class Array
-
# Converts the array to a comma-separated sentence where the last element is
-
# joined by the connector word.
-
#
-
# You can pass the following options to change the default behavior. If you
-
# pass an option key that doesn't exist in the list below, it will raise an
-
# <tt>ArgumentError</tt>.
-
#
-
# ==== Options
-
#
-
# * <tt>:words_connector</tt> - The sign or word used to join the elements
-
# in arrays with two or more elements (default: ", ").
-
# * <tt>:two_words_connector</tt> - The sign or word used to join the elements
-
# in arrays with two elements (default: " and ").
-
# * <tt>:last_word_connector</tt> - The sign or word used to join the last element
-
# in arrays with three or more elements (default: ", and ").
-
# * <tt>:locale</tt> - If +i18n+ is available, you can set a locale and use
-
# the connector options defined on the 'support.array' namespace in the
-
# corresponding dictionary file.
-
#
-
# ==== Examples
-
#
-
# [].to_sentence # => ""
-
# ['one'].to_sentence # => "one"
-
# ['one', 'two'].to_sentence # => "one and two"
-
# ['one', 'two', 'three'].to_sentence # => "one, two, and three"
-
#
-
# ['one', 'two'].to_sentence(passing: 'invalid option')
-
# # => ArgumentError: Unknown key :passing
-
#
-
# ['one', 'two'].to_sentence(two_words_connector: '-')
-
# # => "one-two"
-
#
-
# ['one', 'two', 'three'].to_sentence(words_connector: ' or ', last_word_connector: ' or at least ')
-
# # => "one or two or at least three"
-
#
-
# Using <tt>:locale</tt> option:
-
#
-
# # Given this locale dictionary:
-
# #
-
# # es:
-
# # support:
-
# # array:
-
# # words_connector: " o "
-
# # two_words_connector: " y "
-
# # last_word_connector: " o al menos "
-
#
-
# ['uno', 'dos'].to_sentence(locale: :es)
-
# # => "uno y dos"
-
#
-
# ['uno', 'dos', 'tres'].to_sentence(locale: :es)
-
# # => "uno o dos o al menos tres"
-
1
def to_sentence(options = {})
-
options.assert_valid_keys(:words_connector, :two_words_connector, :last_word_connector, :locale)
-
-
default_connectors = {
-
:words_connector => ', ',
-
:two_words_connector => ' and ',
-
:last_word_connector => ', and '
-
}
-
if defined?(I18n)
-
i18n_connectors = I18n.translate(:'support.array', locale: options[:locale], default: {})
-
default_connectors.merge!(i18n_connectors)
-
end
-
options = default_connectors.merge!(options)
-
-
case length
-
when 0
-
''
-
when 1
-
self[0].to_s.dup
-
when 2
-
"#{self[0]}#{options[:two_words_connector]}#{self[1]}"
-
else
-
"#{self[0...-1].join(options[:words_connector])}#{options[:last_word_connector]}#{self[-1]}"
-
end
-
end
-
-
# Extends <tt>Array#to_s</tt> to convert a collection of elements into a
-
# comma separated id list if <tt>:db</tt> argument is given as the format.
-
#
-
# Blog.all.to_formatted_s(:db) # => "1,2,3"
-
1
def to_formatted_s(format = :default)
-
2
case format
-
when :db
-
if empty?
-
'null'
-
else
-
collect { |element| element.id }.join(',')
-
end
-
else
-
2
to_default_s
-
end
-
end
-
1
alias_method :to_default_s, :to_s
-
1
alias_method :to_s, :to_formatted_s
-
-
# Returns a string that represents the array in XML by invoking +to_xml+
-
# on each element. Active Record collections delegate their representation
-
# in XML to this method.
-
#
-
# All elements are expected to respond to +to_xml+, if any of them does
-
# not then an exception is raised.
-
#
-
# The root node reflects the class name of the first element in plural
-
# if all elements belong to the same type and that's not Hash:
-
#
-
# customer.projects.to_xml
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <projects type="array">
-
# <project>
-
# <amount type="decimal">20000.0</amount>
-
# <customer-id type="integer">1567</customer-id>
-
# <deal-date type="date">2008-04-09</deal-date>
-
# ...
-
# </project>
-
# <project>
-
# <amount type="decimal">57230.0</amount>
-
# <customer-id type="integer">1567</customer-id>
-
# <deal-date type="date">2008-04-15</deal-date>
-
# ...
-
# </project>
-
# </projects>
-
#
-
# Otherwise the root element is "objects":
-
#
-
# [{ foo: 1, bar: 2}, { baz: 3}].to_xml
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <objects type="array">
-
# <object>
-
# <bar type="integer">2</bar>
-
# <foo type="integer">1</foo>
-
# </object>
-
# <object>
-
# <baz type="integer">3</baz>
-
# </object>
-
# </objects>
-
#
-
# If the collection is empty the root element is "nil-classes" by default:
-
#
-
# [].to_xml
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <nil-classes type="array"/>
-
#
-
# To ensure a meaningful root element use the <tt>:root</tt> option:
-
#
-
# customer_with_no_projects.projects.to_xml(root: 'projects')
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <projects type="array"/>
-
#
-
# By default name of the node for the children of root is <tt>root.singularize</tt>.
-
# You can change it with the <tt>:children</tt> option.
-
#
-
# The +options+ hash is passed downwards:
-
#
-
# Message.all.to_xml(skip_types: true)
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <messages>
-
# <message>
-
# <created-at>2008-03-07T09:58:18+01:00</created-at>
-
# <id>1</id>
-
# <name>1</name>
-
# <updated-at>2008-03-07T09:58:18+01:00</updated-at>
-
# <user-id>1</user-id>
-
# </message>
-
# </messages>
-
#
-
1
def to_xml(options = {})
-
require 'active_support/builder' unless defined?(Builder)
-
-
options = options.dup
-
options[:indent] ||= 2
-
options[:builder] ||= Builder::XmlMarkup.new(indent: options[:indent])
-
options[:root] ||= \
-
if first.class != Hash && all? { |e| e.is_a?(first.class) }
-
underscored = ActiveSupport::Inflector.underscore(first.class.name)
-
ActiveSupport::Inflector.pluralize(underscored).tr('/', '_')
-
else
-
'objects'
-
end
-
-
builder = options[:builder]
-
builder.instruct! unless options.delete(:skip_instruct)
-
-
root = ActiveSupport::XmlMini.rename_key(options[:root].to_s, options)
-
children = options.delete(:children) || root.singularize
-
attributes = options[:skip_types] ? {} : { type: 'array' }
-
-
if empty?
-
builder.tag!(root, attributes)
-
else
-
builder.tag!(root, attributes) do
-
each { |value| ActiveSupport::XmlMini.to_tag(children, value, options) }
-
yield builder if block_given?
-
end
-
end
-
end
-
end
-
1
class Hash
-
# By default, only instances of Hash itself are extractable.
-
# Subclasses of Hash may implement this method and return
-
# true to declare themselves as extractable. If a Hash
-
# is extractable, Array#extract_options! pops it from
-
# the Array when it is the last element of the Array.
-
1
def extractable_options?
-
173
instance_of?(Hash)
-
end
-
end
-
-
1
class Array
-
# Extracts options from a set of arguments. Removes and returns the last
-
# element in the array if it's a hash, otherwise returns a blank hash.
-
#
-
# def options(*args)
-
# args.extract_options!
-
# end
-
#
-
# options(1, 2) # => {}
-
# options(1, 2, a: :b) # => {:a=>:b}
-
1
def extract_options!
-
643
if last.is_a?(Hash) && last.extractable_options?
-
173
pop
-
else
-
470
{}
-
end
-
end
-
end
-
1
class Array
-
# Splits or iterates over the array in groups of size +number+,
-
# padding any remaining slots with +fill_with+ unless it is +false+.
-
#
-
# %w(1 2 3 4 5 6 7 8 9 10).in_groups_of(3) {|group| p group}
-
# ["1", "2", "3"]
-
# ["4", "5", "6"]
-
# ["7", "8", "9"]
-
# ["10", nil, nil]
-
#
-
# %w(1 2 3 4 5).in_groups_of(2, ' ') {|group| p group}
-
# ["1", "2"]
-
# ["3", "4"]
-
# ["5", " "]
-
#
-
# %w(1 2 3 4 5).in_groups_of(2, false) {|group| p group}
-
# ["1", "2"]
-
# ["3", "4"]
-
# ["5"]
-
1
def in_groups_of(number, fill_with = nil)
-
if fill_with == false
-
collection = self
-
else
-
# size % number gives how many extra we have;
-
# subtracting from number gives how many to add;
-
# modulo number ensures we don't add group of just fill.
-
padding = (number - size % number) % number
-
collection = dup.concat(Array.new(padding, fill_with))
-
end
-
-
if block_given?
-
collection.each_slice(number) { |slice| yield(slice) }
-
else
-
collection.each_slice(number).to_a
-
end
-
end
-
-
# Splits or iterates over the array in +number+ of groups, padding any
-
# remaining slots with +fill_with+ unless it is +false+.
-
#
-
# %w(1 2 3 4 5 6 7 8 9 10).in_groups(3) {|group| p group}
-
# ["1", "2", "3", "4"]
-
# ["5", "6", "7", nil]
-
# ["8", "9", "10", nil]
-
#
-
# %w(1 2 3 4 5 6 7 8 9 10).in_groups(3, ' ') {|group| p group}
-
# ["1", "2", "3", "4"]
-
# ["5", "6", "7", " "]
-
# ["8", "9", "10", " "]
-
#
-
# %w(1 2 3 4 5 6 7).in_groups(3, false) {|group| p group}
-
# ["1", "2", "3"]
-
# ["4", "5"]
-
# ["6", "7"]
-
1
def in_groups(number, fill_with = nil)
-
# size.div number gives minor group size;
-
# size % number gives how many objects need extra accommodation;
-
# each group hold either division or division + 1 items.
-
division = size.div number
-
modulo = size % number
-
-
# create a new array avoiding dup
-
groups = []
-
start = 0
-
-
number.times do |index|
-
length = division + (modulo > 0 && modulo > index ? 1 : 0)
-
groups << last_group = slice(start, length)
-
last_group << fill_with if fill_with != false &&
-
modulo > 0 && length == division
-
start += length
-
end
-
-
if block_given?
-
groups.each { |g| yield(g) }
-
else
-
groups
-
end
-
end
-
-
# Divides the array into one or more subarrays based on a delimiting +value+
-
# or the result of an optional block.
-
#
-
# [1, 2, 3, 4, 5].split(3) # => [[1, 2], [4, 5]]
-
# (1..10).to_a.split { |i| i % 3 == 0 } # => [[1, 2], [4, 5], [7, 8], [10]]
-
1
def split(value = nil)
-
if block_given?
-
inject([[]]) do |results, element|
-
if yield(element)
-
results << []
-
else
-
results.last << element
-
end
-
-
results
-
end
-
else
-
results, arr = [[]], self.dup
-
until arr.empty?
-
if (idx = arr.index(value))
-
results.last.concat(arr.shift(idx))
-
arr.shift
-
results << []
-
else
-
results.last.concat(arr.shift(arr.size))
-
end
-
end
-
results
-
end
-
end
-
end
-
1
class Array
-
# The human way of thinking about adding stuff to the end of a list is with append.
-
1
alias_method :append, :<<
-
-
# The human way of thinking about adding stuff to the beginning of a list is with prepend.
-
1
alias_method :prepend, :unshift
-
end
-
1
class Array
-
# Wraps its argument in an array unless it is already an array (or array-like).
-
#
-
# Specifically:
-
#
-
# * If the argument is +nil+ an empty list is returned.
-
# * Otherwise, if the argument responds to +to_ary+ it is invoked, and its result returned.
-
# * Otherwise, returns an array with the argument as its single element.
-
#
-
# Array.wrap(nil) # => []
-
# Array.wrap([1, 2, 3]) # => [1, 2, 3]
-
# Array.wrap(0) # => [0]
-
#
-
# This method is similar in purpose to <tt>Kernel#Array</tt>, but there are some differences:
-
#
-
# * If the argument responds to +to_ary+ the method is invoked. <tt>Kernel#Array</tt>
-
# moves on to try +to_a+ if the returned value is +nil+, but <tt>Array.wrap</tt> returns
-
# +nil+ right away.
-
# * If the returned value from +to_ary+ is neither +nil+ nor an +Array+ object, <tt>Kernel#Array</tt>
-
# raises an exception, while <tt>Array.wrap</tt> does not, it just returns the value.
-
# * It does not call +to_a+ on the argument, but returns an empty array if argument is +nil+.
-
#
-
# The second point is easily explained with some enumerables:
-
#
-
# Array(foo: :bar) # => [[:foo, :bar]]
-
# Array.wrap(foo: :bar) # => [{:foo=>:bar}]
-
#
-
# There's also a related idiom that uses the splat operator:
-
#
-
# [*object]
-
#
-
# which returns <tt>[]</tt> for +nil+, but calls to <tt>Array(object)</tt> otherwise.
-
#
-
# The differences with <tt>Kernel#Array</tt> explained above
-
# apply to the rest of <tt>object</tt>s.
-
1
def self.wrap(object)
-
2
if object.nil?
-
[]
-
2
elsif object.respond_to?(:to_ary)
-
2
object.to_ary || [object]
-
else
-
[object]
-
end
-
end
-
end
-
1
require 'benchmark'
-
-
1
class << Benchmark
-
# Benchmark realtime in milliseconds.
-
#
-
# Benchmark.realtime { User.all }
-
# # => 8.0e-05
-
#
-
# Benchmark.ms { User.all }
-
# # => 0.074
-
1
def ms
-
1000 * realtime { yield }
-
end
-
end
-
1
require 'active_support/core_ext/big_decimal/conversions'
-
1
require 'bigdecimal'
-
1
require 'bigdecimal/util'
-
-
1
class BigDecimal
-
1
DEFAULT_STRING_FORMAT = 'F'
-
1
def to_formatted_s(*args)
-
if args[0].is_a?(Symbol)
-
super
-
else
-
format = args[0] || DEFAULT_STRING_FORMAT
-
_original_to_s(format)
-
end
-
end
-
1
alias_method :_original_to_s, :to_s
-
1
alias_method :to_s, :to_formatted_s
-
end
-
1
require 'active_support/core_ext/class/attribute'
-
1
require 'active_support/core_ext/class/delegating_attributes'
-
1
require 'active_support/core_ext/class/subclasses'
-
1
require 'active_support/core_ext/kernel/singleton_class'
-
1
require 'active_support/core_ext/module/remove_method'
-
1
require 'active_support/core_ext/array/extract_options'
-
-
1
class Class
-
# Declare a class-level attribute whose value is inheritable by subclasses.
-
# Subclasses can change their own value and it will not impact parent class.
-
#
-
# class Base
-
# class_attribute :setting
-
# end
-
#
-
# class Subclass < Base
-
# end
-
#
-
# Base.setting = true
-
# Subclass.setting # => true
-
# Subclass.setting = false
-
# Subclass.setting # => false
-
# Base.setting # => true
-
#
-
# In the above case as long as Subclass does not assign a value to setting
-
# by performing <tt>Subclass.setting = _something_ </tt>, <tt>Subclass.setting</tt>
-
# would read value assigned to parent class. Once Subclass assigns a value then
-
# the value assigned by Subclass would be returned.
-
#
-
# This matches normal Ruby method inheritance: think of writing an attribute
-
# on a subclass as overriding the reader method. However, you need to be aware
-
# when using +class_attribute+ with mutable structures as +Array+ or +Hash+.
-
# In such cases, you don't want to do changes in places but use setters:
-
#
-
# Base.setting = []
-
# Base.setting # => []
-
# Subclass.setting # => []
-
#
-
# # Appending in child changes both parent and child because it is the same object:
-
# Subclass.setting << :foo
-
# Base.setting # => [:foo]
-
# Subclass.setting # => [:foo]
-
#
-
# # Use setters to not propagate changes:
-
# Base.setting = []
-
# Subclass.setting += [:foo]
-
# Base.setting # => []
-
# Subclass.setting # => [:foo]
-
#
-
# For convenience, an instance predicate method is defined as well.
-
# To skip it, pass <tt>instance_predicate: false</tt>.
-
#
-
# Subclass.setting? # => false
-
#
-
# Instances may overwrite the class value in the same way:
-
#
-
# Base.setting = true
-
# object = Base.new
-
# object.setting # => true
-
# object.setting = false
-
# object.setting # => false
-
# Base.setting # => true
-
#
-
# To opt out of the instance reader method, pass <tt>instance_reader: false</tt>.
-
#
-
# object.setting # => NoMethodError
-
# object.setting? # => NoMethodError
-
#
-
# To opt out of the instance writer method, pass <tt>instance_writer: false</tt>.
-
#
-
# object.setting = false # => NoMethodError
-
#
-
# To opt out of both instance methods, pass <tt>instance_accessor: false</tt>.
-
1
def class_attribute(*attrs)
-
123
options = attrs.extract_options!
-
123
instance_reader = options.fetch(:instance_accessor, true) && options.fetch(:instance_reader, true)
-
123
instance_writer = options.fetch(:instance_accessor, true) && options.fetch(:instance_writer, true)
-
123
instance_predicate = options.fetch(:instance_predicate, true)
-
-
123
attrs.each do |name|
-
141
define_singleton_method(name) { nil }
-
138
define_singleton_method("#{name}?") { !!public_send(name) } if instance_predicate
-
-
138
ivar = "@#{name}"
-
-
138
define_singleton_method("#{name}=") do |val|
-
284
singleton_class.class_eval do
-
284
remove_possible_method(name)
-
592
define_method(name) { val }
-
end
-
-
284
if singleton_class?
-
class_eval do
-
remove_possible_method(name)
-
define_method(name) do
-
if instance_variable_defined? ivar
-
instance_variable_get ivar
-
else
-
singleton_class.send name
-
end
-
end
-
end
-
end
-
284
val
-
end
-
-
138
if instance_reader
-
127
remove_possible_method name
-
127
define_method(name) do
-
2
if instance_variable_defined?(ivar)
-
instance_variable_get ivar
-
else
-
2
self.class.public_send name
-
end
-
end
-
127
define_method("#{name}?") { !!public_send(name) } if instance_predicate
-
end
-
-
138
attr_writer name if instance_writer
-
end
-
end
-
-
1
private
-
-
1
unless respond_to?(:singleton_class?)
-
def singleton_class?
-
ancestors.first != self
-
end
-
end
-
end
-
1
require 'active_support/core_ext/kernel/singleton_class'
-
1
require 'active_support/core_ext/module/remove_method'
-
-
1
class Class
-
1
def superclass_delegating_accessor(name, options = {})
-
# Create private _name and _name= methods that can still be used if the public
-
# methods are overridden.
-
_superclass_delegating_accessor("_#{name}", options)
-
-
# Generate the public methods name, name=, and name?.
-
# These methods dispatch to the private _name, and _name= methods, making them
-
# overridable.
-
singleton_class.send(:define_method, name) { send("_#{name}") }
-
singleton_class.send(:define_method, "#{name}?") { !!send("_#{name}") }
-
singleton_class.send(:define_method, "#{name}=") { |value| send("_#{name}=", value) }
-
-
# If an instance_reader is needed, generate public instance methods name and name?.
-
if options[:instance_reader] != false
-
define_method(name) { send("_#{name}") }
-
define_method("#{name}?") { !!send("#{name}") }
-
end
-
end
-
-
1
private
-
# Take the object being set and store it in a method. This gives us automatic
-
# inheritance behavior, without having to store the object in an instance
-
# variable and look up the superclass chain manually.
-
1
def _stash_object_in_method(object, method, instance_reader = true)
-
singleton_class.remove_possible_method(method)
-
singleton_class.send(:define_method, method) { object }
-
remove_possible_method(method)
-
define_method(method) { object } if instance_reader
-
end
-
-
1
def _superclass_delegating_accessor(name, options = {})
-
singleton_class.send(:define_method, "#{name}=") do |value|
-
_stash_object_in_method(value, name, options[:instance_reader] != false)
-
end
-
send("#{name}=", nil)
-
end
-
end
-
1
require 'active_support/core_ext/module/anonymous'
-
1
require 'active_support/core_ext/module/reachable'
-
-
1
class Class
-
1
begin
-
1
ObjectSpace.each_object(Class.new) {}
-
-
1
def descendants # :nodoc:
-
descendants = []
-
ObjectSpace.each_object(singleton_class) do |k|
-
descendants.unshift k unless k == self
-
end
-
descendants
-
end
-
rescue StandardError # JRuby
-
def descendants # :nodoc:
-
descendants = []
-
ObjectSpace.each_object(Class) do |k|
-
descendants.unshift k if k < self
-
end
-
descendants.uniq!
-
descendants
-
end
-
end
-
-
# Returns an array with the direct children of +self+.
-
#
-
# Integer.subclasses # => [Fixnum, Bignum]
-
#
-
# class Foo; end
-
# class Bar < Foo; end
-
# class Baz < Bar; end
-
#
-
# Foo.subclasses # => [Bar]
-
1
def subclasses
-
subclasses, chain = [], descendants
-
chain.each do |k|
-
subclasses << k unless chain.any? { |c| c > k }
-
end
-
subclasses
-
end
-
end
-
1
require 'active_support/core_ext/date/acts_like'
-
1
require 'active_support/core_ext/date/calculations'
-
1
require 'active_support/core_ext/date/conversions'
-
1
require 'active_support/core_ext/date/zones'
-
-
1
require 'active_support/core_ext/object/acts_like'
-
-
1
class Date
-
# Duck-types as a Date-like class. See Object#acts_like?.
-
1
def acts_like_date?
-
true
-
end
-
end
-
1
require 'date'
-
1
require 'active_support/duration'
-
1
require 'active_support/core_ext/object/acts_like'
-
1
require 'active_support/core_ext/date/zones'
-
1
require 'active_support/core_ext/time/zones'
-
1
require 'active_support/core_ext/date_and_time/calculations'
-
-
1
class Date
-
1
include DateAndTime::Calculations
-
-
1
class << self
-
1
attr_accessor :beginning_of_week_default
-
-
# Returns the week start (e.g. :monday) for the current request, if this has been set (via Date.beginning_of_week=).
-
# If <tt>Date.beginning_of_week</tt> has not been set for the current request, returns the week start specified in <tt>config.beginning_of_week</tt>.
-
# If no config.beginning_of_week was specified, returns :monday.
-
1
def beginning_of_week
-
Thread.current[:beginning_of_week] || beginning_of_week_default || :monday
-
end
-
-
# Sets <tt>Date.beginning_of_week</tt> to a week start (e.g. :monday) for current request/thread.
-
#
-
# This method accepts any of the following day symbols:
-
# :monday, :tuesday, :wednesday, :thursday, :friday, :saturday, :sunday
-
1
def beginning_of_week=(week_start)
-
Thread.current[:beginning_of_week] = find_beginning_of_week!(week_start)
-
end
-
-
# Returns week start day symbol (e.g. :monday), or raises an ArgumentError for invalid day symbol.
-
1
def find_beginning_of_week!(week_start)
-
1
raise ArgumentError, "Invalid beginning of week: #{week_start}" unless ::Date::DAYS_INTO_WEEK.key?(week_start)
-
1
week_start
-
end
-
-
# Returns a new Date representing the date 1 day ago (i.e. yesterday's date).
-
1
def yesterday
-
::Date.current.yesterday
-
end
-
-
# Returns a new Date representing the date 1 day after today (i.e. tomorrow's date).
-
1
def tomorrow
-
::Date.current.tomorrow
-
end
-
-
# Returns Time.zone.today when <tt>Time.zone</tt> or <tt>config.time_zone</tt> are set, otherwise just returns Date.today.
-
1
def current
-
::Time.zone ? ::Time.zone.today : ::Date.today
-
end
-
end
-
-
# Converts Date to a Time (or DateTime if necessary) with the time portion set to the beginning of the day (0:00)
-
# and then subtracts the specified number of seconds.
-
1
def ago(seconds)
-
in_time_zone.since(-seconds)
-
end
-
-
# Converts Date to a Time (or DateTime if necessary) with the time portion set to the beginning of the day (0:00)
-
# and then adds the specified number of seconds
-
1
def since(seconds)
-
in_time_zone.since(seconds)
-
end
-
1
alias :in :since
-
-
# Converts Date to a Time (or DateTime if necessary) with the time portion set to the beginning of the day (0:00)
-
1
def beginning_of_day
-
in_time_zone
-
end
-
1
alias :midnight :beginning_of_day
-
1
alias :at_midnight :beginning_of_day
-
1
alias :at_beginning_of_day :beginning_of_day
-
-
# Converts Date to a Time (or DateTime if necessary) with the time portion set to the middle of the day (12:00)
-
1
def middle_of_day
-
in_time_zone.middle_of_day
-
end
-
1
alias :midday :middle_of_day
-
1
alias :noon :middle_of_day
-
1
alias :at_midday :middle_of_day
-
1
alias :at_noon :middle_of_day
-
1
alias :at_middle_of_day :middle_of_day
-
-
# Converts Date to a Time (or DateTime if necessary) with the time portion set to the end of the day (23:59:59)
-
1
def end_of_day
-
in_time_zone.end_of_day
-
end
-
1
alias :at_end_of_day :end_of_day
-
-
1
def plus_with_duration(other) #:nodoc:
-
if ActiveSupport::Duration === other
-
other.since(self)
-
else
-
plus_without_duration(other)
-
end
-
end
-
1
alias_method :plus_without_duration, :+
-
1
alias_method :+, :plus_with_duration
-
-
1
def minus_with_duration(other) #:nodoc:
-
if ActiveSupport::Duration === other
-
plus_with_duration(-other)
-
else
-
minus_without_duration(other)
-
end
-
end
-
1
alias_method :minus_without_duration, :-
-
1
alias_method :-, :minus_with_duration
-
-
# Provides precise Date calculations for years, months, and days. The +options+ parameter takes a hash with
-
# any of these keys: <tt>:years</tt>, <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>.
-
1
def advance(options)
-
options = options.dup
-
d = self
-
d = d >> options.delete(:years) * 12 if options[:years]
-
d = d >> options.delete(:months) if options[:months]
-
d = d + options.delete(:weeks) * 7 if options[:weeks]
-
d = d + options.delete(:days) if options[:days]
-
d
-
end
-
-
# Returns a new Date where one or more of the elements have been changed according to the +options+ parameter.
-
# The +options+ parameter is a hash with a combination of these keys: <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>.
-
#
-
# Date.new(2007, 5, 12).change(day: 1) # => Date.new(2007, 5, 1)
-
# Date.new(2007, 5, 12).change(year: 2005, month: 1) # => Date.new(2005, 1, 12)
-
1
def change(options)
-
::Date.new(
-
options.fetch(:year, year),
-
options.fetch(:month, month),
-
options.fetch(:day, day)
-
)
-
end
-
-
# Allow Date to be compared with Time by converting to DateTime and relying on the <=> from there.
-
1
def compare_with_coercion(other)
-
if other.is_a?(Time)
-
self.to_datetime <=> other
-
else
-
compare_without_coercion(other)
-
end
-
end
-
1
alias_method :compare_without_coercion, :<=>
-
1
alias_method :<=>, :compare_with_coercion
-
end
-
1
require 'date'
-
1
require 'active_support/inflector/methods'
-
1
require 'active_support/core_ext/date/zones'
-
1
require 'active_support/core_ext/module/remove_method'
-
-
1
class Date
-
1
DATE_FORMATS = {
-
:short => '%e %b',
-
:long => '%B %e, %Y',
-
:db => '%Y-%m-%d',
-
:number => '%Y%m%d',
-
:long_ordinal => lambda { |date|
-
day_format = ActiveSupport::Inflector.ordinalize(date.day)
-
date.strftime("%B #{day_format}, %Y") # => "April 25th, 2007"
-
},
-
:rfc822 => '%e %b %Y',
-
:iso8601 => lambda { |date| date.iso8601 }
-
}
-
-
# Ruby 1.9 has Date#to_time which converts to localtime only.
-
1
remove_method :to_time
-
-
# Ruby 1.9 has Date#xmlschema which converts to a string without the time
-
# component. This removal may generate an issue on FreeBSD, that's why we
-
# need to use remove_possible_method here
-
1
remove_possible_method :xmlschema
-
-
# Convert to a formatted string. See DATE_FORMATS for predefined formats.
-
#
-
# This method is aliased to <tt>to_s</tt>.
-
#
-
# date = Date.new(2007, 11, 10) # => Sat, 10 Nov 2007
-
#
-
# date.to_formatted_s(:db) # => "2007-11-10"
-
# date.to_s(:db) # => "2007-11-10"
-
#
-
# date.to_formatted_s(:short) # => "10 Nov"
-
# date.to_formatted_s(:long) # => "November 10, 2007"
-
# date.to_formatted_s(:long_ordinal) # => "November 10th, 2007"
-
# date.to_formatted_s(:rfc822) # => "10 Nov 2007"
-
# date.to_formatted_s(:iso8601) # => "2007-11-10"
-
#
-
# == Adding your own date formats to to_formatted_s
-
# You can add your own formats to the Date::DATE_FORMATS hash.
-
# Use the format name as the hash key and either a strftime string
-
# or Proc instance that takes a date argument as the value.
-
#
-
# # config/initializers/date_formats.rb
-
# Date::DATE_FORMATS[:month_and_year] = '%B %Y'
-
# Date::DATE_FORMATS[:short_ordinal] = ->(date) { date.strftime("%B #{date.day.ordinalize}") }
-
1
def to_formatted_s(format = :default)
-
if formatter = DATE_FORMATS[format]
-
if formatter.respond_to?(:call)
-
formatter.call(self).to_s
-
else
-
strftime(formatter)
-
end
-
else
-
to_default_s
-
end
-
end
-
1
alias_method :to_default_s, :to_s
-
1
alias_method :to_s, :to_formatted_s
-
-
# Overrides the default inspect method with a human readable one, e.g., "Mon, 21 Feb 2005"
-
1
def readable_inspect
-
strftime('%a, %d %b %Y')
-
end
-
1
alias_method :default_inspect, :inspect
-
1
alias_method :inspect, :readable_inspect
-
-
# Converts a Date instance to a Time, where the time is set to the beginning of the day.
-
# The timezone can be either :local or :utc (default :local).
-
#
-
# date = Date.new(2007, 11, 10) # => Sat, 10 Nov 2007
-
#
-
# date.to_time # => Sat Nov 10 00:00:00 0800 2007
-
# date.to_time(:local) # => Sat Nov 10 00:00:00 0800 2007
-
#
-
# date.to_time(:utc) # => Sat Nov 10 00:00:00 UTC 2007
-
1
def to_time(form = :local)
-
::Time.send(form, year, month, day)
-
end
-
-
1
def xmlschema
-
in_time_zone.xmlschema
-
end
-
end
-
1
require 'date'
-
1
require 'active_support/core_ext/date_and_time/zones'
-
-
1
class Date
-
1
include DateAndTime::Zones
-
end
-
1
module DateAndTime
-
1
module Calculations
-
1
DAYS_INTO_WEEK = {
-
:monday => 0,
-
:tuesday => 1,
-
:wednesday => 2,
-
:thursday => 3,
-
:friday => 4,
-
:saturday => 5,
-
:sunday => 6
-
}
-
-
# Returns a new date/time representing yesterday.
-
1
def yesterday
-
advance(:days => -1)
-
end
-
-
# Returns a new date/time representing tomorrow.
-
1
def tomorrow
-
advance(:days => 1)
-
end
-
-
# Returns true if the date/time is today.
-
1
def today?
-
to_date == ::Date.current
-
end
-
-
# Returns true if the date/time is in the past.
-
1
def past?
-
self < self.class.current
-
end
-
-
# Returns true if the date/time is in the future.
-
1
def future?
-
self > self.class.current
-
end
-
-
# Returns a new date/time the specified number of days ago.
-
1
def days_ago(days)
-
advance(:days => -days)
-
end
-
-
# Returns a new date/time the specified number of days in the future.
-
1
def days_since(days)
-
advance(:days => days)
-
end
-
-
# Returns a new date/time the specified number of weeks ago.
-
1
def weeks_ago(weeks)
-
advance(:weeks => -weeks)
-
end
-
-
# Returns a new date/time the specified number of weeks in the future.
-
1
def weeks_since(weeks)
-
advance(:weeks => weeks)
-
end
-
-
# Returns a new date/time the specified number of months ago.
-
1
def months_ago(months)
-
advance(:months => -months)
-
end
-
-
# Returns a new date/time the specified number of months in the future.
-
1
def months_since(months)
-
advance(:months => months)
-
end
-
-
# Returns a new date/time the specified number of years ago.
-
1
def years_ago(years)
-
advance(:years => -years)
-
end
-
-
# Returns a new date/time the specified number of years in the future.
-
1
def years_since(years)
-
advance(:years => years)
-
end
-
-
# Returns a new date/time at the start of the month.
-
# DateTime objects will have a time set to 0:00.
-
1
def beginning_of_month
-
first_hour(change(:day => 1))
-
end
-
1
alias :at_beginning_of_month :beginning_of_month
-
-
# Returns a new date/time at the start of the quarter.
-
# Example: 1st January, 1st July, 1st October.
-
# DateTime objects will have a time set to 0:00.
-
1
def beginning_of_quarter
-
first_quarter_month = [10, 7, 4, 1].detect { |m| m <= month }
-
beginning_of_month.change(:month => first_quarter_month)
-
end
-
1
alias :at_beginning_of_quarter :beginning_of_quarter
-
-
# Returns a new date/time at the end of the quarter.
-
# Example: 31st March, 30th June, 30th September.
-
# DateTime objects will have a time set to 23:59:59.
-
1
def end_of_quarter
-
last_quarter_month = [3, 6, 9, 12].detect { |m| m >= month }
-
beginning_of_month.change(:month => last_quarter_month).end_of_month
-
end
-
1
alias :at_end_of_quarter :end_of_quarter
-
-
# Return a new date/time at the beginning of the year.
-
# Example: 1st January.
-
# DateTime objects will have a time set to 0:00.
-
1
def beginning_of_year
-
change(:month => 1).beginning_of_month
-
end
-
1
alias :at_beginning_of_year :beginning_of_year
-
-
# Returns a new date/time representing the given day in the next week.
-
# The +given_day_in_next_week+ defaults to the beginning of the week
-
# which is determined by +Date.beginning_of_week+ or +config.beginning_of_week+
-
# when set. +DateTime+ objects have their time set to 0:00.
-
1
def next_week(given_day_in_next_week = Date.beginning_of_week)
-
first_hour(weeks_since(1).beginning_of_week.days_since(days_span(given_day_in_next_week)))
-
end
-
-
# Short-hand for months_since(1).
-
1
def next_month
-
months_since(1)
-
end
-
-
# Short-hand for months_since(3)
-
1
def next_quarter
-
months_since(3)
-
end
-
-
# Short-hand for years_since(1).
-
1
def next_year
-
years_since(1)
-
end
-
-
# Returns a new date/time representing the given day in the previous week.
-
# Week is assumed to start on +start_day+, default is
-
# +Date.beginning_of_week+ or +config.beginning_of_week+ when set.
-
# DateTime objects have their time set to 0:00.
-
1
def prev_week(start_day = Date.beginning_of_week)
-
first_hour(weeks_ago(1).beginning_of_week.days_since(days_span(start_day)))
-
end
-
1
alias_method :last_week, :prev_week
-
-
# Short-hand for months_ago(1).
-
1
def prev_month
-
months_ago(1)
-
end
-
1
alias_method :last_month, :prev_month
-
-
# Short-hand for months_ago(3).
-
1
def prev_quarter
-
months_ago(3)
-
end
-
1
alias_method :last_quarter, :prev_quarter
-
-
# Short-hand for years_ago(1).
-
1
def prev_year
-
years_ago(1)
-
end
-
1
alias_method :last_year, :prev_year
-
-
# Returns the number of days to the start of the week on the given day.
-
# Week is assumed to start on +start_day+, default is
-
# +Date.beginning_of_week+ or +config.beginning_of_week+ when set.
-
1
def days_to_week_start(start_day = Date.beginning_of_week)
-
start_day_number = DAYS_INTO_WEEK[start_day]
-
current_day_number = wday != 0 ? wday - 1 : 6
-
(current_day_number - start_day_number) % 7
-
end
-
-
# Returns a new date/time representing the start of this week on the given day.
-
# Week is assumed to start on +start_day+, default is
-
# +Date.beginning_of_week+ or +config.beginning_of_week+ when set.
-
# +DateTime+ objects have their time set to 0:00.
-
1
def beginning_of_week(start_day = Date.beginning_of_week)
-
result = days_ago(days_to_week_start(start_day))
-
acts_like?(:time) ? result.midnight : result
-
end
-
1
alias :at_beginning_of_week :beginning_of_week
-
-
# Returns Monday of this week assuming that week starts on Monday.
-
# +DateTime+ objects have their time set to 0:00.
-
1
def monday
-
beginning_of_week(:monday)
-
end
-
-
# Returns a new date/time representing the end of this week on the given day.
-
# Week is assumed to start on +start_day+, default is
-
# +Date.beginning_of_week+ or +config.beginning_of_week+ when set.
-
# DateTime objects have their time set to 23:59:59.
-
1
def end_of_week(start_day = Date.beginning_of_week)
-
last_hour(days_since(6 - days_to_week_start(start_day)))
-
end
-
1
alias :at_end_of_week :end_of_week
-
-
# Returns Sunday of this week assuming that week starts on Monday.
-
# +DateTime+ objects have their time set to 23:59:59.
-
1
def sunday
-
end_of_week(:monday)
-
end
-
-
# Returns a new date/time representing the end of the month.
-
# DateTime objects will have a time set to 23:59:59.
-
1
def end_of_month
-
last_day = ::Time.days_in_month(month, year)
-
last_hour(days_since(last_day - day))
-
end
-
1
alias :at_end_of_month :end_of_month
-
-
# Returns a new date/time representing the end of the year.
-
# DateTime objects will have a time set to 23:59:59.
-
1
def end_of_year
-
change(:month => 12).end_of_month
-
end
-
1
alias :at_end_of_year :end_of_year
-
-
# Returns a Range representing the whole week of the current date/time.
-
# Week starts on start_day, default is <tt>Date.week_start</tt> or <tt>config.week_start</tt> when set.
-
1
def all_week(start_day = Date.beginning_of_week)
-
beginning_of_week(start_day)..end_of_week(start_day)
-
end
-
-
# Returns a Range representing the whole month of the current date/time.
-
1
def all_month
-
beginning_of_month..end_of_month
-
end
-
-
# Returns a Range representing the whole quarter of the current date/time.
-
1
def all_quarter
-
beginning_of_quarter..end_of_quarter
-
end
-
-
# Returns a Range representing the whole year of the current date/time.
-
1
def all_year
-
beginning_of_year..end_of_year
-
end
-
-
1
private
-
-
1
def first_hour(date_or_time)
-
date_or_time.acts_like?(:time) ? date_or_time.beginning_of_day : date_or_time
-
end
-
-
1
def last_hour(date_or_time)
-
date_or_time.acts_like?(:time) ? date_or_time.end_of_day : date_or_time
-
end
-
-
1
def days_span(day)
-
(DAYS_INTO_WEEK[day] - DAYS_INTO_WEEK[Date.beginning_of_week]) % 7
-
end
-
end
-
end
-
1
module DateAndTime
-
1
module Zones
-
# Returns the simultaneous time in <tt>Time.zone</tt> if a zone is given or
-
# if Time.zone_default is set. Otherwise, it returns the current time.
-
#
-
# Time.zone = 'Hawaii' # => 'Hawaii'
-
# DateTime.utc(2000).in_time_zone # => Fri, 31 Dec 1999 14:00:00 HST -10:00
-
# Date.new(2000).in_time_zone # => Sat, 01 Jan 2000 00:00:00 HST -10:00
-
#
-
# This method is similar to Time#localtime, except that it uses <tt>Time.zone</tt> as the local zone
-
# instead of the operating system's time zone.
-
#
-
# You can also pass in a TimeZone instance or string that identifies a TimeZone as an argument,
-
# and the conversion will be based on that zone instead of <tt>Time.zone</tt>.
-
#
-
# Time.utc(2000).in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00
-
# DateTime.utc(2000).in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00
-
# Date.new(2000).in_time_zone('Alaska') # => Sat, 01 Jan 2000 00:00:00 AKST -09:00
-
1
def in_time_zone(zone = ::Time.zone)
-
time_zone = ::Time.find_zone! zone
-
time = acts_like?(:time) ? self : nil
-
-
if time_zone
-
time_with_zone(time, time_zone)
-
else
-
time || self.to_time
-
end
-
end
-
-
1
private
-
-
1
def time_with_zone(time, zone)
-
if time
-
ActiveSupport::TimeWithZone.new(time.utc? ? time : time.getutc, zone)
-
else
-
ActiveSupport::TimeWithZone.new(nil, zone, to_time(:utc))
-
end
-
end
-
end
-
end
-
-
1
require 'active_support/core_ext/date_time/acts_like'
-
1
require 'active_support/core_ext/date_time/calculations'
-
1
require 'active_support/core_ext/date_time/conversions'
-
1
require 'active_support/core_ext/date_time/zones'
-
1
require 'date'
-
1
require 'active_support/core_ext/object/acts_like'
-
-
1
class DateTime
-
# Duck-types as a Date-like class. See Object#acts_like?.
-
1
def acts_like_date?
-
true
-
end
-
-
# Duck-types as a Time-like class. See Object#acts_like?.
-
1
def acts_like_time?
-
true
-
end
-
end
-
1
require 'date'
-
-
1
class DateTime
-
1
class << self
-
# Returns <tt>Time.zone.now.to_datetime</tt> when <tt>Time.zone</tt> or
-
# <tt>config.time_zone</tt> are set, otherwise returns
-
# <tt>Time.now.to_datetime</tt>.
-
1
def current
-
::Time.zone ? ::Time.zone.now.to_datetime : ::Time.now.to_datetime
-
end
-
end
-
-
# Seconds since midnight: DateTime.now.seconds_since_midnight.
-
1
def seconds_since_midnight
-
sec + (min * 60) + (hour * 3600)
-
end
-
-
# Returns the number of seconds until 23:59:59.
-
#
-
# DateTime.new(2012, 8, 29, 0, 0, 0).seconds_until_end_of_day # => 86399
-
# DateTime.new(2012, 8, 29, 12, 34, 56).seconds_until_end_of_day # => 41103
-
# DateTime.new(2012, 8, 29, 23, 59, 59).seconds_until_end_of_day # => 0
-
1
def seconds_until_end_of_day
-
end_of_day.to_i - to_i
-
end
-
-
# Returns a new DateTime where one or more of the elements have been changed
-
# according to the +options+ parameter. The time options (<tt>:hour</tt>,
-
# <tt>:min</tt>, <tt>:sec</tt>) reset cascadingly, so if only the hour is
-
# passed, then minute and sec is set to 0. If the hour and minute is passed,
-
# then sec is set to 0. The +options+ parameter takes a hash with any of these
-
# keys: <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>, <tt>:hour</tt>,
-
# <tt>:min</tt>, <tt>:sec</tt>, <tt>:offset</tt>, <tt>:start</tt>.
-
#
-
# DateTime.new(2012, 8, 29, 22, 35, 0).change(day: 1) # => DateTime.new(2012, 8, 1, 22, 35, 0)
-
# DateTime.new(2012, 8, 29, 22, 35, 0).change(year: 1981, day: 1) # => DateTime.new(1981, 8, 1, 22, 35, 0)
-
# DateTime.new(2012, 8, 29, 22, 35, 0).change(year: 1981, hour: 0) # => DateTime.new(1981, 8, 29, 0, 0, 0)
-
1
def change(options)
-
::DateTime.civil(
-
options.fetch(:year, year),
-
options.fetch(:month, month),
-
options.fetch(:day, day),
-
options.fetch(:hour, hour),
-
options.fetch(:min, options[:hour] ? 0 : min),
-
options.fetch(:sec, (options[:hour] || options[:min]) ? 0 : sec + sec_fraction),
-
options.fetch(:offset, offset),
-
options.fetch(:start, start)
-
)
-
end
-
-
# Uses Date to provide precise Time calculations for years, months, and days.
-
# The +options+ parameter takes a hash with any of these keys: <tt>:years</tt>,
-
# <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>, <tt>:hours</tt>,
-
# <tt>:minutes</tt>, <tt>:seconds</tt>.
-
1
def advance(options)
-
d = to_date.advance(options)
-
datetime_advanced_by_date = change(:year => d.year, :month => d.month, :day => d.day)
-
seconds_to_advance = \
-
options.fetch(:seconds, 0) +
-
options.fetch(:minutes, 0) * 60 +
-
options.fetch(:hours, 0) * 3600
-
-
if seconds_to_advance.zero?
-
datetime_advanced_by_date
-
else
-
datetime_advanced_by_date.since seconds_to_advance
-
end
-
end
-
-
# Returns a new DateTime representing the time a number of seconds ago.
-
# Do not use this method in combination with x.months, use months_ago instead!
-
1
def ago(seconds)
-
since(-seconds)
-
end
-
-
# Returns a new DateTime representing the time a number of seconds since the
-
# instance time. Do not use this method in combination with x.months, use
-
# months_since instead!
-
1
def since(seconds)
-
self + Rational(seconds.round, 86400)
-
end
-
1
alias :in :since
-
-
# Returns a new DateTime representing the start of the day (0:00).
-
1
def beginning_of_day
-
change(:hour => 0)
-
end
-
1
alias :midnight :beginning_of_day
-
1
alias :at_midnight :beginning_of_day
-
1
alias :at_beginning_of_day :beginning_of_day
-
-
# Returns a new DateTime representing the middle of the day (12:00)
-
1
def middle_of_day
-
change(:hour => 12)
-
end
-
1
alias :midday :middle_of_day
-
1
alias :noon :middle_of_day
-
1
alias :at_midday :middle_of_day
-
1
alias :at_noon :middle_of_day
-
1
alias :at_middle_of_day :middle_of_day
-
-
# Returns a new DateTime representing the end of the day (23:59:59).
-
1
def end_of_day
-
change(:hour => 23, :min => 59, :sec => 59)
-
end
-
1
alias :at_end_of_day :end_of_day
-
-
# Returns a new DateTime representing the start of the hour (hh:00:00).
-
1
def beginning_of_hour
-
change(:min => 0)
-
end
-
1
alias :at_beginning_of_hour :beginning_of_hour
-
-
# Returns a new DateTime representing the end of the hour (hh:59:59).
-
1
def end_of_hour
-
change(:min => 59, :sec => 59)
-
end
-
1
alias :at_end_of_hour :end_of_hour
-
-
# Returns a new DateTime representing the start of the minute (hh:mm:00).
-
1
def beginning_of_minute
-
change(:sec => 0)
-
end
-
1
alias :at_beginning_of_minute :beginning_of_minute
-
-
# Returns a new DateTime representing the end of the minute (hh:mm:59).
-
1
def end_of_minute
-
change(:sec => 59)
-
end
-
1
alias :at_end_of_minute :end_of_minute
-
-
# Adjusts DateTime to UTC by adding its offset value; offset is set to 0.
-
#
-
# DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-6, 24)) # => Mon, 21 Feb 2005 10:11:12 -0600
-
# DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-6, 24)).utc # => Mon, 21 Feb 2005 16:11:12 +0000
-
1
def utc
-
new_offset(0)
-
end
-
1
alias_method :getutc, :utc
-
-
# Returns +true+ if <tt>offset == 0</tt>.
-
1
def utc?
-
offset == 0
-
end
-
-
# Returns the offset value in seconds.
-
1
def utc_offset
-
(offset * 86400).to_i
-
end
-
-
# Layers additional behavior on DateTime#<=> so that Time and
-
# ActiveSupport::TimeWithZone instances can be compared with a DateTime.
-
1
def <=>(other)
-
if other.respond_to? :to_datetime
-
super other.to_datetime
-
else
-
nil
-
end
-
end
-
-
end
-
1
require 'date'
-
1
require 'active_support/inflector/methods'
-
1
require 'active_support/core_ext/time/conversions'
-
1
require 'active_support/core_ext/date_time/calculations'
-
1
require 'active_support/values/time_zone'
-
-
1
class DateTime
-
# Convert to a formatted string. See Time::DATE_FORMATS for predefined formats.
-
#
-
# This method is aliased to <tt>to_s</tt>.
-
#
-
# === Examples
-
# datetime = DateTime.civil(2007, 12, 4, 0, 0, 0, 0) # => Tue, 04 Dec 2007 00:00:00 +0000
-
#
-
# datetime.to_formatted_s(:db) # => "2007-12-04 00:00:00"
-
# datetime.to_s(:db) # => "2007-12-04 00:00:00"
-
# datetime.to_s(:number) # => "20071204000000"
-
# datetime.to_formatted_s(:short) # => "04 Dec 00:00"
-
# datetime.to_formatted_s(:long) # => "December 04, 2007 00:00"
-
# datetime.to_formatted_s(:long_ordinal) # => "December 4th, 2007 00:00"
-
# datetime.to_formatted_s(:rfc822) # => "Tue, 04 Dec 2007 00:00:00 +0000"
-
# datetime.to_formatted_s(:iso8601) # => "2007-12-04T00:00:00+00:00"
-
#
-
# == Adding your own datetime formats to to_formatted_s
-
# DateTime formats are shared with Time. You can add your own to the
-
# Time::DATE_FORMATS hash. Use the format name as the hash key and
-
# either a strftime string or Proc instance that takes a time or
-
# datetime argument as the value.
-
#
-
# # config/initializers/time_formats.rb
-
# Time::DATE_FORMATS[:month_and_year] = '%B %Y'
-
# Time::DATE_FORMATS[:short_ordinal] = lambda { |time| time.strftime("%B #{time.day.ordinalize}") }
-
1
def to_formatted_s(format = :default)
-
if formatter = ::Time::DATE_FORMATS[format]
-
formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter)
-
else
-
to_default_s
-
end
-
end
-
1
alias_method :to_default_s, :to_s if instance_methods(false).include?(:to_s)
-
1
alias_method :to_s, :to_formatted_s
-
-
#
-
# datetime = DateTime.civil(2000, 1, 1, 0, 0, 0, Rational(-6, 24))
-
# datetime.formatted_offset # => "-06:00"
-
# datetime.formatted_offset(false) # => "-0600"
-
1
def formatted_offset(colon = true, alternate_utc_string = nil)
-
utc? && alternate_utc_string || ActiveSupport::TimeZone.seconds_to_utc_offset(utc_offset, colon)
-
end
-
-
# Overrides the default inspect method with a human readable one, e.g., "Mon, 21 Feb 2005 14:30:00 +0000".
-
1
def readable_inspect
-
to_s(:rfc822)
-
end
-
1
alias_method :default_inspect, :inspect
-
1
alias_method :inspect, :readable_inspect
-
-
# Returns DateTime with local offset for given year if format is local else
-
# offset is zero.
-
#
-
# DateTime.civil_from_format :local, 2012
-
# # => Sun, 01 Jan 2012 00:00:00 +0300
-
# DateTime.civil_from_format :local, 2012, 12, 17
-
# # => Mon, 17 Dec 2012 00:00:00 +0000
-
1
def self.civil_from_format(utc_or_local, year, month=1, day=1, hour=0, min=0, sec=0)
-
if utc_or_local.to_sym == :local
-
offset = ::Time.local(year, month, day).utc_offset.to_r / 86400
-
else
-
offset = 0
-
end
-
civil(year, month, day, hour, min, sec, offset)
-
end
-
-
# Converts +self+ to a floating-point number of seconds since the Unix epoch.
-
1
def to_f
-
seconds_since_unix_epoch.to_f
-
end
-
-
# Converts +self+ to an integer number of seconds since the Unix epoch.
-
1
def to_i
-
seconds_since_unix_epoch.to_i
-
end
-
-
# Returns the fraction of a second as microseconds
-
1
def usec
-
(sec_fraction * 1_000_000).to_i
-
end
-
-
# Returns the fraction of a second as nanoseconds
-
1
def nsec
-
(sec_fraction * 1_000_000_000).to_i
-
end
-
-
1
private
-
-
1
def offset_in_seconds
-
(offset * 86400).to_i
-
end
-
-
1
def seconds_since_unix_epoch
-
(jd - 2440588) * 86400 - offset_in_seconds + seconds_since_midnight
-
end
-
end
-
1
require 'date'
-
1
require 'active_support/core_ext/date_and_time/zones'
-
-
1
class DateTime
-
1
include DateAndTime::Zones
-
end
-
1
module Enumerable
-
# Calculates a sum from the elements.
-
#
-
# payments.sum { |p| p.price * p.tax_rate }
-
# payments.sum(&:price)
-
#
-
# The latter is a shortcut for:
-
#
-
# payments.inject(0) { |sum, p| sum + p.price }
-
#
-
# It can also calculate the sum without the use of a block.
-
#
-
# [5, 15, 10].sum # => 30
-
# ['foo', 'bar'].sum # => "foobar"
-
# [[1, 2], [3, 1, 5]].sum => [1, 2, 3, 1, 5]
-
#
-
# The default sum of an empty list is zero. You can override this default:
-
#
-
# [].sum(Payment.new(0)) { |i| i.amount } # => Payment.new(0)
-
1
def sum(identity = 0, &block)
-
if block_given?
-
map(&block).sum(identity)
-
else
-
inject { |sum, element| sum + element } || identity
-
end
-
end
-
-
# Convert an enumerable to a hash.
-
#
-
# people.index_by(&:login)
-
# => { "nextangle" => <Person ...>, "chade-" => <Person ...>, ...}
-
# people.index_by { |person| "#{person.first_name} #{person.last_name}" }
-
# => { "Chade- Fowlersburg-e" => <Person ...>, "David Heinemeier Hansson" => <Person ...>, ...}
-
1
def index_by
-
if block_given?
-
Hash[map { |elem| [yield(elem), elem] }]
-
else
-
to_enum(:index_by) { size if respond_to?(:size) }
-
end
-
end
-
-
# Returns +true+ if the enumerable has more than 1 element. Functionally
-
# equivalent to <tt>enum.to_a.size > 1</tt>. Can be called with a block too,
-
# much like any?, so <tt>people.many? { |p| p.age > 26 }</tt> returns +true+
-
# if more than one person is over 26.
-
1
def many?
-
cnt = 0
-
if block_given?
-
any? do |element|
-
cnt += 1 if yield element
-
cnt > 1
-
end
-
else
-
any? { (cnt += 1) > 1 }
-
end
-
end
-
-
# The negative of the <tt>Enumerable#include?</tt>. Returns +true+ if the
-
# collection does not include the object.
-
1
def exclude?(object)
-
!include?(object)
-
end
-
end
-
-
1
class Range #:nodoc:
-
# Optimize range sum to use arithmetic progression if a block is not given and
-
# we have a range of numeric values.
-
1
def sum(identity = 0)
-
if block_given? || !(first.is_a?(Integer) && last.is_a?(Integer))
-
super
-
else
-
actual_last = exclude_end? ? (last - 1) : last
-
if actual_last >= first
-
(actual_last - first + 1) * (actual_last + first) / 2
-
else
-
identity
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/file/atomic'
-
1
require 'fileutils'
-
-
1
class File
-
# Write to a file atomically. Useful for situations where you don't
-
# want other processes or threads to see half-written files.
-
#
-
# File.atomic_write('important.file') do |file|
-
# file.write('hello')
-
# end
-
#
-
# If your temp directory is not on the same filesystem as the file you're
-
# trying to write, you can provide a different temporary directory.
-
#
-
# File.atomic_write('/data/something.important', '/data/tmp') do |file|
-
# file.write('hello')
-
# end
-
1
def self.atomic_write(file_name, temp_dir = Dir.tmpdir)
-
require 'tempfile' unless defined?(Tempfile)
-
require 'fileutils' unless defined?(FileUtils)
-
-
temp_file = Tempfile.new(basename(file_name), temp_dir)
-
temp_file.binmode
-
yield temp_file
-
temp_file.close
-
-
if File.exist?(file_name)
-
# Get original file permissions
-
old_stat = stat(file_name)
-
else
-
# If not possible, probe which are the default permissions in the
-
# destination directory.
-
old_stat = probe_stat_in(dirname(file_name))
-
end
-
-
# Overwrite original file with temp file
-
FileUtils.mv(temp_file.path, file_name)
-
-
# Set correct permissions on new file
-
begin
-
chown(old_stat.uid, old_stat.gid, file_name)
-
# This operation will affect filesystem ACL's
-
chmod(old_stat.mode, file_name)
-
rescue Errno::EPERM
-
# Changing file ownership failed, moving on.
-
end
-
end
-
-
# Private utility method.
-
1
def self.probe_stat_in(dir) #:nodoc:
-
basename = [
-
'.permissions_check',
-
Thread.current.object_id,
-
Process.pid,
-
rand(1000000)
-
].join('.')
-
-
file_name = join(dir, basename)
-
FileUtils.touch(file_name)
-
stat(file_name)
-
ensure
-
FileUtils.rm_f(file_name) if file_name
-
end
-
end
-
1
require 'active_support/core_ext/hash/compact'
-
1
require 'active_support/core_ext/hash/conversions'
-
1
require 'active_support/core_ext/hash/deep_merge'
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/hash/indifferent_access'
-
1
require 'active_support/core_ext/hash/keys'
-
1
require 'active_support/core_ext/hash/reverse_merge'
-
1
require 'active_support/core_ext/hash/slice'
-
1
class Hash
-
# Returns a hash with non +nil+ values.
-
#
-
# hash = { a: true, b: false, c: nil}
-
# hash.compact # => { a: true, b: false}
-
# hash # => { a: true, b: false, c: nil}
-
# { c: nil }.compact # => {}
-
1
def compact
-
self.select { |_, value| !value.nil? }
-
end
-
-
# Replaces current hash with non +nil+ values.
-
#
-
# hash = { a: true, b: false, c: nil}
-
# hash.compact! # => { a: true, b: false}
-
# hash # => { a: true, b: false}
-
1
def compact!
-
self.reject! { |_, value| value.nil? }
-
end
-
end
-
1
require 'active_support/xml_mini'
-
1
require 'active_support/time'
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'active_support/core_ext/object/to_param'
-
1
require 'active_support/core_ext/object/to_query'
-
1
require 'active_support/core_ext/array/wrap'
-
1
require 'active_support/core_ext/hash/reverse_merge'
-
1
require 'active_support/core_ext/string/inflections'
-
-
1
class Hash
-
# Returns a string containing an XML representation of its receiver:
-
#
-
# { foo: 1, bar: 2 }.to_xml
-
# # =>
-
# # <?xml version="1.0" encoding="UTF-8"?>
-
# # <hash>
-
# # <foo type="integer">1</foo>
-
# # <bar type="integer">2</bar>
-
# # </hash>
-
#
-
# To do so, the method loops over the pairs and builds nodes that depend on
-
# the _values_. Given a pair +key+, +value+:
-
#
-
# * If +value+ is a hash there's a recursive call with +key+ as <tt>:root</tt>.
-
#
-
# * If +value+ is an array there's a recursive call with +key+ as <tt>:root</tt>,
-
# and +key+ singularized as <tt>:children</tt>.
-
#
-
# * If +value+ is a callable object it must expect one or two arguments. Depending
-
# on the arity, the callable is invoked with the +options+ hash as first argument
-
# with +key+ as <tt>:root</tt>, and +key+ singularized as second argument. The
-
# callable can add nodes by using <tt>options[:builder]</tt>.
-
#
-
# 'foo'.to_xml(lambda { |options, key| options[:builder].b(key) })
-
# # => "<b>foo</b>"
-
#
-
# * If +value+ responds to +to_xml+ the method is invoked with +key+ as <tt>:root</tt>.
-
#
-
# class Foo
-
# def to_xml(options)
-
# options[:builder].bar 'fooing!'
-
# end
-
# end
-
#
-
# { foo: Foo.new }.to_xml(skip_instruct: true)
-
# # =>
-
# # <hash>
-
# # <bar>fooing!</bar>
-
# # </hash>
-
#
-
# * Otherwise, a node with +key+ as tag is created with a string representation of
-
# +value+ as text node. If +value+ is +nil+ an attribute "nil" set to "true" is added.
-
# Unless the option <tt>:skip_types</tt> exists and is true, an attribute "type" is
-
# added as well according to the following mapping:
-
#
-
# XML_TYPE_NAMES = {
-
# "Symbol" => "symbol",
-
# "Fixnum" => "integer",
-
# "Bignum" => "integer",
-
# "BigDecimal" => "decimal",
-
# "Float" => "float",
-
# "TrueClass" => "boolean",
-
# "FalseClass" => "boolean",
-
# "Date" => "date",
-
# "DateTime" => "dateTime",
-
# "Time" => "dateTime"
-
# }
-
#
-
# By default the root node is "hash", but that's configurable via the <tt>:root</tt> option.
-
#
-
# The default XML builder is a fresh instance of <tt>Builder::XmlMarkup</tt>. You can
-
# configure your own builder with the <tt>:builder</tt> option. The method also accepts
-
# options like <tt>:dasherize</tt> and friends, they are forwarded to the builder.
-
1
def to_xml(options = {})
-
require 'active_support/builder' unless defined?(Builder)
-
-
options = options.dup
-
options[:indent] ||= 2
-
options[:root] ||= 'hash'
-
options[:builder] ||= Builder::XmlMarkup.new(indent: options[:indent])
-
-
builder = options[:builder]
-
builder.instruct! unless options.delete(:skip_instruct)
-
-
root = ActiveSupport::XmlMini.rename_key(options[:root].to_s, options)
-
-
builder.tag!(root) do
-
each { |key, value| ActiveSupport::XmlMini.to_tag(key, value, options) }
-
yield builder if block_given?
-
end
-
end
-
-
1
class << self
-
# Returns a Hash containing a collection of pairs when the key is the node name and the value is
-
# its content
-
#
-
# xml = <<-XML
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <hash>
-
# <foo type="integer">1</foo>
-
# <bar type="integer">2</bar>
-
# </hash>
-
# XML
-
#
-
# hash = Hash.from_xml(xml)
-
# # => {"hash"=>{"foo"=>1, "bar"=>2}}
-
#
-
# DisallowedType is raised if the XML contains attributes with <tt>type="yaml"</tt> or
-
# <tt>type="symbol"</tt>. Use <tt>Hash.from_trusted_xml</tt> to parse this XML.
-
1
def from_xml(xml, disallowed_types = nil)
-
ActiveSupport::XMLConverter.new(xml, disallowed_types).to_h
-
end
-
-
# Builds a Hash from XML just like <tt>Hash.from_xml</tt>, but also allows Symbol and YAML.
-
1
def from_trusted_xml(xml)
-
from_xml xml, []
-
end
-
end
-
end
-
-
1
module ActiveSupport
-
1
class XMLConverter # :nodoc:
-
1
class DisallowedType < StandardError
-
1
def initialize(type)
-
super "Disallowed type attribute: #{type.inspect}"
-
end
-
end
-
-
1
DISALLOWED_TYPES = %w(symbol yaml)
-
-
1
def initialize(xml, disallowed_types = nil)
-
@xml = normalize_keys(XmlMini.parse(xml))
-
@disallowed_types = disallowed_types || DISALLOWED_TYPES
-
end
-
-
1
def to_h
-
deep_to_h(@xml)
-
end
-
-
1
private
-
1
def normalize_keys(params)
-
case params
-
when Hash
-
Hash[params.map { |k,v| [k.to_s.tr('-', '_'), normalize_keys(v)] } ]
-
when Array
-
params.map { |v| normalize_keys(v) }
-
else
-
params
-
end
-
end
-
-
1
def deep_to_h(value)
-
case value
-
when Hash
-
process_hash(value)
-
when Array
-
process_array(value)
-
when String
-
value
-
else
-
raise "can't typecast #{value.class.name} - #{value.inspect}"
-
end
-
end
-
-
1
def process_hash(value)
-
if value.include?('type') && !value['type'].is_a?(Hash) && @disallowed_types.include?(value['type'])
-
raise DisallowedType, value['type']
-
end
-
-
if become_array?(value)
-
_, entries = Array.wrap(value.detect { |k,v| not v.is_a?(String) })
-
if entries.nil? || value['__content__'].try(:empty?)
-
[]
-
else
-
case entries
-
when Array
-
entries.collect { |v| deep_to_h(v) }
-
when Hash
-
[deep_to_h(entries)]
-
else
-
raise "can't typecast #{entries.inspect}"
-
end
-
end
-
elsif become_content?(value)
-
process_content(value)
-
-
elsif become_empty_string?(value)
-
''
-
elsif become_hash?(value)
-
xml_value = Hash[value.map { |k,v| [k, deep_to_h(v)] }]
-
-
# Turn { files: { file: #<StringIO> } } into { files: #<StringIO> } so it is compatible with
-
# how multipart uploaded files from HTML appear
-
xml_value['file'].is_a?(StringIO) ? xml_value['file'] : xml_value
-
end
-
end
-
-
1
def become_content?(value)
-
value['type'] == 'file' || (value['__content__'] && (value.keys.size == 1 || value['__content__'].present?))
-
end
-
-
1
def become_array?(value)
-
value['type'] == 'array'
-
end
-
-
1
def become_empty_string?(value)
-
# { "string" => true }
-
# No tests fail when the second term is removed.
-
value['type'] == 'string' && value['nil'] != 'true'
-
end
-
-
1
def become_hash?(value)
-
!nothing?(value) && !garbage?(value)
-
end
-
-
1
def nothing?(value)
-
# blank or nil parsed values are represented by nil
-
value.blank? || value['nil'] == 'true'
-
end
-
-
1
def garbage?(value)
-
# If the type is the only element which makes it then
-
# this still makes the value nil, except if type is
-
# a XML node(where type['value'] is a Hash)
-
value['type'] && !value['type'].is_a?(::Hash) && value.size == 1
-
end
-
-
1
def process_content(value)
-
content = value['__content__']
-
if parser = ActiveSupport::XmlMini::PARSING[value['type']]
-
parser.arity == 1 ? parser.call(content) : parser.call(content, value)
-
else
-
content
-
end
-
end
-
-
1
def process_array(value)
-
value.map! { |i| deep_to_h(i) }
-
value.length > 1 ? value : value.first
-
end
-
-
end
-
end
-
-
1
class Hash
-
# Returns a new hash with +self+ and +other_hash+ merged recursively.
-
#
-
# h1 = { x: { y: [4, 5, 6] }, z: [7, 8, 9] }
-
# h2 = { x: { y: [7, 8, 9] }, z: 'xyz' }
-
#
-
# h1.deep_merge(h2) # => {x: {y: [7, 8, 9]}, z: "xyz"}
-
# h2.deep_merge(h1) # => {x: {y: [4, 5, 6]}, z: [7, 8, 9]}
-
# h1.deep_merge(h2) { |key, old, new| Array.wrap(old) + Array.wrap(new) }
-
# # => {:x=>{:y=>[4, 5, 6, 7, 8, 9]}, :z=>[7, 8, 9, "xyz"]}
-
1
def deep_merge(other_hash, &block)
-
9
dup.deep_merge!(other_hash, &block)
-
end
-
-
# Same as +deep_merge+, but modifies +self+.
-
1
def deep_merge!(other_hash, &block)
-
9
other_hash.each_pair do |k,v|
-
18
tv = self[k]
-
18
if tv.is_a?(Hash) && v.is_a?(Hash)
-
self[k] = tv.deep_merge(v, &block)
-
else
-
18
self[k] = block && tv ? block.call(k, tv, v) : v
-
end
-
end
-
9
self
-
end
-
end
-
1
class Hash
-
# Returns a hash that includes everything but the given keys. This is useful for
-
# limiting a set of parameters to everything but a few known toggles:
-
#
-
# @person.update(params[:person].except(:admin))
-
1
def except(*keys)
-
314
dup.except!(*keys)
-
end
-
-
# Replaces the hash without the given keys.
-
1
def except!(*keys)
-
1427
keys.each { |key| delete(key) }
-
314
self
-
end
-
end
-
1
require 'active_support/hash_with_indifferent_access'
-
-
1
class Hash
-
-
# Returns an <tt>ActiveSupport::HashWithIndifferentAccess</tt> out of its receiver:
-
#
-
# { a: 1 }.with_indifferent_access['a'] # => 1
-
1
def with_indifferent_access
-
ActiveSupport::HashWithIndifferentAccess.new_from_hash_copying_default(self)
-
end
-
-
# Called when object is nested under an object that receives
-
# #with_indifferent_access. This method will be called on the current object
-
# by the enclosing object and is aliased to #with_indifferent_access by
-
# default. Subclasses of Hash may overwrite this method to return +self+ if
-
# converting to an <tt>ActiveSupport::HashWithIndifferentAccess</tt> would not be
-
# desirable.
-
#
-
# b = { b: 1 }
-
# { a: b }.with_indifferent_access['a'] # calls b.nested_under_indifferent_access
-
# # => {"b"=>32}
-
1
alias nested_under_indifferent_access with_indifferent_access
-
end
-
1
class Hash
-
# Returns a new hash with all keys converted using the block operation.
-
#
-
# hash = { name: 'Rob', age: '28' }
-
#
-
# hash.transform_keys{ |key| key.to_s.upcase }
-
# # => {"NAME"=>"Rob", "AGE"=>"28"}
-
1
def transform_keys
-
14
result = {}
-
14
each_key do |key|
-
21
result[yield(key)] = self[key]
-
end
-
14
result
-
end
-
-
# Destructively convert all keys using the block operations.
-
# Same as transform_keys but modifies +self+.
-
1
def transform_keys!
-
keys.each do |key|
-
self[yield(key)] = delete(key)
-
end
-
self
-
end
-
-
# Returns a new hash with all keys converted to strings.
-
#
-
# hash = { name: 'Rob', age: '28' }
-
#
-
# hash.stringify_keys
-
# # => { "name" => "Rob", "age" => "28" }
-
1
def stringify_keys
-
transform_keys{ |key| key.to_s }
-
end
-
-
# Destructively convert all keys to strings. Same as
-
# +stringify_keys+, but modifies +self+.
-
1
def stringify_keys!
-
transform_keys!{ |key| key.to_s }
-
end
-
-
# Returns a new hash with all keys converted to symbols, as long as
-
# they respond to +to_sym+.
-
#
-
# hash = { 'name' => 'Rob', 'age' => '28' }
-
#
-
# hash.symbolize_keys
-
# # => { name: "Rob", age: "28" }
-
1
def symbolize_keys
-
35
transform_keys{ |key| key.to_sym rescue key }
-
end
-
1
alias_method :to_options, :symbolize_keys
-
-
# Destructively convert all keys to symbols, as long as they respond
-
# to +to_sym+. Same as +symbolize_keys+, but modifies +self+.
-
1
def symbolize_keys!
-
transform_keys!{ |key| key.to_sym rescue key }
-
end
-
1
alias_method :to_options!, :symbolize_keys!
-
-
# Validate all keys in a hash match <tt>*valid_keys</tt>, raising ArgumentError
-
# on a mismatch. Note that keys are NOT treated indifferently, meaning if you
-
# use strings for keys but assert symbols as keys, this will fail.
-
#
-
# { name: 'Rob', years: '28' }.assert_valid_keys(:name, :age) # => raises "ArgumentError: Unknown key: :years. Valid keys are: :name, :age"
-
# { name: 'Rob', age: '28' }.assert_valid_keys('name', 'age') # => raises "ArgumentError: Unknown key: :name. Valid keys are: 'name', 'age'"
-
# { name: 'Rob', age: '28' }.assert_valid_keys(:name, :age) # => passes, raises nothing
-
1
def assert_valid_keys(*valid_keys)
-
23
valid_keys.flatten!
-
23
each_key do |k|
-
38
unless valid_keys.include?(k)
-
raise ArgumentError.new("Unknown key: #{k.inspect}. Valid keys are: #{valid_keys.map(&:inspect).join(', ')}")
-
end
-
end
-
end
-
-
# Returns a new hash with all keys converted by the block operation.
-
# This includes the keys from the root hash and from all
-
# nested hashes.
-
#
-
# hash = { person: { name: 'Rob', age: '28' } }
-
#
-
# hash.deep_transform_keys{ |key| key.to_s.upcase }
-
# # => {"PERSON"=>{"NAME"=>"Rob", "AGE"=>"28"}}
-
1
def deep_transform_keys(&block)
-
result = {}
-
each do |key, value|
-
result[yield(key)] = value.is_a?(Hash) ? value.deep_transform_keys(&block) : value
-
end
-
result
-
end
-
-
# Destructively convert all keys by using the block operation.
-
# This includes the keys from the root hash and from all
-
# nested hashes.
-
1
def deep_transform_keys!(&block)
-
keys.each do |key|
-
value = delete(key)
-
self[yield(key)] = value.is_a?(Hash) ? value.deep_transform_keys!(&block) : value
-
end
-
self
-
end
-
-
# Returns a new hash with all keys converted to strings.
-
# This includes the keys from the root hash and from all
-
# nested hashes.
-
#
-
# hash = { person: { name: 'Rob', age: '28' } }
-
#
-
# hash.deep_stringify_keys
-
# # => {"person"=>{"name"=>"Rob", "age"=>"28"}}
-
1
def deep_stringify_keys
-
deep_transform_keys{ |key| key.to_s }
-
end
-
-
# Destructively convert all keys to strings.
-
# This includes the keys from the root hash and from all
-
# nested hashes.
-
1
def deep_stringify_keys!
-
deep_transform_keys!{ |key| key.to_s }
-
end
-
-
# Returns a new hash with all keys converted to symbols, as long as
-
# they respond to +to_sym+. This includes the keys from the root hash
-
# and from all nested hashes.
-
#
-
# hash = { 'person' => { 'name' => 'Rob', 'age' => '28' } }
-
#
-
# hash.deep_symbolize_keys
-
# # => {:person=>{:name=>"Rob", :age=>"28"}}
-
1
def deep_symbolize_keys
-
deep_transform_keys{ |key| key.to_sym rescue key }
-
end
-
-
# Destructively convert all keys to symbols, as long as they respond
-
# to +to_sym+. This includes the keys from the root hash and from all
-
# nested hashes.
-
1
def deep_symbolize_keys!
-
deep_transform_keys!{ |key| key.to_sym rescue key }
-
end
-
end
-
1
class Hash
-
# Merges the caller into +other_hash+. For example,
-
#
-
# options = options.reverse_merge(size: 25, velocity: 10)
-
#
-
# is equivalent to
-
#
-
# options = { size: 25, velocity: 10 }.merge(options)
-
#
-
# This is particularly useful for initializing an options hash
-
# with default values.
-
1
def reverse_merge(other_hash)
-
other_hash.merge(self)
-
end
-
-
# Destructive +reverse_merge+.
-
1
def reverse_merge!(other_hash)
-
# right wins if there is no left
-
118
merge!( other_hash ){|key,left,right| left }
-
end
-
1
alias_method :reverse_update, :reverse_merge!
-
end
-
1
class Hash
-
# Slice a hash to include only the given keys. This is useful for
-
# limiting an options hash to valid keys before passing to a method:
-
#
-
# def search(criteria = {})
-
# criteria.assert_valid_keys(:mass, :velocity, :time)
-
# end
-
#
-
# search(options.slice(:mass, :velocity, :time))
-
#
-
# If you have an array of keys you want to limit to, you should splat them:
-
#
-
# valid_keys = [:mass, :velocity, :time]
-
# search(options.slice(*valid_keys))
-
1
def slice(*keys)
-
30
keys.map! { |key| convert_key(key) } if respond_to?(:convert_key, true)
-
132
keys.each_with_object(self.class.new) { |k, hash| hash[k] = self[k] if has_key?(k) }
-
end
-
-
# Replaces the hash with only the given keys.
-
# Returns a hash containing the removed key/value pairs.
-
#
-
# { a: 1, b: 2, c: 3, d: 4 }.slice!(:a, :b)
-
# # => {:c=>3, :d=>4}
-
1
def slice!(*keys)
-
13
keys.map! { |key| convert_key(key) } if respond_to?(:convert_key, true)
-
13
omit = slice(*self.keys - keys)
-
13
hash = slice(*keys)
-
13
hash.default = default
-
13
hash.default_proc = default_proc if default_proc
-
13
replace(hash)
-
13
omit
-
end
-
-
# Removes and returns the key/value pairs matching the given keys.
-
#
-
# { a: 1, b: 2, c: 3, d: 4 }.extract!(:a, :b) # => {:a=>1, :b=>2}
-
# { a: 1, b: 2 }.extract!(:a, :x) # => {:a=>1}
-
1
def extract!(*keys)
-
keys.each_with_object(self.class.new) { |key, result| result[key] = delete(key) if has_key?(key) }
-
end
-
end
-
1
require 'active_support/core_ext/integer/multiple'
-
1
require 'active_support/core_ext/integer/inflections'
-
1
require 'active_support/core_ext/integer/time'
-
1
require 'active_support/inflector'
-
-
1
class Integer
-
# Ordinalize turns a number into an ordinal string used to denote the
-
# position in an ordered sequence such as 1st, 2nd, 3rd, 4th.
-
#
-
# 1.ordinalize # => "1st"
-
# 2.ordinalize # => "2nd"
-
# 1002.ordinalize # => "1002nd"
-
# 1003.ordinalize # => "1003rd"
-
# -11.ordinalize # => "-11th"
-
# -1001.ordinalize # => "-1001st"
-
1
def ordinalize
-
ActiveSupport::Inflector.ordinalize(self)
-
end
-
-
# Ordinal returns the suffix used to denote the position
-
# in an ordered sequence such as 1st, 2nd, 3rd, 4th.
-
#
-
# 1.ordinal # => "st"
-
# 2.ordinal # => "nd"
-
# 1002.ordinal # => "nd"
-
# 1003.ordinal # => "rd"
-
# -11.ordinal # => "th"
-
# -1001.ordinal # => "st"
-
1
def ordinal
-
ActiveSupport::Inflector.ordinal(self)
-
end
-
end
-
1
class Integer
-
# Check whether the integer is evenly divisible by the argument.
-
#
-
# 0.multiple_of?(0) # => true
-
# 6.multiple_of?(5) # => false
-
# 10.multiple_of?(2) # => true
-
1
def multiple_of?(number)
-
number != 0 ? self % number == 0 : zero?
-
end
-
end
-
1
require 'active_support/duration'
-
1
require 'active_support/core_ext/numeric/time'
-
-
1
class Integer
-
# Enables the use of time calculations and declarations, like <tt>45.minutes +
-
# 2.hours + 4.years</tt>.
-
#
-
# These methods use Time#advance for precise date calculations when using
-
# <tt>from_now</tt>, +ago+, etc. as well as adding or subtracting their
-
# results from a Time object.
-
#
-
# # equivalent to Time.now.advance(months: 1)
-
# 1.month.from_now
-
#
-
# # equivalent to Time.now.advance(years: 2)
-
# 2.years.from_now
-
#
-
# # equivalent to Time.now.advance(months: 4, years: 5)
-
# (4.months + 5.years).from_now
-
#
-
# While these methods provide precise calculation when used as in the examples
-
# above, care should be taken to note that this is not true if the result of
-
# +months+, +years+, etc is converted before use:
-
#
-
# # equivalent to 30.days.to_i.from_now
-
# 1.month.to_i.from_now
-
#
-
# # equivalent to 365.25.days.to_f.from_now
-
# 1.year.to_f.from_now
-
#
-
# In such cases, Ruby's core
-
# Date[http://ruby-doc.org/stdlib/libdoc/date/rdoc/Date.html] and
-
# Time[http://ruby-doc.org/stdlib/libdoc/time/rdoc/Time.html] should be used for precision
-
# date and time arithmetic.
-
1
def months
-
ActiveSupport::Duration.new(self * 30.days, [[:months, self]])
-
end
-
1
alias :month :months
-
-
1
def years
-
ActiveSupport::Duration.new(self * 365.25.days, [[:years, self]])
-
end
-
1
alias :year :years
-
end
-
1
require 'active_support/core_ext/kernel/reporting'
-
1
require 'active_support/core_ext/kernel/agnostics'
-
1
require 'active_support/core_ext/kernel/debugger'
-
1
require 'active_support/core_ext/kernel/singleton_class'
-
1
class Object
-
# Makes backticks behave (somewhat more) similarly on all platforms.
-
# On win32 `nonexistent_command` raises Errno::ENOENT; on Unix, the
-
# spawned shell prints a message to stderr and sets $?. We emulate
-
# Unix on the former but not the latter.
-
1
def `(command) #:nodoc:
-
super
-
rescue Errno::ENOENT => e
-
STDERR.puts "#$0: #{e}"
-
end
-
end
-
1
module Kernel
-
1
unless respond_to?(:debugger)
-
# Starts a debugging session if the +debugger+ gem has been loaded (call rails server --debugger to do load it).
-
1
def debugger
-
message = "\n***** Debugger requested, but was not available (ensure the debugger gem is listed in Gemfile/installed as gem): Start server with --debugger to enable *****\n"
-
defined?(Rails) ? Rails.logger.info(message) : $stderr.puts(message)
-
end
-
1
alias breakpoint debugger unless respond_to?(:breakpoint)
-
end
-
end
-
1
module Kernel
-
# class_eval on an object acts like singleton_class.class_eval.
-
1
def class_eval(*args, &block)
-
singleton_class.class_eval(*args, &block)
-
end
-
end
-
1
class LoadError
-
1
REGEXPS = [
-
/^no such file to load -- (.+)$/i,
-
/^Missing \w+ (?:file\s*)?([^\s]+.rb)$/i,
-
/^Missing API definition file in (.+)$/i,
-
/^cannot load such file -- (.+)$/i,
-
]
-
-
1
unless method_defined?(:path)
-
def path
-
@path ||= begin
-
REGEXPS.find do |regex|
-
message =~ regex
-
end
-
$1
-
end
-
end
-
end
-
-
1
def is_missing?(location)
-
1
location.sub(/\.rb$/, '') == path.sub(/\.rb$/, '')
-
end
-
end
-
-
1
MissingSourceFile = LoadError
-
1
require 'active_support/core_ext/module/aliasing'
-
-
1
module Marshal
-
1
class << self
-
1
def load_with_autoloading(source)
-
load_without_autoloading(source)
-
rescue ArgumentError, NameError => exc
-
if exc.message.match(%r|undefined class/module (.+)|)
-
# try loading the class/module
-
$1.constantize
-
# if it is a IO we need to go back to read the object
-
source.rewind if source.respond_to?(:rewind)
-
retry
-
else
-
raise exc
-
end
-
end
-
-
1
alias_method_chain :load, :autoloading
-
end
-
end
-
1
require 'active_support/core_ext/module/aliasing'
-
1
require 'active_support/core_ext/module/introspection'
-
1
require 'active_support/core_ext/module/anonymous'
-
1
require 'active_support/core_ext/module/reachable'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/module/attr_internal'
-
1
require 'active_support/core_ext/module/concerning'
-
1
require 'active_support/core_ext/module/delegation'
-
1
require 'active_support/core_ext/module/deprecation'
-
1
require 'active_support/core_ext/module/remove_method'
-
1
require 'active_support/core_ext/module/qualified_const'
-
1
class Module
-
# Encapsulates the common pattern of:
-
#
-
# alias_method :foo_without_feature, :foo
-
# alias_method :foo, :foo_with_feature
-
#
-
# With this, you simply do:
-
#
-
# alias_method_chain :foo, :feature
-
#
-
# And both aliases are set up for you.
-
#
-
# Query and bang methods (foo?, foo!) keep the same punctuation:
-
#
-
# alias_method_chain :foo?, :feature
-
#
-
# is equivalent to
-
#
-
# alias_method :foo_without_feature?, :foo?
-
# alias_method :foo?, :foo_with_feature?
-
#
-
# so you can safely chain foo, foo?, and foo! with the same feature.
-
1
def alias_method_chain(target, feature)
-
# Strip out punctuation on predicates or bang methods since
-
# e.g. target?_without_feature is not a valid method name.
-
16
aliased_target, punctuation = target.to_s.sub(/([?!=])$/, ''), $1
-
16
yield(aliased_target, punctuation) if block_given?
-
-
16
with_method = "#{aliased_target}_with_#{feature}#{punctuation}"
-
16
without_method = "#{aliased_target}_without_#{feature}#{punctuation}"
-
-
16
alias_method without_method, target
-
16
alias_method target, with_method
-
-
case
-
when public_method_defined?(without_method)
-
16
public target
-
when protected_method_defined?(without_method)
-
protected target
-
when private_method_defined?(without_method)
-
private target
-
16
end
-
end
-
-
# Allows you to make aliases for attributes, which includes
-
# getter, setter, and query methods.
-
#
-
# class Content < ActiveRecord::Base
-
# # has a title attribute
-
# end
-
#
-
# class Email < Content
-
# alias_attribute :subject, :title
-
# end
-
#
-
# e = Email.find(1)
-
# e.title # => "Superstars"
-
# e.subject # => "Superstars"
-
# e.subject? # => true
-
# e.subject = "Megastars"
-
# e.title # => "Megastars"
-
1
def alias_attribute(new_name, old_name)
-
module_eval <<-STR, __FILE__, __LINE__ + 1
-
def #{new_name}; self.#{old_name}; end # def subject; self.title; end
-
def #{new_name}?; self.#{old_name}?; end # def subject?; self.title?; end
-
def #{new_name}=(v); self.#{old_name} = v; end # def subject=(v); self.title = v; end
-
STR
-
end
-
end
-
1
class Module
-
# A module may or may not have a name.
-
#
-
# module M; end
-
# M.name # => "M"
-
#
-
# m = Module.new
-
# m.name # => nil
-
#
-
# A module gets a name when it is first assigned to a constant. Either
-
# via the +module+ or +class+ keyword or by an explicit assignment:
-
#
-
# m = Module.new # creates an anonymous module
-
# M = m # => m gets a name here as a side-effect
-
# m.name # => "M"
-
1
def anonymous?
-
10
name.nil?
-
end
-
end
-
1
class Module
-
# Declares an attribute reader backed by an internally-named instance variable.
-
1
def attr_internal_reader(*attrs)
-
25
attrs.each {|attr_name| attr_internal_define(attr_name, :reader)}
-
end
-
-
# Declares an attribute writer backed by an internally-named instance variable.
-
1
def attr_internal_writer(*attrs)
-
31
attrs.each {|attr_name| attr_internal_define(attr_name, :writer)}
-
end
-
-
# Declares an attribute reader and writer backed by an internally-named instance
-
# variable.
-
1
def attr_internal_accessor(*attrs)
-
10
attr_internal_reader(*attrs)
-
10
attr_internal_writer(*attrs)
-
end
-
1
alias_method :attr_internal, :attr_internal_accessor
-
-
2
class << self; attr_accessor :attr_internal_naming_format end
-
1
self.attr_internal_naming_format = '@_%s'
-
-
1
private
-
1
def attr_internal_ivar_name(attr)
-
33
Module.attr_internal_naming_format % attr
-
end
-
-
1
def attr_internal_define(attr_name, type)
-
33
internal_name = attr_internal_ivar_name(attr_name).sub(/\A@/, '')
-
# class_eval is necessary on 1.9 or else the methods are made private
-
33
class_eval do
-
# use native attr_* methods as they are faster on some Ruby implementations
-
33
send("attr_#{type}", internal_name)
-
end
-
33
attr_name, internal_name = "#{attr_name}=", "#{internal_name}=" if type == :writer
-
33
alias_method attr_name, internal_name
-
33
remove_method internal_name
-
end
-
end
-
1
require 'active_support/core_ext/array/extract_options'
-
-
# Extends the module object with class/module and instance accessors for
-
# class/module attributes, just like the native attr* accessors for instance
-
# attributes.
-
1
class Module
-
# Defines a class attribute and creates a class and instance reader methods.
-
# The underlying the class variable is set to +nil+, if it is not previously
-
# defined.
-
#
-
# module HairColors
-
# mattr_reader :hair_colors
-
# end
-
#
-
# HairColors.hair_colors # => nil
-
# HairColors.class_variable_set("@@hair_colors", [:brown, :black])
-
# HairColors.hair_colors # => [:brown, :black]
-
#
-
# The attribute name must be a valid method name in Ruby.
-
#
-
# module Foo
-
# mattr_reader :"1_Badname "
-
# end
-
# # => NameError: invalid attribute name
-
#
-
# If you want to opt out the creation on the instance reader method, pass
-
# <tt>instance_reader: false</tt> or <tt>instance_accessor: false</tt>.
-
#
-
# module HairColors
-
# mattr_writer :hair_colors, instance_reader: false
-
# end
-
#
-
# class Person
-
# include HairColors
-
# end
-
#
-
# Person.new.hair_colors # => NoMethodError
-
#
-
#
-
# Also, you can pass a block to set up the attribute with a default value.
-
#
-
# module HairColors
-
# cattr_reader :hair_colors do
-
# [:brown, :black, :blonde, :red]
-
# end
-
# end
-
#
-
# class Person
-
# include HairColors
-
# end
-
#
-
# Person.hair_colors # => [:brown, :black, :blonde, :red]
-
1
def mattr_reader(*syms)
-
104
options = syms.extract_options!
-
104
syms.each do |sym|
-
104
raise NameError.new("invalid attribute name: #{sym}") unless sym =~ /^[_A-Za-z]\w*$/
-
104
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
@@#{sym} = nil unless defined? @@#{sym}
-
-
def self.#{sym}
-
@@#{sym}
-
end
-
EOS
-
-
104
unless options[:instance_reader] == false || options[:instance_accessor] == false
-
101
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
def #{sym}
-
@@#{sym}
-
end
-
EOS
-
end
-
104
class_variable_set("@@#{sym}", yield) if block_given?
-
end
-
end
-
1
alias :cattr_reader :mattr_reader
-
-
# Defines a class attribute and creates a class and instance writer methods to
-
# allow assignment to the attribute.
-
#
-
# module HairColors
-
# mattr_writer :hair_colors
-
# end
-
#
-
# class Person
-
# include HairColors
-
# end
-
#
-
# HairColors.hair_colors = [:brown, :black]
-
# Person.class_variable_get("@@hair_colors") # => [:brown, :black]
-
# Person.new.hair_colors = [:blonde, :red]
-
# HairColors.class_variable_get("@@hair_colors") # => [:blonde, :red]
-
#
-
# If you want to opt out the instance writer method, pass
-
# <tt>instance_writer: false</tt> or <tt>instance_accessor: false</tt>.
-
#
-
# module HairColors
-
# mattr_writer :hair_colors, instance_writer: false
-
# end
-
#
-
# class Person
-
# include HairColors
-
# end
-
#
-
# Person.new.hair_colors = [:blonde, :red] # => NoMethodError
-
#
-
# Also, you can pass a block to set up the attribute with a default value.
-
#
-
# class HairColors
-
# mattr_writer :hair_colors do
-
# [:brown, :black, :blonde, :red]
-
# end
-
# end
-
#
-
# class Person
-
# include HairColors
-
# end
-
#
-
# Person.class_variable_get("@@hair_colors") # => [:brown, :black, :blonde, :red]
-
1
def mattr_writer(*syms)
-
101
options = syms.extract_options!
-
101
syms.each do |sym|
-
101
raise NameError.new("invalid attribute name: #{sym}") unless sym =~ /^[_A-Za-z]\w*$/
-
101
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
@@#{sym} = nil unless defined? @@#{sym}
-
-
def self.#{sym}=(obj)
-
@@#{sym} = obj
-
end
-
EOS
-
-
101
unless options[:instance_writer] == false || options[:instance_accessor] == false
-
89
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
def #{sym}=(obj)
-
@@#{sym} = obj
-
end
-
EOS
-
end
-
101
send("#{sym}=", yield) if block_given?
-
end
-
end
-
1
alias :cattr_writer :mattr_writer
-
-
# Defines both class and instance accessors for class attributes.
-
#
-
# module HairColors
-
# mattr_accessor :hair_colors
-
# end
-
#
-
# class Person
-
# include HairColors
-
# end
-
#
-
# Person.hair_colors = [:brown, :black, :blonde, :red]
-
# Person.hair_colors # => [:brown, :black, :blonde, :red]
-
# Person.new.hair_colors # => [:brown, :black, :blonde, :red]
-
#
-
# If a subclass changes the value then that would also change the value for
-
# parent class. Similarly if parent class changes the value then that would
-
# change the value of subclasses too.
-
#
-
# class Male < Person
-
# end
-
#
-
# Male.hair_colors << :blue
-
# Person.hair_colors # => [:brown, :black, :blonde, :red, :blue]
-
#
-
# To opt out of the instance writer method, pass <tt>instance_writer: false</tt>.
-
# To opt out of the instance reader method, pass <tt>instance_reader: false</tt>.
-
#
-
# module HairColors
-
# mattr_accessor :hair_colors, instance_writer: false, instance_reader: false
-
# end
-
#
-
# class Person
-
# include HairColors
-
# end
-
#
-
# Person.new.hair_colors = [:brown] # => NoMethodError
-
# Person.new.hair_colors # => NoMethodError
-
#
-
# Or pass <tt>instance_accessor: false</tt>, to opt out both instance methods.
-
#
-
# module HairColors
-
# mattr_accessor :hair_colors, instance_accessor: false
-
# end
-
#
-
# class Person
-
# include HairColors
-
# end
-
#
-
# Person.new.hair_colors = [:brown] # => NoMethodError
-
# Person.new.hair_colors # => NoMethodError
-
#
-
# Also you can pass a block to set up the attribute with a default value.
-
#
-
# module HairColors
-
# mattr_accessor :hair_colors do
-
# [:brown, :black, :blonde, :red]
-
# end
-
# end
-
#
-
# class Person
-
# include HairColors
-
# end
-
#
-
# Person.class_variable_get("@@hair_colors") #=> [:brown, :black, :blonde, :red]
-
1
def mattr_accessor(*syms, &blk)
-
100
mattr_reader(*syms, &blk)
-
100
mattr_writer(*syms, &blk)
-
end
-
1
alias :cattr_accessor :mattr_accessor
-
end
-
1
require 'active_support/concern'
-
-
1
class Module
-
# = Bite-sized separation of concerns
-
#
-
# We often find ourselves with a medium-sized chunk of behavior that we'd
-
# like to extract, but only mix in to a single class.
-
#
-
# Extracting a plain old Ruby object to encapsulate it and collaborate or
-
# delegate to the original object is often a good choice, but when there's
-
# no additional state to encapsulate or we're making DSL-style declarations
-
# about the parent class, introducing new collaborators can obfuscate rather
-
# than simplify.
-
#
-
# The typical route is to just dump everything in a monolithic class, perhaps
-
# with a comment, as a least-bad alternative. Using modules in separate files
-
# means tedious sifting to get a big-picture view.
-
#
-
# = Dissatisfying ways to separate small concerns
-
#
-
# == Using comments:
-
#
-
# class Todo
-
# # Other todo implementation
-
# # ...
-
#
-
# ## Event tracking
-
# has_many :events
-
#
-
# before_create :track_creation
-
# after_destroy :track_deletion
-
#
-
# private
-
# def track_creation
-
# # ...
-
# end
-
# end
-
#
-
# == With an inline module:
-
#
-
# Noisy syntax.
-
#
-
# class Todo
-
# # Other todo implementation
-
# # ...
-
#
-
# module EventTracking
-
# extend ActiveSupport::Concern
-
#
-
# included do
-
# has_many :events
-
# before_create :track_creation
-
# after_destroy :track_deletion
-
# end
-
#
-
# private
-
# def track_creation
-
# # ...
-
# end
-
# end
-
# include EventTracking
-
# end
-
#
-
# == Mix-in noise exiled to its own file:
-
#
-
# Once our chunk of behavior starts pushing the scroll-to-understand it's
-
# boundary, we give in and move it to a separate file. At this size, the
-
# overhead feels in good proportion to the size of our extraction, despite
-
# diluting our at-a-glance sense of how things really work.
-
#
-
# class Todo
-
# # Other todo implementation
-
# # ...
-
#
-
# include TodoEventTracking
-
# end
-
#
-
# = Introducing Module#concerning
-
#
-
# By quieting the mix-in noise, we arrive at a natural, low-ceremony way to
-
# separate bite-sized concerns.
-
#
-
# class Todo
-
# # Other todo implementation
-
# # ...
-
#
-
# concerning :EventTracking do
-
# included do
-
# has_many :events
-
# before_create :track_creation
-
# after_destroy :track_deletion
-
# end
-
#
-
# private
-
# def track_creation
-
# # ...
-
# end
-
# end
-
# end
-
#
-
# Todo.ancestors
-
# # => Todo, Todo::EventTracking, Object
-
#
-
# This small step has some wonderful ripple effects. We can
-
# * grok the behavior of our class in one glance,
-
# * clean up monolithic junk-drawer classes by separating their concerns, and
-
# * stop leaning on protected/private for crude "this is internal stuff" modularity.
-
1
module Concerning
-
# Define a new concern and mix it in.
-
1
def concerning(topic, &block)
-
include concern(topic, &block)
-
end
-
-
# A low-cruft shortcut to define a concern.
-
#
-
# concern :EventTracking do
-
# ...
-
# end
-
#
-
# is equivalent to
-
#
-
# module EventTracking
-
# extend ActiveSupport::Concern
-
#
-
# ...
-
# end
-
1
def concern(topic, &module_definition)
-
const_set topic, Module.new {
-
extend ::ActiveSupport::Concern
-
module_eval(&module_definition)
-
}
-
end
-
end
-
1
include Concerning
-
end
-
1
class Module
-
# Error generated by +delegate+ when a method is called on +nil+ and +allow_nil+
-
# option is not used.
-
1
class DelegationError < NoMethodError; end
-
-
# Provides a +delegate+ class method to easily expose contained objects'
-
# public methods as your own.
-
#
-
# ==== Options
-
# * <tt>:to</tt> - Specifies the target object
-
# * <tt>:prefix</tt> - Prefixes the new method with the target name or a custom prefix
-
# * <tt>:allow_nil</tt> - if set to true, prevents a +NoMethodError+ to be raised
-
#
-
# The macro receives one or more method names (specified as symbols or
-
# strings) and the name of the target object via the <tt>:to</tt> option
-
# (also a symbol or string).
-
#
-
# Delegation is particularly useful with Active Record associations:
-
#
-
# class Greeter < ActiveRecord::Base
-
# def hello
-
# 'hello'
-
# end
-
#
-
# def goodbye
-
# 'goodbye'
-
# end
-
# end
-
#
-
# class Foo < ActiveRecord::Base
-
# belongs_to :greeter
-
# delegate :hello, to: :greeter
-
# end
-
#
-
# Foo.new.hello # => "hello"
-
# Foo.new.goodbye # => NoMethodError: undefined method `goodbye' for #<Foo:0x1af30c>
-
#
-
# Multiple delegates to the same target are allowed:
-
#
-
# class Foo < ActiveRecord::Base
-
# belongs_to :greeter
-
# delegate :hello, :goodbye, to: :greeter
-
# end
-
#
-
# Foo.new.goodbye # => "goodbye"
-
#
-
# Methods can be delegated to instance variables, class variables, or constants
-
# by providing them as a symbols:
-
#
-
# class Foo
-
# CONSTANT_ARRAY = [0,1,2,3]
-
# @@class_array = [4,5,6,7]
-
#
-
# def initialize
-
# @instance_array = [8,9,10,11]
-
# end
-
# delegate :sum, to: :CONSTANT_ARRAY
-
# delegate :min, to: :@@class_array
-
# delegate :max, to: :@instance_array
-
# end
-
#
-
# Foo.new.sum # => 6
-
# Foo.new.min # => 4
-
# Foo.new.max # => 11
-
#
-
# It's also possible to delegate a method to the class by using +:class+:
-
#
-
# class Foo
-
# def self.hello
-
# "world"
-
# end
-
#
-
# delegate :hello, to: :class
-
# end
-
#
-
# Foo.new.hello # => "world"
-
#
-
# Delegates can optionally be prefixed using the <tt>:prefix</tt> option. If the value
-
# is <tt>true</tt>, the delegate methods are prefixed with the name of the object being
-
# delegated to.
-
#
-
# Person = Struct.new(:name, :address)
-
#
-
# class Invoice < Struct.new(:client)
-
# delegate :name, :address, to: :client, prefix: true
-
# end
-
#
-
# john_doe = Person.new('John Doe', 'Vimmersvej 13')
-
# invoice = Invoice.new(john_doe)
-
# invoice.client_name # => "John Doe"
-
# invoice.client_address # => "Vimmersvej 13"
-
#
-
# It is also possible to supply a custom prefix.
-
#
-
# class Invoice < Struct.new(:client)
-
# delegate :name, :address, to: :client, prefix: :customer
-
# end
-
#
-
# invoice = Invoice.new(john_doe)
-
# invoice.customer_name # => 'John Doe'
-
# invoice.customer_address # => 'Vimmersvej 13'
-
#
-
# If the target is +nil+ and does not respond to the delegated method a
-
# +NoMethodError+ is raised, as with any other value. Sometimes, however, it
-
# makes sense to be robust to that situation and that is the purpose of the
-
# <tt>:allow_nil</tt> option: If the target is not +nil+, or it is and
-
# responds to the method, everything works as usual. But if it is +nil+ and
-
# does not respond to the delegated method, +nil+ is returned.
-
#
-
# class User < ActiveRecord::Base
-
# has_one :profile
-
# delegate :age, to: :profile
-
# end
-
#
-
# User.new.age # raises NoMethodError: undefined method `age'
-
#
-
# But if not having a profile yet is fine and should not be an error
-
# condition:
-
#
-
# class User < ActiveRecord::Base
-
# has_one :profile
-
# delegate :age, to: :profile, allow_nil: true
-
# end
-
#
-
# User.new.age # nil
-
#
-
# Note that if the target is not +nil+ then the call is attempted regardless of the
-
# <tt>:allow_nil</tt> option, and thus an exception is still raised if said object
-
# does not respond to the method:
-
#
-
# class Foo
-
# def initialize(bar)
-
# @bar = bar
-
# end
-
#
-
# delegate :name, to: :@bar, allow_nil: true
-
# end
-
#
-
# Foo.new("Bar").name # raises NoMethodError: undefined method `name'
-
#
-
# The target method must be public, otherwise it will raise +NoMethodError+.
-
#
-
1
def delegate(*methods)
-
80
options = methods.pop
-
80
unless options.is_a?(Hash) && to = options[:to]
-
raise ArgumentError, 'Delegation needs a target. Supply an options hash with a :to key as the last argument (e.g. delegate :hello, to: :greeter).'
-
end
-
-
80
prefix, allow_nil = options.values_at(:prefix, :allow_nil)
-
-
80
if prefix == true && to =~ /^[^a-z_]/
-
raise ArgumentError, 'Can only automatically set the delegation prefix when delegating to a method.'
-
end
-
-
80
method_prefix = \
-
if prefix
-
"#{prefix == true ? to : prefix}_"
-
else
-
80
''
-
end
-
-
80
file, line = caller.first.split(':', 2)
-
80
line = line.to_i
-
-
80
to = to.to_s
-
80
to = 'self.class' if to == 'class'
-
-
80
methods.each do |method|
-
# Attribute writer methods only accept one argument. Makes sure []=
-
# methods still accept two arguments.
-
269
definition = (method =~ /[^\]]=$/) ? 'arg' : '*args, &block'
-
-
# The following generated methods call the target exactly once, storing
-
# the returned value in a dummy variable.
-
#
-
# Reason is twofold: On one hand doing less calls is in general better.
-
# On the other hand it could be that the target has side-effects,
-
# whereas conceptually, from the user point of view, the delegator should
-
# be doing one call.
-
269
if allow_nil
-
6
method_def = [
-
"def #{method_prefix}#{method}(#{definition})", # def customer_name(*args, &block)
-
"_ = #{to}", # _ = client
-
"if !_.nil? || nil.respond_to?(:#{method})", # if !_.nil? || nil.respond_to?(:name)
-
" _.#{method}(#{definition})", # _.name(*args, &block)
-
"end", # end
-
"end" # end
-
].join ';'
-
else
-
263
exception = %(raise DelegationError, "#{self}##{method_prefix}#{method} delegated to #{to}.#{method}, but #{to} is nil: \#{self.inspect}")
-
-
263
method_def = [
-
"def #{method_prefix}#{method}(#{definition})", # def customer_name(*args, &block)
-
" _ = #{to}", # _ = client
-
" _.#{method}(#{definition})", # _.name(*args, &block)
-
"rescue NoMethodError => e", # rescue NoMethodError => e
-
" if _.nil? && e.name == :#{method}", # if _.nil? && e.name == :name
-
" #{exception}", # # add helpful message to the exception
-
" else", # else
-
" raise", # raise
-
" end", # end
-
"end" # end
-
].join ';'
-
end
-
-
269
module_eval(method_def, file, line)
-
end
-
end
-
end
-
1
class Module
-
# deprecate :foo
-
# deprecate bar: 'message'
-
# deprecate :foo, :bar, baz: 'warning!', qux: 'gone!'
-
#
-
# You can also use custom deprecator instance:
-
#
-
# deprecate :foo, deprecator: MyLib::Deprecator.new
-
# deprecate :foo, bar: "warning!", deprecator: MyLib::Deprecator.new
-
#
-
# \Custom deprecators must respond to <tt>deprecation_warning(deprecated_method_name, message, caller_backtrace)</tt>
-
# method where you can implement your custom warning behavior.
-
#
-
# class MyLib::Deprecator
-
# def deprecation_warning(deprecated_method_name, message, caller_backtrace = nil)
-
# message = "#{deprecated_method_name} is deprecated and will be removed from MyLibrary | #{message}"
-
# Kernel.warn message
-
# end
-
# end
-
1
def deprecate(*method_names)
-
ActiveSupport::Deprecation.deprecate_methods(self, *method_names)
-
end
-
end
-
1
require 'active_support/inflector'
-
-
1
class Module
-
# Returns the name of the module containing this one.
-
#
-
# M::N.parent_name # => "M"
-
1
def parent_name
-
6
if defined? @parent_name
-
4
@parent_name
-
else
-
2
@parent_name = name =~ /::[^:]+\Z/ ? $`.freeze : nil
-
end
-
end
-
-
# Returns the module which contains this one according to its name.
-
#
-
# module M
-
# module N
-
# end
-
# end
-
# X = M::N
-
#
-
# M::N.parent # => M
-
# X.parent # => M
-
#
-
# The parent of top-level and anonymous modules is Object.
-
#
-
# M.parent # => Object
-
# Module.new.parent # => Object
-
1
def parent
-
1
parent_name ? ActiveSupport::Inflector.constantize(parent_name) : Object
-
end
-
-
# Returns all the parents of this module according to its name, ordered from
-
# nested outwards. The receiver is not contained within the result.
-
#
-
# module M
-
# module N
-
# end
-
# end
-
# X = M::N
-
#
-
# M.parents # => [Object]
-
# M::N.parents # => [M, Object]
-
# X.parents # => [M, Object]
-
1
def parents
-
3
parents = []
-
3
if parent_name
-
2
parts = parent_name.split('::')
-
2
until parts.empty?
-
4
parents << ActiveSupport::Inflector.constantize(parts * '::')
-
4
parts.pop
-
end
-
end
-
3
parents << Object unless parents.include? Object
-
3
parents
-
end
-
-
1
def local_constants #:nodoc:
-
constants(false)
-
end
-
end
-
1
class Module
-
###
-
# TODO: remove this after 1.9 support is dropped
-
1
def methods_transplantable? # :nodoc:
-
4
x = Module.new { def foo; end }
-
4
Module.new { define_method :bar, x.instance_method(:foo) }
-
2
true
-
rescue TypeError
-
false
-
end
-
end
-
1
require 'active_support/core_ext/string/inflections'
-
-
#--
-
# Allows code reuse in the methods below without polluting Module.
-
#++
-
1
module QualifiedConstUtils
-
1
def self.raise_if_absolute(path)
-
3
raise NameError.new("wrong constant name #$&") if path =~ /\A::[^:]+/
-
end
-
-
1
def self.names(path)
-
3
path.split('::')
-
end
-
end
-
-
##
-
# Extends the API for constants to be able to deal with qualified names. Arguments
-
# are assumed to be relative to the receiver.
-
#
-
#--
-
# Qualified names are required to be relative because we are extending existing
-
# methods that expect constant names, ie, relative paths of length 1. For example,
-
# Object.const_get('::String') raises NameError and so does qualified_const_get.
-
#++
-
1
class Module
-
1
def qualified_const_defined?(path, search_parents=true)
-
3
QualifiedConstUtils.raise_if_absolute(path)
-
-
3
QualifiedConstUtils.names(path).inject(self) do |mod, name|
-
3
return unless mod.const_defined?(name, search_parents)
-
3
mod.const_get(name)
-
end
-
3
return true
-
end
-
-
1
def qualified_const_get(path)
-
QualifiedConstUtils.raise_if_absolute(path)
-
-
QualifiedConstUtils.names(path).inject(self) do |mod, name|
-
mod.const_get(name)
-
end
-
end
-
-
1
def qualified_const_set(path, value)
-
QualifiedConstUtils.raise_if_absolute(path)
-
-
const_name = path.demodulize
-
mod_name = path.deconstantize
-
mod = mod_name.empty? ? self : qualified_const_get(mod_name)
-
mod.const_set(const_name, value)
-
end
-
end
-
1
require 'active_support/core_ext/module/anonymous'
-
1
require 'active_support/core_ext/string/inflections'
-
-
1
class Module
-
1
def reachable? #:nodoc:
-
!anonymous? && name.safe_constantize.equal?(self)
-
end
-
end
-
1
class Module
-
1
def remove_possible_method(method)
-
501
if method_defined?(method) || private_method_defined?(method)
-
298
undef_method(method)
-
end
-
end
-
-
1
def redefine_method(method, &block)
-
2
remove_possible_method(method)
-
2
define_method(method, &block)
-
end
-
end
-
1
class NameError
-
# Extract the name of the missing constant from the exception message.
-
1
def missing_name
-
if /undefined local variable or method/ !~ message
-
$1 if /((::)?([A-Z]\w*)(::[A-Z]\w*)*)$/ =~ message
-
end
-
end
-
-
# Was this exception raised because the given name was missing?
-
1
def missing_name?(name)
-
if name.is_a? Symbol
-
last_name = (missing_name || '').split('::').last
-
last_name == name.to_s
-
else
-
missing_name == name.to_s
-
end
-
end
-
end
-
1
require 'active_support/core_ext/numeric/bytes'
-
1
require 'active_support/core_ext/numeric/time'
-
1
require 'active_support/core_ext/numeric/conversions'
-
1
class Numeric
-
1
KILOBYTE = 1024
-
1
MEGABYTE = KILOBYTE * 1024
-
1
GIGABYTE = MEGABYTE * 1024
-
1
TERABYTE = GIGABYTE * 1024
-
1
PETABYTE = TERABYTE * 1024
-
1
EXABYTE = PETABYTE * 1024
-
-
# Enables the use of byte calculations and declarations, like 45.bytes + 2.6.megabytes
-
1
def bytes
-
self
-
end
-
1
alias :byte :bytes
-
-
1
def kilobytes
-
1
self * KILOBYTE
-
end
-
1
alias :kilobyte :kilobytes
-
-
1
def megabytes
-
self * MEGABYTE
-
end
-
1
alias :megabyte :megabytes
-
-
1
def gigabytes
-
self * GIGABYTE
-
end
-
1
alias :gigabyte :gigabytes
-
-
1
def terabytes
-
self * TERABYTE
-
end
-
1
alias :terabyte :terabytes
-
-
1
def petabytes
-
self * PETABYTE
-
end
-
1
alias :petabyte :petabytes
-
-
1
def exabytes
-
self * EXABYTE
-
end
-
1
alias :exabyte :exabytes
-
end
-
1
require 'active_support/core_ext/big_decimal/conversions'
-
1
require 'active_support/number_helper'
-
-
1
class Numeric
-
-
# Provides options for converting numbers into formatted strings.
-
# Options are provided for phone numbers, currency, percentage,
-
# precision, positional notation, file size and pretty printing.
-
#
-
# ==== Options
-
#
-
# For details on which formats use which options, see ActiveSupport::NumberHelper
-
#
-
# ==== Examples
-
#
-
# Phone Numbers:
-
# 5551234.to_s(:phone) # => 555-1234
-
# 1235551234.to_s(:phone) # => 123-555-1234
-
# 1235551234.to_s(:phone, area_code: true) # => (123) 555-1234
-
# 1235551234.to_s(:phone, delimiter: ' ') # => 123 555 1234
-
# 1235551234.to_s(:phone, area_code: true, extension: 555) # => (123) 555-1234 x 555
-
# 1235551234.to_s(:phone, country_code: 1) # => +1-123-555-1234
-
# 1235551234.to_s(:phone, country_code: 1, extension: 1343, delimiter: '.')
-
# # => +1.123.555.1234 x 1343
-
#
-
# Currency:
-
# 1234567890.50.to_s(:currency) # => $1,234,567,890.50
-
# 1234567890.506.to_s(:currency) # => $1,234,567,890.51
-
# 1234567890.506.to_s(:currency, precision: 3) # => $1,234,567,890.506
-
# 1234567890.506.to_s(:currency, locale: :fr) # => 1 234 567 890,51 €
-
# -1234567890.50.to_s(:currency, negative_format: '(%u%n)')
-
# # => ($1,234,567,890.50)
-
# 1234567890.50.to_s(:currency, unit: '£', separator: ',', delimiter: '')
-
# # => £1234567890,50
-
# 1234567890.50.to_s(:currency, unit: '£', separator: ',', delimiter: '', format: '%n %u')
-
# # => 1234567890,50 £
-
#
-
# Percentage:
-
# 100.to_s(:percentage) # => 100.000%
-
# 100.to_s(:percentage, precision: 0) # => 100%
-
# 1000.to_s(:percentage, delimiter: '.', separator: ',') # => 1.000,000%
-
# 302.24398923423.to_s(:percentage, precision: 5) # => 302.24399%
-
# 1000.to_s(:percentage, locale: :fr) # => 1 000,000%
-
# 100.to_s(:percentage, format: '%n %') # => 100 %
-
#
-
# Delimited:
-
# 12345678.to_s(:delimited) # => 12,345,678
-
# 12345678.05.to_s(:delimited) # => 12,345,678.05
-
# 12345678.to_s(:delimited, delimiter: '.') # => 12.345.678
-
# 12345678.to_s(:delimited, delimiter: ',') # => 12,345,678
-
# 12345678.05.to_s(:delimited, separator: ' ') # => 12,345,678 05
-
# 12345678.05.to_s(:delimited, locale: :fr) # => 12 345 678,05
-
# 98765432.98.to_s(:delimited, delimiter: ' ', separator: ',')
-
# # => 98 765 432,98
-
#
-
# Rounded:
-
# 111.2345.to_s(:rounded) # => 111.235
-
# 111.2345.to_s(:rounded, precision: 2) # => 111.23
-
# 13.to_s(:rounded, precision: 5) # => 13.00000
-
# 389.32314.to_s(:rounded, precision: 0) # => 389
-
# 111.2345.to_s(:rounded, significant: true) # => 111
-
# 111.2345.to_s(:rounded, precision: 1, significant: true) # => 100
-
# 13.to_s(:rounded, precision: 5, significant: true) # => 13.000
-
# 111.234.to_s(:rounded, locale: :fr) # => 111,234
-
# 13.to_s(:rounded, precision: 5, significant: true, strip_insignificant_zeros: true)
-
# # => 13
-
# 389.32314.to_s(:rounded, precision: 4, significant: true) # => 389.3
-
# 1111.2345.to_s(:rounded, precision: 2, separator: ',', delimiter: '.')
-
# # => 1.111,23
-
#
-
# Human-friendly size in Bytes:
-
# 123.to_s(:human_size) # => 123 Bytes
-
# 1234.to_s(:human_size) # => 1.21 KB
-
# 12345.to_s(:human_size) # => 12.1 KB
-
# 1234567.to_s(:human_size) # => 1.18 MB
-
# 1234567890.to_s(:human_size) # => 1.15 GB
-
# 1234567890123.to_s(:human_size) # => 1.12 TB
-
# 1234567.to_s(:human_size, precision: 2) # => 1.2 MB
-
# 483989.to_s(:human_size, precision: 2) # => 470 KB
-
# 1234567.to_s(:human_size, precision: 2, separator: ',') # => 1,2 MB
-
# 1234567890123.to_s(:human_size, precision: 5) # => "1.1229 TB"
-
# 524288000.to_s(:human_size, precision: 5) # => "500 MB"
-
#
-
# Human-friendly format:
-
# 123.to_s(:human) # => "123"
-
# 1234.to_s(:human) # => "1.23 Thousand"
-
# 12345.to_s(:human) # => "12.3 Thousand"
-
# 1234567.to_s(:human) # => "1.23 Million"
-
# 1234567890.to_s(:human) # => "1.23 Billion"
-
# 1234567890123.to_s(:human) # => "1.23 Trillion"
-
# 1234567890123456.to_s(:human) # => "1.23 Quadrillion"
-
# 1234567890123456789.to_s(:human) # => "1230 Quadrillion"
-
# 489939.to_s(:human, precision: 2) # => "490 Thousand"
-
# 489939.to_s(:human, precision: 4) # => "489.9 Thousand"
-
# 1234567.to_s(:human, precision: 4,
-
# significant: false) # => "1.2346 Million"
-
# 1234567.to_s(:human, precision: 1,
-
# separator: ',',
-
# significant: false) # => "1,2 Million"
-
1
def to_formatted_s(format = :default, options = {})
-
case format
-
when :phone
-
return ActiveSupport::NumberHelper.number_to_phone(self, options)
-
when :currency
-
return ActiveSupport::NumberHelper.number_to_currency(self, options)
-
when :percentage
-
return ActiveSupport::NumberHelper.number_to_percentage(self, options)
-
when :delimited
-
return ActiveSupport::NumberHelper.number_to_delimited(self, options)
-
when :rounded
-
return ActiveSupport::NumberHelper.number_to_rounded(self, options)
-
when :human
-
return ActiveSupport::NumberHelper.number_to_human(self, options)
-
when :human_size
-
return ActiveSupport::NumberHelper.number_to_human_size(self, options)
-
else
-
self.to_default_s
-
end
-
end
-
-
1
[Float, Fixnum, Bignum, BigDecimal].each do |klass|
-
4
klass.send(:alias_method, :to_default_s, :to_s)
-
-
4
klass.send(:define_method, :to_s) do |*args|
-
11
if args[0].is_a?(Symbol)
-
format = args[0]
-
options = args[1] || {}
-
-
self.to_formatted_s(format, options)
-
else
-
11
to_default_s(*args)
-
end
-
end
-
end
-
end
-
1
require 'active_support/duration'
-
1
require 'active_support/core_ext/time/calculations'
-
1
require 'active_support/core_ext/time/acts_like'
-
-
1
class Numeric
-
# Enables the use of time calculations and declarations, like 45.minutes + 2.hours + 4.years.
-
#
-
# These methods use Time#advance for precise date calculations when using from_now, ago, etc.
-
# as well as adding or subtracting their results from a Time object. For example:
-
#
-
# # equivalent to Time.current.advance(months: 1)
-
# 1.month.from_now
-
#
-
# # equivalent to Time.current.advance(years: 2)
-
# 2.years.from_now
-
#
-
# # equivalent to Time.current.advance(months: 4, years: 5)
-
# (4.months + 5.years).from_now
-
#
-
# While these methods provide precise calculation when used as in the examples above, care
-
# should be taken to note that this is not true if the result of `months', `years', etc is
-
# converted before use:
-
#
-
# # equivalent to 30.days.to_i.from_now
-
# 1.month.to_i.from_now
-
#
-
# # equivalent to 365.25.days.to_f.from_now
-
# 1.year.to_f.from_now
-
#
-
# In such cases, Ruby's core
-
# Date[http://ruby-doc.org/stdlib/libdoc/date/rdoc/Date.html] and
-
# Time[http://ruby-doc.org/stdlib/libdoc/time/rdoc/Time.html] should be used for precision
-
# date and time arithmetic.
-
1
def seconds
-
ActiveSupport::Duration.new(self, [[:seconds, self]])
-
end
-
1
alias :second :seconds
-
-
1
def minutes
-
1
ActiveSupport::Duration.new(self * 60, [[:seconds, self * 60]])
-
end
-
1
alias :minute :minutes
-
-
1
def hours
-
5
ActiveSupport::Duration.new(self * 3600, [[:seconds, self * 3600]])
-
end
-
1
alias :hour :hours
-
-
1
def days
-
2
ActiveSupport::Duration.new(self * 24.hours, [[:days, self]])
-
end
-
1
alias :day :days
-
-
1
def weeks
-
1
ActiveSupport::Duration.new(self * 7.days, [[:days, self * 7]])
-
end
-
1
alias :week :weeks
-
-
1
def fortnights
-
ActiveSupport::Duration.new(self * 2.weeks, [[:days, self * 14]])
-
end
-
1
alias :fortnight :fortnights
-
-
# Reads best without arguments: 10.minutes.ago
-
1
def ago(time = ::Time.current)
-
ActiveSupport::Deprecation.warn "Calling #ago or #until on a number (e.g. 5.ago) is deprecated and will be removed in the future, use 5.seconds.ago instead"
-
time - self
-
end
-
-
# Reads best with argument: 10.minutes.until(time)
-
1
alias :until :ago
-
-
# Reads best with argument: 10.minutes.since(time)
-
1
def since(time = ::Time.current)
-
ActiveSupport::Deprecation.warn "Calling #since or #from_now on a number (e.g. 5.since) is deprecated and will be removed in the future, use 5.seconds.since instead"
-
time + self
-
end
-
-
# Reads best without arguments: 10.minutes.from_now
-
1
alias :from_now :since
-
-
# Used with the standard time durations, like 1.hour.in_milliseconds --
-
# so we can feed them to JavaScript functions like getTime().
-
1
def in_milliseconds
-
self * 1000
-
end
-
end
-
1
require 'active_support/core_ext/object/acts_like'
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'active_support/core_ext/object/duplicable'
-
1
require 'active_support/core_ext/object/deep_dup'
-
1
require 'active_support/core_ext/object/try'
-
1
require 'active_support/core_ext/object/inclusion'
-
-
1
require 'active_support/core_ext/object/conversions'
-
1
require 'active_support/core_ext/object/instance_variables'
-
-
1
require 'active_support/core_ext/object/json'
-
1
require 'active_support/core_ext/object/to_param'
-
1
require 'active_support/core_ext/object/to_query'
-
1
require 'active_support/core_ext/object/with_options'
-
1
class Object
-
# A duck-type assistant method. For example, Active Support extends Date
-
# to define an <tt>acts_like_date?</tt> method, and extends Time to define
-
# <tt>acts_like_time?</tt>. As a result, we can do <tt>x.acts_like?(:time)</tt> and
-
# <tt>x.acts_like?(:date)</tt> to do duck-type-safe comparisons, since classes that
-
# we want to act like Time simply need to define an <tt>acts_like_time?</tt> method.
-
1
def acts_like?(duck)
-
respond_to? :"acts_like_#{duck}?"
-
end
-
end
-
# encoding: utf-8
-
-
1
class Object
-
# An object is blank if it's false, empty, or a whitespace string.
-
# For example, '', ' ', +nil+, [], and {} are all blank.
-
#
-
# This simplifies
-
#
-
# address.nil? || address.empty?
-
#
-
# to
-
#
-
# address.blank?
-
#
-
# @return [true, false]
-
1
def blank?
-
96
respond_to?(:empty?) ? !!empty? : !self
-
end
-
-
# An object is present if it's not blank.
-
#
-
# @return [true, false]
-
1
def present?
-
374
!blank?
-
end
-
-
# Returns the receiver if it's present otherwise returns +nil+.
-
# <tt>object.presence</tt> is equivalent to
-
#
-
# object.present? ? object : nil
-
#
-
# For example, something like
-
#
-
# state = params[:state] if params[:state].present?
-
# country = params[:country] if params[:country].present?
-
# region = state || country || 'US'
-
#
-
# becomes
-
#
-
# region = params[:state].presence || params[:country].presence || 'US'
-
#
-
# @return [Object]
-
1
def presence
-
72
self if present?
-
end
-
end
-
-
1
class NilClass
-
# +nil+ is blank:
-
#
-
# nil.blank? # => true
-
#
-
# @return [true]
-
1
def blank?
-
296
true
-
end
-
end
-
-
1
class FalseClass
-
# +false+ is blank:
-
#
-
# false.blank? # => true
-
#
-
# @return [true]
-
1
def blank?
-
true
-
end
-
end
-
-
1
class TrueClass
-
# +true+ is not blank:
-
#
-
# true.blank? # => false
-
#
-
# @return [false]
-
1
def blank?
-
false
-
end
-
end
-
-
1
class Array
-
# An array is blank if it's empty:
-
#
-
# [].blank? # => true
-
# [1,2,3].blank? # => false
-
#
-
# @return [true, false]
-
1
alias_method :blank?, :empty?
-
end
-
-
1
class Hash
-
# A hash is blank if it's empty:
-
#
-
# {}.blank? # => true
-
# { key: 'value' }.blank? # => false
-
#
-
# @return [true, false]
-
1
alias_method :blank?, :empty?
-
end
-
-
1
class String
-
1
BLANK_RE = /\A[[:space:]]*\z/
-
-
# A string is blank if it's empty or contains whitespaces only:
-
#
-
# ''.blank? # => true
-
# ' '.blank? # => true
-
# "\t\n\r".blank? # => true
-
# ' blah '.blank? # => false
-
#
-
# Unicode whitespace is supported:
-
#
-
# "\u00a0".blank? # => true
-
#
-
# @return [true, false]
-
1
def blank?
-
560
BLANK_RE === self
-
end
-
end
-
-
1
class Numeric #:nodoc:
-
# No number is blank:
-
#
-
# 1.blank? # => false
-
# 0.blank? # => false
-
#
-
# @return [false]
-
1
def blank?
-
false
-
end
-
end
-
1
require 'active_support/core_ext/object/to_param'
-
1
require 'active_support/core_ext/object/to_query'
-
1
require 'active_support/core_ext/array/conversions'
-
1
require 'active_support/core_ext/hash/conversions'
-
1
require 'active_support/core_ext/object/duplicable'
-
-
1
class Object
-
# Returns a deep copy of object if it's duplicable. If it's
-
# not duplicable, returns +self+.
-
#
-
# object = Object.new
-
# dup = object.deep_dup
-
# dup.instance_variable_set(:@a, 1)
-
#
-
# object.instance_variable_defined?(:@a) # => false
-
# dup.instance_variable_defined?(:@a) # => true
-
1
def deep_dup
-
292
duplicable? ? dup : self
-
end
-
end
-
-
1
class Array
-
# Returns a deep copy of array.
-
#
-
# array = [1, [2, 3]]
-
# dup = array.deep_dup
-
# dup[1][2] = 4
-
#
-
# array[1][2] # => nil
-
# dup[1][2] # => 4
-
1
def deep_dup
-
map { |it| it.deep_dup }
-
end
-
end
-
-
1
class Hash
-
# Returns a deep copy of hash.
-
#
-
# hash = { a: { b: 'b' } }
-
# dup = hash.deep_dup
-
# dup[:a][:c] = 'c'
-
#
-
# hash[:a][:c] # => nil
-
# dup[:a][:c] # => "c"
-
1
def deep_dup
-
86
each_with_object(dup) do |(key, value), hash|
-
167
hash[key.deep_dup] = value.deep_dup
-
end
-
end
-
end
-
#--
-
# Most objects are cloneable, but not all. For example you can't dup +nil+:
-
#
-
# nil.dup # => TypeError: can't dup NilClass
-
#
-
# Classes may signal their instances are not duplicable removing +dup+/+clone+
-
# or raising exceptions from them. So, to dup an arbitrary object you normally
-
# use an optimistic approach and are ready to catch an exception, say:
-
#
-
# arbitrary_object.dup rescue object
-
#
-
# Rails dups objects in a few critical spots where they are not that arbitrary.
-
# That rescue is very expensive (like 40 times slower than a predicate), and it
-
# is often triggered.
-
#
-
# That's why we hardcode the following cases and check duplicable? instead of
-
# using that rescue idiom.
-
#++
-
1
class Object
-
# Can you safely dup this object?
-
#
-
# False for +nil+, +false+, +true+, symbol, and number objects;
-
# true otherwise.
-
1
def duplicable?
-
true
-
end
-
end
-
-
1
class NilClass
-
# +nil+ is not duplicable:
-
#
-
# nil.duplicable? # => false
-
# nil.dup # => TypeError: can't dup NilClass
-
1
def duplicable?
-
14
false
-
end
-
end
-
-
1
class FalseClass
-
# +false+ is not duplicable:
-
#
-
# false.duplicable? # => false
-
# false.dup # => TypeError: can't dup FalseClass
-
1
def duplicable?
-
false
-
end
-
end
-
-
1
class TrueClass
-
# +true+ is not duplicable:
-
#
-
# true.duplicable? # => false
-
# true.dup # => TypeError: can't dup TrueClass
-
1
def duplicable?
-
42
false
-
end
-
end
-
-
1
class Symbol
-
# Symbols are not duplicable:
-
#
-
# :my_symbol.duplicable? # => false
-
# :my_symbol.dup # => TypeError: can't dup Symbol
-
1
def duplicable?
-
236
false
-
end
-
end
-
-
1
class Numeric
-
# Numbers are not duplicable:
-
#
-
# 3.duplicable? # => false
-
# 3.dup # => TypeError: can't dup Fixnum
-
1
def duplicable?
-
false
-
end
-
end
-
-
1
require 'bigdecimal'
-
1
class BigDecimal
-
1
begin
-
1
BigDecimal.new('4.56').dup
-
-
1
def duplicable?
-
true
-
end
-
rescue TypeError
-
# can't dup, so use superclass implementation
-
end
-
end
-
1
class Object
-
# Returns true if this object is included in the argument. Argument must be
-
# any object which responds to +#include?+. Usage:
-
#
-
# characters = ["Konata", "Kagami", "Tsukasa"]
-
# "Konata".in?(characters) # => true
-
#
-
# This will throw an ArgumentError if the argument doesn't respond
-
# to +#include?+.
-
1
def in?(another_object)
-
another_object.include?(self)
-
rescue NoMethodError
-
raise ArgumentError.new("The parameter passed to #in? must respond to #include?")
-
end
-
-
# Returns the receiver if it's included in the argument otherwise returns +nil+.
-
# Argument must be any object which responds to +#include?+. Usage:
-
#
-
# params[:bucket_type].presence_in %w( project calendar )
-
#
-
# This will throw an ArgumentError if the argument doesn't respond to +#include?+.
-
#
-
# @return [Object]
-
1
def presence_in(another_object)
-
self.in?(another_object) ? self : nil
-
end
-
end
-
1
class Object
-
# Returns a hash with string keys that maps instance variable names without "@" to their
-
# corresponding values.
-
#
-
# class C
-
# def initialize(x, y)
-
# @x, @y = x, y
-
# end
-
# end
-
#
-
# C.new(0, 1).instance_values # => {"x" => 0, "y" => 1}
-
1
def instance_values
-
Hash[instance_variables.map { |name| [name[1..-1], instance_variable_get(name)] }]
-
end
-
-
# Returns an array of instance variable names as strings including "@".
-
#
-
# class C
-
# def initialize(x, y)
-
# @x, @y = x, y
-
# end
-
# end
-
#
-
# C.new(0, 1).instance_variable_names # => ["@y", "@x"]
-
1
def instance_variable_names
-
instance_variables.map { |var| var.to_s }
-
end
-
end
-
# Hack to load json gem first so we can overwrite its to_json.
-
1
require 'json'
-
1
require 'bigdecimal'
-
1
require 'active_support/core_ext/big_decimal/conversions' # for #to_s
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/hash/slice'
-
1
require 'active_support/core_ext/object/instance_variables'
-
1
require 'time'
-
1
require 'active_support/core_ext/time/conversions'
-
1
require 'active_support/core_ext/date_time/conversions'
-
1
require 'active_support/core_ext/date/conversions'
-
1
require 'active_support/core_ext/module/aliasing'
-
-
# The JSON gem adds a few modules to Ruby core classes containing :to_json definition, overwriting
-
# their default behavior. That said, we need to define the basic to_json method in all of them,
-
# otherwise they will always use to_json gem implementation, which is backwards incompatible in
-
# several cases (for instance, the JSON implementation for Hash does not work) with inheritance
-
# and consequently classes as ActiveSupport::OrderedHash cannot be serialized to json.
-
#
-
# On the other hand, we should avoid conflict with ::JSON.{generate,dump}(obj). Unfortunately, the
-
# JSON gem's encoder relies on its own to_json implementation to encode objects. Since it always
-
# passes a ::JSON::State object as the only argument to to_json, we can detect that and forward the
-
# calls to the original to_json method.
-
#
-
# It should be noted that when using ::JSON.{generate,dump} directly, ActiveSupport's encoder is
-
# bypassed completely. This means that as_json won't be invoked and the JSON gem will simply
-
# ignore any options it does not natively understand. This also means that ::JSON.{generate,dump}
-
# should give exactly the same results with or without active support.
-
1
[Object, Array, FalseClass, Float, Hash, Integer, NilClass, String, TrueClass].each do |klass|
-
9
klass.class_eval do
-
9
def to_json_with_active_support_encoder(options = nil)
-
if options.is_a?(::JSON::State)
-
# Called from JSON.{generate,dump}, forward it to JSON gem's to_json
-
self.to_json_without_active_support_encoder(options)
-
else
-
# to_json is being invoked directly, use ActiveSupport's encoder
-
ActiveSupport::JSON.encode(self, options)
-
end
-
end
-
-
9
alias_method_chain :to_json, :active_support_encoder
-
end
-
end
-
-
1
class Object
-
1
def as_json(options = nil) #:nodoc:
-
if respond_to?(:to_hash)
-
to_hash.as_json(options)
-
else
-
instance_values.as_json(options)
-
end
-
end
-
end
-
-
1
class Struct #:nodoc:
-
1
def as_json(options = nil)
-
Hash[members.zip(values)].as_json(options)
-
end
-
end
-
-
1
class TrueClass
-
1
def as_json(options = nil) #:nodoc:
-
self
-
end
-
end
-
-
1
class FalseClass
-
1
def as_json(options = nil) #:nodoc:
-
self
-
end
-
end
-
-
1
class NilClass
-
1
def as_json(options = nil) #:nodoc:
-
self
-
end
-
end
-
-
1
class String
-
1
def as_json(options = nil) #:nodoc:
-
self
-
end
-
end
-
-
1
class Symbol
-
1
def as_json(options = nil) #:nodoc:
-
to_s
-
end
-
end
-
-
1
class Numeric
-
1
def as_json(options = nil) #:nodoc:
-
self
-
end
-
end
-
-
1
class Float
-
# Encoding Infinity or NaN to JSON should return "null". The default returns
-
# "Infinity" or "NaN" which are not valid JSON.
-
1
def as_json(options = nil) #:nodoc:
-
finite? ? self : nil
-
end
-
end
-
-
1
class BigDecimal
-
# A BigDecimal would be naturally represented as a JSON number. Most libraries,
-
# however, parse non-integer JSON numbers directly as floats. Clients using
-
# those libraries would get in general a wrong number and no way to recover
-
# other than manually inspecting the string with the JSON code itself.
-
#
-
# That's why a JSON string is returned. The JSON literal is not numeric, but
-
# if the other end knows by contract that the data is supposed to be a
-
# BigDecimal, it still has the chance to post-process the string and get the
-
# real value.
-
1
def as_json(options = nil) #:nodoc:
-
finite? ? to_s : nil
-
end
-
end
-
-
1
class Regexp
-
1
def as_json(options = nil) #:nodoc:
-
to_s
-
end
-
end
-
-
1
module Enumerable
-
1
def as_json(options = nil) #:nodoc:
-
to_a.as_json(options)
-
end
-
end
-
-
1
class Range
-
1
def as_json(options = nil) #:nodoc:
-
to_s
-
end
-
end
-
-
1
class Array
-
1
def as_json(options = nil) #:nodoc:
-
map { |v| options ? v.as_json(options.dup) : v.as_json }
-
end
-
end
-
-
1
class Hash
-
1
def as_json(options = nil) #:nodoc:
-
# create a subset of the hash by applying :only or :except
-
subset = if options
-
if attrs = options[:only]
-
slice(*Array(attrs))
-
elsif attrs = options[:except]
-
except(*Array(attrs))
-
else
-
self
-
end
-
else
-
self
-
end
-
-
Hash[subset.map { |k, v| [k.to_s, options ? v.as_json(options.dup) : v.as_json] }]
-
end
-
end
-
-
1
class Time
-
1
def as_json(options = nil) #:nodoc:
-
if ActiveSupport.use_standard_json_time_format
-
xmlschema(ActiveSupport::JSON::Encoding.time_precision)
-
else
-
%(#{strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)})
-
end
-
end
-
end
-
-
1
class Date
-
1
def as_json(options = nil) #:nodoc:
-
if ActiveSupport.use_standard_json_time_format
-
strftime("%Y-%m-%d")
-
else
-
strftime("%Y/%m/%d")
-
end
-
end
-
end
-
-
1
class DateTime
-
1
def as_json(options = nil) #:nodoc:
-
if ActiveSupport.use_standard_json_time_format
-
xmlschema(ActiveSupport::JSON::Encoding.time_precision)
-
else
-
strftime('%Y/%m/%d %H:%M:%S %z')
-
end
-
end
-
end
-
-
1
class Process::Status #:nodoc:
-
1
def as_json(options = nil)
-
{ :exitstatus => exitstatus, :pid => pid }
-
end
-
end
-
1
class Object
-
# Alias of <tt>to_s</tt>.
-
1
def to_param
-
to_s
-
end
-
end
-
-
1
class NilClass
-
# Returns +self+.
-
1
def to_param
-
self
-
end
-
end
-
-
1
class TrueClass
-
# Returns +self+.
-
1
def to_param
-
self
-
end
-
end
-
-
1
class FalseClass
-
# Returns +self+.
-
1
def to_param
-
self
-
end
-
end
-
-
1
class Array
-
# Calls <tt>to_param</tt> on all its elements and joins the result with
-
# slashes. This is used by <tt>url_for</tt> in Action Pack.
-
1
def to_param
-
collect { |e| e.to_param }.join '/'
-
end
-
end
-
-
1
class Hash
-
# Returns a string representation of the receiver suitable for use as a URL
-
# query string:
-
#
-
# {name: 'David', nationality: 'Danish'}.to_param
-
# # => "name=David&nationality=Danish"
-
#
-
# An optional namespace can be passed to enclose the param names:
-
#
-
# {name: 'David', nationality: 'Danish'}.to_param('user')
-
# # => "user[name]=David&user[nationality]=Danish"
-
#
-
# The string pairs "key=value" that conform the query string
-
# are sorted lexicographically in ascending order.
-
#
-
# This method is also aliased as +to_query+.
-
1
def to_param(namespace = nil)
-
if empty?
-
namespace ? nil.to_query(namespace) : ''
-
else
-
collect do |key, value|
-
value.to_query(namespace ? "#{namespace}[#{key}]" : key)
-
end.sort! * '&'
-
end
-
end
-
end
-
1
require 'active_support/core_ext/object/to_param'
-
-
1
class Object
-
# Converts an object into a string suitable for use as a URL query string, using the given <tt>key</tt> as the
-
# param name.
-
#
-
# Note: This method is defined as a default implementation for all Objects for Hash#to_query to work.
-
1
def to_query(key)
-
require 'cgi' unless defined?(CGI) && defined?(CGI::escape)
-
"#{CGI.escape(key.to_param)}=#{CGI.escape(to_param.to_s)}"
-
end
-
end
-
-
1
class Array
-
# Converts an array into a string suitable for use as a URL query string,
-
# using the given +key+ as the param name.
-
#
-
# ['Rails', 'coding'].to_query('hobbies') # => "hobbies%5B%5D=Rails&hobbies%5B%5D=coding"
-
1
def to_query(key)
-
prefix = "#{key}[]"
-
-
if empty?
-
nil.to_query(prefix)
-
else
-
collect { |value| value.to_query(prefix) }.join '&'
-
end
-
end
-
end
-
-
1
class Hash
-
1
alias_method :to_query, :to_param
-
end
-
1
class Object
-
# Invokes the public method whose name goes as first argument just like
-
# +public_send+ does, except that if the receiver does not respond to it the
-
# call returns +nil+ rather than raising an exception.
-
#
-
# This method is defined to be able to write
-
#
-
# @person.try(:name)
-
#
-
# instead of
-
#
-
# @person ? @person.name : nil
-
#
-
# +try+ returns +nil+ when called on +nil+ regardless of whether it responds
-
# to the method:
-
#
-
# nil.try(:to_i) # => nil, rather than 0
-
#
-
# Arguments and blocks are forwarded to the method if invoked:
-
#
-
# @posts.try(:each_slice, 2) do |a, b|
-
# ...
-
# end
-
#
-
# The number of arguments in the signature must match. If the object responds
-
# to the method the call is attempted and +ArgumentError+ is still raised
-
# otherwise.
-
#
-
# If +try+ is called without arguments it yields the receiver to a given
-
# block unless it is +nil+:
-
#
-
# @person.try do |p|
-
# ...
-
# end
-
#
-
# Please also note that +try+ is defined on +Object+, therefore it won't work
-
# with instances of classes that do not have +Object+ among their ancestors,
-
# like direct subclasses of +BasicObject+. For example, using +try+ with
-
# +SimpleDelegator+ will delegate +try+ to the target instead of calling it on
-
# delegator itself.
-
1
def try(*a, &b)
-
2
if a.empty? && block_given?
-
yield self
-
else
-
2
public_send(*a, &b) if respond_to?(a.first)
-
end
-
end
-
-
# Same as #try, but will raise a NoMethodError exception if the receiving is not nil and
-
# does not implement the tried method.
-
1
def try!(*a, &b)
-
if a.empty? && block_given?
-
yield self
-
else
-
public_send(*a, &b)
-
end
-
end
-
end
-
-
1
class NilClass
-
# Calling +try+ on +nil+ always returns +nil+.
-
# It becomes specially helpful when navigating through associations that may return +nil+.
-
#
-
# nil.try(:name) # => nil
-
#
-
# Without +try+
-
# @person && !@person.children.blank? && @person.children.first.name
-
#
-
# With +try+
-
# @person.try(:children).try(:first).try(:name)
-
1
def try(*args)
-
nil
-
end
-
-
1
def try!(*args)
-
nil
-
end
-
end
-
1
require 'active_support/option_merger'
-
-
1
class Object
-
# An elegant way to factor duplication out of options passed to a series of
-
# method calls. Each method called in the block, with the block variable as
-
# the receiver, will have its options merged with the default +options+ hash
-
# provided. Each method called on the block variable must take an options
-
# hash as its final argument.
-
#
-
# Without <tt>with_options></tt>, this code contains duplication:
-
#
-
# class Account < ActiveRecord::Base
-
# has_many :customers, dependent: :destroy
-
# has_many :products, dependent: :destroy
-
# has_many :invoices, dependent: :destroy
-
# has_many :expenses, dependent: :destroy
-
# end
-
#
-
# Using <tt>with_options</tt>, we can remove the duplication:
-
#
-
# class Account < ActiveRecord::Base
-
# with_options dependent: :destroy do |assoc|
-
# assoc.has_many :customers
-
# assoc.has_many :products
-
# assoc.has_many :invoices
-
# assoc.has_many :expenses
-
# end
-
# end
-
#
-
# It can also be used with an explicit receiver:
-
#
-
# I18n.with_options locale: user.locale, scope: 'newsletter' do |i18n|
-
# subject i18n.t :subject
-
# body i18n.t :body, user_name: user.name
-
# end
-
#
-
# <tt>with_options</tt> can also be nested since the call is forwarded to its receiver.
-
# Each nesting level will merge inherited defaults in addition to their own.
-
1
def with_options(options)
-
2
yield ActiveSupport::OptionMerger.new(self, options)
-
end
-
end
-
1
require 'active_support/core_ext/range/conversions'
-
1
require 'active_support/core_ext/range/include_range'
-
1
require 'active_support/core_ext/range/overlaps'
-
1
require 'active_support/core_ext/range/each'
-
1
class Range
-
1
RANGE_FORMATS = {
-
:db => Proc.new { |start, stop| "BETWEEN '#{start.to_s(:db)}' AND '#{stop.to_s(:db)}'" }
-
}
-
-
# Gives a human readable format of the range.
-
#
-
# (1..100).to_formatted_s # => "1..100"
-
1
def to_formatted_s(format = :default)
-
if formatter = RANGE_FORMATS[format]
-
formatter.call(first, last)
-
else
-
to_default_s
-
end
-
end
-
-
1
alias_method :to_default_s, :to_s
-
1
alias_method :to_s, :to_formatted_s
-
end
-
1
require 'active_support/core_ext/module/aliasing'
-
-
1
class Range #:nodoc:
-
-
1
def each_with_time_with_zone(&block)
-
6
ensure_iteration_allowed
-
6
each_without_time_with_zone(&block)
-
end
-
1
alias_method_chain :each, :time_with_zone
-
-
1
def step_with_time_with_zone(n = 1, &block)
-
ensure_iteration_allowed
-
step_without_time_with_zone(n, &block)
-
end
-
1
alias_method_chain :step, :time_with_zone
-
-
1
private
-
1
def ensure_iteration_allowed
-
6
if first.is_a?(Time)
-
raise TypeError, "can't iterate from #{first.class}"
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/aliasing'
-
-
1
class Range
-
# Extends the default Range#include? to support range comparisons.
-
# (1..5).include?(1..5) # => true
-
# (1..5).include?(2..3) # => true
-
# (1..5).include?(2..6) # => false
-
#
-
# The native Range#include? behavior is untouched.
-
# ('a'..'f').include?('c') # => true
-
# (5..9).include?(11) # => false
-
1
def include_with_range?(value)
-
if value.is_a?(::Range)
-
# 1...10 includes 1..9 but it does not include 1..10.
-
operator = exclude_end? && !value.exclude_end? ? :< : :<=
-
include_without_range?(value.first) && value.last.send(operator, last)
-
else
-
include_without_range?(value)
-
end
-
end
-
-
1
alias_method_chain :include?, :range
-
end
-
1
class Range
-
# Compare two ranges and see if they overlap each other
-
# (1..5).overlaps?(4..6) # => true
-
# (1..5).overlaps?(7..9) # => false
-
1
def overlaps?(other)
-
cover?(other.first) || other.cover?(first)
-
end
-
end
-
1
class Regexp #:nodoc:
-
1
def multiline?
-
options & MULTILINE == MULTILINE
-
end
-
end
-
1
require 'active_support/core_ext/string/conversions'
-
1
require 'active_support/core_ext/string/filters'
-
1
require 'active_support/core_ext/string/multibyte'
-
1
require 'active_support/core_ext/string/starts_ends_with'
-
1
require 'active_support/core_ext/string/inflections'
-
1
require 'active_support/core_ext/string/access'
-
1
require 'active_support/core_ext/string/behavior'
-
1
require 'active_support/core_ext/string/output_safety'
-
1
require 'active_support/core_ext/string/exclude'
-
1
require 'active_support/core_ext/string/strip'
-
1
require 'active_support/core_ext/string/inquiry'
-
1
require 'active_support/core_ext/string/indent'
-
1
require 'active_support/core_ext/string/zones'
-
1
class String
-
# If you pass a single Fixnum, returns a substring of one character at that
-
# position. The first character of the string is at position 0, the next at
-
# position 1, and so on. If a range is supplied, a substring containing
-
# characters at offsets given by the range is returned. In both cases, if an
-
# offset is negative, it is counted from the end of the string. Returns nil
-
# if the initial offset falls outside the string. Returns an empty string if
-
# the beginning of the range is greater than the end of the string.
-
#
-
# str = "hello"
-
# str.at(0) # => "h"
-
# str.at(1..3) # => "ell"
-
# str.at(-2) # => "l"
-
# str.at(-2..-1) # => "lo"
-
# str.at(5) # => nil
-
# str.at(5..-1) # => ""
-
#
-
# If a Regexp is given, the matching portion of the string is returned.
-
# If a String is given, that given string is returned if it occurs in
-
# the string. In both cases, nil is returned if there is no match.
-
#
-
# str = "hello"
-
# str.at(/lo/) # => "lo"
-
# str.at(/ol/) # => nil
-
# str.at("lo") # => "lo"
-
# str.at("ol") # => nil
-
1
def at(position)
-
self[position]
-
end
-
-
# Returns a substring from the given position to the end of the string.
-
# If the position is negative, it is counted from the end of the string.
-
#
-
# str = "hello"
-
# str.from(0) # => "hello"
-
# str.from(3) # => "lo"
-
# str.from(-2) # => "lo"
-
#
-
# You can mix it with +to+ method and do fun things like:
-
#
-
# str = "hello"
-
# str.from(0).to(-1) # => "hello"
-
# str.from(1).to(-2) # => "ell"
-
1
def from(position)
-
self[position..-1]
-
end
-
-
# Returns a substring from the beginning of the string to the given position.
-
# If the position is negative, it is counted from the end of the string.
-
#
-
# str = "hello"
-
# str.to(0) # => "h"
-
# str.to(3) # => "hell"
-
# str.to(-2) # => "hell"
-
#
-
# You can mix it with +from+ method and do fun things like:
-
#
-
# str = "hello"
-
# str.from(0).to(-1) # => "hello"
-
# str.from(1).to(-2) # => "ell"
-
1
def to(position)
-
self[0..position]
-
end
-
-
# Returns the first character. If a limit is supplied, returns a substring
-
# from the beginning of the string until it reaches the limit value. If the
-
# given limit is greater than or equal to the string length, returns self.
-
#
-
# str = "hello"
-
# str.first # => "h"
-
# str.first(1) # => "h"
-
# str.first(2) # => "he"
-
# str.first(0) # => ""
-
# str.first(6) # => "hello"
-
1
def first(limit = 1)
-
if limit == 0
-
''
-
elsif limit >= size
-
self
-
else
-
to(limit - 1)
-
end
-
end
-
-
# Returns the last character of the string. If a limit is supplied, returns a substring
-
# from the end of the string until it reaches the limit value (counting backwards). If
-
# the given limit is greater than or equal to the string length, returns self.
-
#
-
# str = "hello"
-
# str.last # => "o"
-
# str.last(1) # => "o"
-
# str.last(2) # => "lo"
-
# str.last(0) # => ""
-
# str.last(6) # => "hello"
-
1
def last(limit = 1)
-
if limit == 0
-
''
-
elsif limit >= size
-
self
-
else
-
from(-limit)
-
end
-
end
-
end
-
1
class String
-
# Enable more predictable duck-typing on String-like classes. See <tt>Object#acts_like?</tt>.
-
1
def acts_like_string?
-
true
-
end
-
end
-
1
require 'date'
-
1
require 'active_support/core_ext/time/calculations'
-
-
1
class String
-
# Converts a string to a Time value.
-
# The +form+ can be either :utc or :local (default :local).
-
#
-
# The time is parsed using Time.parse method.
-
# If +form+ is :local, then the time is in the system timezone.
-
# If the date part is missing then the current date is used and if
-
# the time part is missing then it is assumed to be 00:00:00.
-
#
-
# "13-12-2012".to_time # => 2012-12-13 00:00:00 +0100
-
# "06:12".to_time # => 2012-12-13 06:12:00 +0100
-
# "2012-12-13 06:12".to_time # => 2012-12-13 06:12:00 +0100
-
# "2012-12-13T06:12".to_time # => 2012-12-13 06:12:00 +0100
-
# "2012-12-13T06:12".to_time(:utc) # => 2012-12-13 05:12:00 UTC
-
# "12/13/2012".to_time # => ArgumentError: argument out of range
-
1
def to_time(form = :local)
-
parts = Date._parse(self, false)
-
return if parts.empty?
-
-
now = Time.now
-
time = Time.new(
-
parts.fetch(:year, now.year),
-
parts.fetch(:mon, now.month),
-
parts.fetch(:mday, now.day),
-
parts.fetch(:hour, 0),
-
parts.fetch(:min, 0),
-
parts.fetch(:sec, 0) + parts.fetch(:sec_fraction, 0),
-
parts.fetch(:offset, form == :utc ? 0 : nil)
-
)
-
-
form == :utc ? time.utc : time.getlocal
-
end
-
-
# Converts a string to a Date value.
-
#
-
# "1-1-2012".to_date # => Sun, 01 Jan 2012
-
# "01/01/2012".to_date # => Sun, 01 Jan 2012
-
# "2012-12-13".to_date # => Thu, 13 Dec 2012
-
# "12/13/2012".to_date # => ArgumentError: invalid date
-
1
def to_date
-
::Date.parse(self, false) unless blank?
-
end
-
-
# Converts a string to a DateTime value.
-
#
-
# "1-1-2012".to_datetime # => Sun, 01 Jan 2012 00:00:00 +0000
-
# "01/01/2012 23:59:59".to_datetime # => Sun, 01 Jan 2012 23:59:59 +0000
-
# "2012-12-13 12:50".to_datetime # => Thu, 13 Dec 2012 12:50:00 +0000
-
# "12/13/2012".to_datetime # => ArgumentError: invalid date
-
1
def to_datetime
-
::DateTime.parse(self, false) unless blank?
-
end
-
end
-
1
class String
-
# The inverse of <tt>String#include?</tt>. Returns true if the string
-
# does not include the other string.
-
#
-
# "hello".exclude? "lo" # => false
-
# "hello".exclude? "ol" # => true
-
# "hello".exclude? ?h # => false
-
1
def exclude?(string)
-
!include?(string)
-
end
-
end
-
1
class String
-
# Returns the string, first removing all whitespace on both ends of
-
# the string, and then changing remaining consecutive whitespace
-
# groups into one space each.
-
#
-
# Note that it handles both ASCII and Unicode whitespace like mongolian vowel separator (U+180E).
-
#
-
# %{ Multi-line
-
# string }.squish # => "Multi-line string"
-
# " foo bar \n \t boo".squish # => "foo bar boo"
-
1
def squish
-
dup.squish!
-
end
-
-
# Performs a destructive squish. See String#squish.
-
1
def squish!
-
gsub!(/\A[[:space:]]+/, '')
-
gsub!(/[[:space:]]+\z/, '')
-
gsub!(/[[:space:]]+/, ' ')
-
self
-
end
-
-
# Returns a new string with all occurrences of the pattern removed. Short-hand for String#gsub(pattern, '').
-
1
def remove(pattern)
-
gsub pattern, ''
-
end
-
-
# Alters the string by removing all occurrences of the pattern. Short-hand for String#gsub!(pattern, '').
-
1
def remove!(pattern)
-
gsub! pattern, ''
-
end
-
-
# Truncates a given +text+ after a given <tt>length</tt> if +text+ is longer than <tt>length</tt>:
-
#
-
# 'Once upon a time in a world far far away'.truncate(27)
-
# # => "Once upon a time in a wo..."
-
#
-
# Pass a string or regexp <tt>:separator</tt> to truncate +text+ at a natural break:
-
#
-
# 'Once upon a time in a world far far away'.truncate(27, separator: ' ')
-
# # => "Once upon a time in a..."
-
#
-
# 'Once upon a time in a world far far away'.truncate(27, separator: /\s/)
-
# # => "Once upon a time in a..."
-
#
-
# The last characters will be replaced with the <tt>:omission</tt> string (defaults to "...")
-
# for a total length not exceeding <tt>length</tt>:
-
#
-
# 'And they found that many people were sleeping better.'.truncate(25, omission: '... (continued)')
-
# # => "And they f... (continued)"
-
1
def truncate(truncate_at, options = {})
-
return dup unless length > truncate_at
-
-
omission = options[:omission] || '...'
-
length_with_room_for_omission = truncate_at - omission.length
-
stop = \
-
if options[:separator]
-
rindex(options[:separator], length_with_room_for_omission) || length_with_room_for_omission
-
else
-
length_with_room_for_omission
-
end
-
-
"#{self[0, stop]}#{omission}"
-
end
-
end
-
1
class String
-
# Same as +indent+, except it indents the receiver in-place.
-
#
-
# Returns the indented string, or +nil+ if there was nothing to indent.
-
1
def indent!(amount, indent_string=nil, indent_empty_lines=false)
-
indent_string = indent_string || self[/^[ \t]/] || ' '
-
re = indent_empty_lines ? /^/ : /^(?!$)/
-
gsub!(re, indent_string * amount)
-
end
-
-
# Indents the lines in the receiver:
-
#
-
# <<EOS.indent(2)
-
# def some_method
-
# some_code
-
# end
-
# EOS
-
# # =>
-
# def some_method
-
# some_code
-
# end
-
#
-
# The second argument, +indent_string+, specifies which indent string to
-
# use. The default is +nil+, which tells the method to make a guess by
-
# peeking at the first indented line, and fallback to a space if there is
-
# none.
-
#
-
# " foo".indent(2) # => " foo"
-
# "foo\n\t\tbar".indent(2) # => "\t\tfoo\n\t\t\t\tbar"
-
# "foo".indent(2, "\t") # => "\t\tfoo"
-
#
-
# While +indent_string+ is typically one space or tab, it may be any string.
-
#
-
# The third argument, +indent_empty_lines+, is a flag that says whether
-
# empty lines should be indented. Default is false.
-
#
-
# "foo\n\nbar".indent(2) # => " foo\n\n bar"
-
# "foo\n\nbar".indent(2, nil, true) # => " foo\n \n bar"
-
#
-
1
def indent(amount, indent_string=nil, indent_empty_lines=false)
-
dup.tap {|_| _.indent!(amount, indent_string, indent_empty_lines)}
-
end
-
end
-
1
require 'active_support/inflector/methods'
-
1
require 'active_support/inflector/transliterate'
-
-
# String inflections define new methods on the String class to transform names for different purposes.
-
# For instance, you can figure out the name of a table from the name of a class.
-
#
-
# 'ScaleScore'.tableize # => "scale_scores"
-
#
-
1
class String
-
# Returns the plural form of the word in the string.
-
#
-
# If the optional parameter +count+ is specified,
-
# the singular form will be returned if <tt>count == 1</tt>.
-
# For any other value of +count+ the plural will be returned.
-
#
-
# If the optional parameter +locale+ is specified,
-
# the word will be pluralized as a word of that language.
-
# By default, this parameter is set to <tt>:en</tt>.
-
# You must define your own inflection rules for languages other than English.
-
#
-
# 'post'.pluralize # => "posts"
-
# 'octopus'.pluralize # => "octopi"
-
# 'sheep'.pluralize # => "sheep"
-
# 'words'.pluralize # => "words"
-
# 'the blue mailman'.pluralize # => "the blue mailmen"
-
# 'CamelOctopus'.pluralize # => "CamelOctopi"
-
# 'apple'.pluralize(1) # => "apple"
-
# 'apple'.pluralize(2) # => "apples"
-
# 'ley'.pluralize(:es) # => "leyes"
-
# 'ley'.pluralize(1, :es) # => "ley"
-
1
def pluralize(count = nil, locale = :en)
-
8
locale = count if count.is_a?(Symbol)
-
8
if count == 1
-
self
-
else
-
8
ActiveSupport::Inflector.pluralize(self, locale)
-
end
-
end
-
-
# The reverse of +pluralize+, returns the singular form of a word in a string.
-
#
-
# If the optional parameter +locale+ is specified,
-
# the word will be singularized as a word of that language.
-
# By default, this parameter is set to <tt>:en</tt>.
-
# You must define your own inflection rules for languages other than English.
-
#
-
# 'posts'.singularize # => "post"
-
# 'octopi'.singularize # => "octopus"
-
# 'sheep'.singularize # => "sheep"
-
# 'word'.singularize # => "word"
-
# 'the blue mailmen'.singularize # => "the blue mailman"
-
# 'CamelOctopi'.singularize # => "CamelOctopus"
-
# 'leyes'.singularize(:es) # => "ley"
-
1
def singularize(locale = :en)
-
26
ActiveSupport::Inflector.singularize(self, locale)
-
end
-
-
# +constantize+ tries to find a declared constant with the name specified
-
# in the string. It raises a NameError when the name is not in CamelCase
-
# or is not initialized. See ActiveSupport::Inflector.constantize
-
#
-
# 'Module'.constantize # => Module
-
# 'Class'.constantize # => Class
-
# 'blargle'.constantize # => NameError: wrong constant name blargle
-
1
def constantize
-
15
ActiveSupport::Inflector.constantize(self)
-
end
-
-
# +safe_constantize+ tries to find a declared constant with the name specified
-
# in the string. It returns nil when the name is not in CamelCase
-
# or is not initialized. See ActiveSupport::Inflector.safe_constantize
-
#
-
# 'Module'.safe_constantize # => Module
-
# 'Class'.safe_constantize # => Class
-
# 'blargle'.safe_constantize # => nil
-
1
def safe_constantize
-
ActiveSupport::Inflector.safe_constantize(self)
-
end
-
-
# By default, +camelize+ converts strings to UpperCamelCase. If the argument to camelize
-
# is set to <tt>:lower</tt> then camelize produces lowerCamelCase.
-
#
-
# +camelize+ will also convert '/' to '::' which is useful for converting paths to namespaces.
-
#
-
# 'active_record'.camelize # => "ActiveRecord"
-
# 'active_record'.camelize(:lower) # => "activeRecord"
-
# 'active_record/errors'.camelize # => "ActiveRecord::Errors"
-
# 'active_record/errors'.camelize(:lower) # => "activeRecord::Errors"
-
1
def camelize(first_letter = :upper)
-
37
case first_letter
-
when :upper
-
37
ActiveSupport::Inflector.camelize(self, true)
-
when :lower
-
ActiveSupport::Inflector.camelize(self, false)
-
end
-
end
-
1
alias_method :camelcase, :camelize
-
-
# Capitalizes all the words and replaces some characters in the string to create
-
# a nicer looking title. +titleize+ is meant for creating pretty output. It is not
-
# used in the Rails internals.
-
#
-
# +titleize+ is also aliased as +titlecase+.
-
#
-
# 'man from the boondocks'.titleize # => "Man From The Boondocks"
-
# 'x-men: the last stand'.titleize # => "X Men: The Last Stand"
-
1
def titleize
-
ActiveSupport::Inflector.titleize(self)
-
end
-
1
alias_method :titlecase, :titleize
-
-
# The reverse of +camelize+. Makes an underscored, lowercase form from the expression in the string.
-
#
-
# +underscore+ will also change '::' to '/' to convert namespaces to paths.
-
#
-
# 'ActiveModel'.underscore # => "active_model"
-
# 'ActiveModel::Errors'.underscore # => "active_model/errors"
-
1
def underscore
-
54
ActiveSupport::Inflector.underscore(self)
-
end
-
-
# Replaces underscores with dashes in the string.
-
#
-
# 'puni_puni'.dasherize # => "puni-puni"
-
1
def dasherize
-
72
ActiveSupport::Inflector.dasherize(self)
-
end
-
-
# Removes the module part from the constant expression in the string.
-
#
-
# 'ActiveRecord::CoreExtensions::String::Inflections'.demodulize # => "Inflections"
-
# 'Inflections'.demodulize # => "Inflections"
-
#
-
# See also +deconstantize+.
-
1
def demodulize
-
ActiveSupport::Inflector.demodulize(self)
-
end
-
-
# Removes the rightmost segment from the constant expression in the string.
-
#
-
# 'Net::HTTP'.deconstantize # => "Net"
-
# '::Net::HTTP'.deconstantize # => "::Net"
-
# 'String'.deconstantize # => ""
-
# '::String'.deconstantize # => ""
-
# ''.deconstantize # => ""
-
#
-
# See also +demodulize+.
-
1
def deconstantize
-
ActiveSupport::Inflector.deconstantize(self)
-
end
-
-
# Replaces special characters in a string so that it may be used as part of a 'pretty' URL.
-
#
-
# class Person
-
# def to_param
-
# "#{id}-#{name.parameterize}"
-
# end
-
# end
-
#
-
# @person = Person.find(1)
-
# # => #<Person id: 1, name: "Donald E. Knuth">
-
#
-
# <%= link_to(@person.name, person_path) %>
-
# # => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a>
-
1
def parameterize(sep = '-')
-
ActiveSupport::Inflector.parameterize(self, sep)
-
end
-
-
# Creates the name of a table like Rails does for models to table names. This method
-
# uses the +pluralize+ method on the last word in the string.
-
#
-
# 'RawScaledScorer'.tableize # => "raw_scaled_scorers"
-
# 'egg_and_ham'.tableize # => "egg_and_hams"
-
# 'fancyCategory'.tableize # => "fancy_categories"
-
1
def tableize
-
ActiveSupport::Inflector.tableize(self)
-
end
-
-
# Create a class name from a plural table name like Rails does for table names to models.
-
# Note that this returns a string and not a class. (To convert to an actual class
-
# follow +classify+ with +constantize+.)
-
#
-
# 'egg_and_hams'.classify # => "EggAndHam"
-
# 'posts'.classify # => "Post"
-
1
def classify
-
12
ActiveSupport::Inflector.classify(self)
-
end
-
-
# Capitalizes the first word, turns underscores into spaces, and strips a
-
# trailing '_id' if present.
-
# Like +titleize+, this is meant for creating pretty output.
-
#
-
# The capitalization of the first word can be turned off by setting the
-
# optional parameter +capitalize+ to false.
-
# By default, this parameter is true.
-
#
-
# 'employee_salary'.humanize # => "Employee salary"
-
# 'author_id'.humanize # => "Author"
-
# 'author_id'.humanize(capitalize: false) # => "author"
-
1
def humanize(options = {})
-
6
ActiveSupport::Inflector.humanize(self, options)
-
end
-
-
# Creates a foreign key name from a class name.
-
# +separate_class_name_and_id_with_underscore+ sets whether
-
# the method should put '_' between the name and 'id'.
-
#
-
# 'Message'.foreign_key # => "message_id"
-
# 'Message'.foreign_key(false) # => "messageid"
-
# 'Admin::Post'.foreign_key # => "post_id"
-
1
def foreign_key(separate_class_name_and_id_with_underscore = true)
-
ActiveSupport::Inflector.foreign_key(self, separate_class_name_and_id_with_underscore)
-
end
-
end
-
1
require 'active_support/string_inquirer'
-
-
1
class String
-
# Wraps the current string in the <tt>ActiveSupport::StringInquirer</tt> class,
-
# which gives you a prettier way to test for equality.
-
#
-
# env = 'production'.inquiry
-
# env.production? # => true
-
# env.development? # => false
-
1
def inquiry
-
ActiveSupport::StringInquirer.new(self)
-
end
-
end
-
# encoding: utf-8
-
1
require 'active_support/multibyte'
-
-
1
class String
-
# == Multibyte proxy
-
#
-
# +mb_chars+ is a multibyte safe proxy for string methods.
-
#
-
# It creates and returns an instance of the ActiveSupport::Multibyte::Chars class which
-
# encapsulates the original string. A Unicode safe version of all the String methods are defined on this proxy
-
# class. If the proxy class doesn't respond to a certain method, it's forwarded to the encapsulated string.
-
#
-
# name = 'Claus Müller'
-
# name.reverse # => "rell??M sualC"
-
# name.length # => 13
-
#
-
# name.mb_chars.reverse.to_s # => "rellüM sualC"
-
# name.mb_chars.length # => 12
-
#
-
# == Method chaining
-
#
-
# All the methods on the Chars proxy which normally return a string will return a Chars object. This allows
-
# method chaining on the result of any of these methods.
-
#
-
# name.mb_chars.reverse.length # => 12
-
#
-
# == Interoperability and configuration
-
#
-
# The Chars object tries to be as interchangeable with String objects as possible: sorting and comparing between
-
# String and Char work like expected. The bang! methods change the internal string representation in the Chars
-
# object. Interoperability problems can be resolved easily with a +to_s+ call.
-
#
-
# For more information about the methods defined on the Chars proxy see ActiveSupport::Multibyte::Chars. For
-
# information about how to change the default Multibyte behavior see ActiveSupport::Multibyte.
-
1
def mb_chars
-
ActiveSupport::Multibyte.proxy_class.new(self)
-
end
-
-
1
def is_utf8?
-
case encoding
-
when Encoding::UTF_8
-
valid_encoding?
-
when Encoding::ASCII_8BIT, Encoding::US_ASCII
-
dup.force_encoding(Encoding::UTF_8).valid_encoding?
-
else
-
false
-
end
-
end
-
end
-
1
require 'erb'
-
1
require 'active_support/core_ext/kernel/singleton_class'
-
-
1
class ERB
-
1
module Util
-
1
HTML_ESCAPE = { '&' => '&', '>' => '>', '<' => '<', '"' => '"', "'" => ''' }
-
1
JSON_ESCAPE = { '&' => '\u0026', '>' => '\u003e', '<' => '\u003c', "\u2028" => '\u2028', "\u2029" => '\u2029' }
-
1
HTML_ESCAPE_REGEXP = /[&"'><]/
-
1
HTML_ESCAPE_ONCE_REGEXP = /["><']|&(?!([a-zA-Z]+|(#\d+));)/
-
1
JSON_ESCAPE_REGEXP = /[\u2028\u2029&><]/u
-
-
# A utility method for escaping HTML tag characters.
-
# This method is also aliased as <tt>h</tt>.
-
#
-
# In your ERB templates, use this method to escape any unsafe content. For example:
-
# <%=h @person.name %>
-
#
-
# puts html_escape('is a > 0 & a < 10?')
-
# # => is a > 0 & a < 10?
-
1
def html_escape(s)
-
s = s.to_s
-
if s.html_safe?
-
s
-
else
-
s.gsub(HTML_ESCAPE_REGEXP, HTML_ESCAPE).html_safe
-
end
-
end
-
-
# Aliasing twice issues a warning "discarding old...". Remove first to avoid it.
-
1
remove_method(:h)
-
1
alias h html_escape
-
-
1
module_function :h
-
-
1
singleton_class.send(:remove_method, :html_escape)
-
1
module_function :html_escape
-
-
# A utility method for escaping HTML without affecting existing escaped entities.
-
#
-
# html_escape_once('1 < 2 & 3')
-
# # => "1 < 2 & 3"
-
#
-
# html_escape_once('<< Accept & Checkout')
-
# # => "<< Accept & Checkout"
-
1
def html_escape_once(s)
-
result = s.to_s.gsub(HTML_ESCAPE_ONCE_REGEXP, HTML_ESCAPE)
-
s.html_safe? ? result.html_safe : result
-
end
-
-
1
module_function :html_escape_once
-
-
# A utility method for escaping HTML entities in JSON strings. Specifically, the
-
# &, > and < characters are replaced with their equivalent unicode escaped form -
-
# \u0026, \u003e, and \u003c. The Unicode sequences \u2028 and \u2029 are also
-
# escaped as they are treated as newline characters in some JavaScript engines.
-
# These sequences have identical meaning as the original characters inside the
-
# context of a JSON string, so assuming the input is a valid and well-formed
-
# JSON value, the output will have equivalent meaning when parsed:
-
#
-
# json = JSON.generate({ name: "</script><script>alert('PWNED!!!')</script>"})
-
# # => "{\"name\":\"</script><script>alert('PWNED!!!')</script>\"}"
-
#
-
# json_escape(json)
-
# # => "{\"name\":\"\\u003C/script\\u003E\\u003Cscript\\u003Ealert('PWNED!!!')\\u003C/script\\u003E\"}"
-
#
-
# JSON.parse(json) == JSON.parse(json_escape(json))
-
# # => true
-
#
-
# The intended use case for this method is to escape JSON strings before including
-
# them inside a script tag to avoid XSS vulnerability:
-
#
-
# <script>
-
# var currentUser = <%= raw json_escape(current_user.to_json) %>;
-
# </script>
-
#
-
# It is necessary to +raw+ the result of +json_escape+, so that quotation marks
-
# don't get converted to <tt>"</tt> entities. +json_escape+ doesn't
-
# automatically flag the result as HTML safe, since the raw value is unsafe to
-
# use inside HTML attributes.
-
#
-
# If you need to output JSON elsewhere in your HTML, you can just do something
-
# like this, as any unsafe characters (including quotation marks) will be
-
# automatically escaped for you:
-
#
-
# <div data-user-info="<%= current_user.to_json %>">...</div>
-
#
-
# WARNING: this helper only works with valid JSON. Using this on non-JSON values
-
# will open up serious XSS vulnerabilities. For example, if you replace the
-
# +current_user.to_json+ in the example above with user input instead, the browser
-
# will happily eval() that string as JavaScript.
-
#
-
# The escaping performed in this method is identical to those performed in the
-
# Active Support JSON encoder when +ActiveSupport.escape_html_entities_in_json+ is
-
# set to true. Because this transformation is idempotent, this helper can be
-
# applied even if +ActiveSupport.escape_html_entities_in_json+ is already true.
-
#
-
# Therefore, when you are unsure if +ActiveSupport.escape_html_entities_in_json+
-
# is enabled, or if you are unsure where your JSON string originated from, it
-
# is recommended that you always apply this helper (other libraries, such as the
-
# JSON gem, do not provide this kind of protection by default; also some gems
-
# might override +to_json+ to bypass Active Support's encoder).
-
1
def json_escape(s)
-
result = s.to_s.gsub(JSON_ESCAPE_REGEXP, JSON_ESCAPE)
-
s.html_safe? ? result.html_safe : result
-
end
-
-
1
module_function :json_escape
-
end
-
end
-
-
1
class Object
-
1
def html_safe?
-
false
-
end
-
end
-
-
1
class Numeric
-
1
def html_safe?
-
true
-
end
-
end
-
-
1
module ActiveSupport #:nodoc:
-
1
class SafeBuffer < String
-
1
UNSAFE_STRING_METHODS = %w(
-
capitalize chomp chop delete downcase gsub lstrip next reverse rstrip
-
slice squeeze strip sub succ swapcase tr tr_s upcase prepend
-
)
-
-
1
alias_method :original_concat, :concat
-
1
private :original_concat
-
-
1
class SafeConcatError < StandardError
-
1
def initialize
-
super 'Could not concatenate to the buffer because it is not html safe.'
-
end
-
end
-
-
1
def [](*args)
-
if args.size < 2
-
super
-
else
-
if html_safe?
-
new_safe_buffer = super
-
new_safe_buffer.instance_eval { @html_safe = true }
-
new_safe_buffer
-
else
-
to_str[*args]
-
end
-
end
-
end
-
-
1
def safe_concat(value)
-
raise SafeConcatError unless html_safe?
-
original_concat(value)
-
end
-
-
1
def initialize(*)
-
@html_safe = true
-
super
-
end
-
-
1
def initialize_copy(other)
-
super
-
@html_safe = other.html_safe?
-
end
-
-
1
def clone_empty
-
self[0, 0]
-
end
-
-
1
def concat(value)
-
if !html_safe? || value.html_safe?
-
super(value)
-
else
-
super(ERB::Util.h(value))
-
end
-
end
-
1
alias << concat
-
-
1
def +(other)
-
dup.concat(other)
-
end
-
-
1
def %(args)
-
case args
-
when Hash
-
escaped_args = Hash[args.map { |k,arg| [k, html_escape_interpolated_argument(arg)] }]
-
else
-
escaped_args = Array(args).map { |arg| html_escape_interpolated_argument(arg) }
-
end
-
-
self.class.new(super(escaped_args))
-
end
-
-
1
def html_safe?
-
defined?(@html_safe) && @html_safe
-
end
-
-
1
def to_s
-
self
-
end
-
-
1
def to_param
-
to_str
-
end
-
-
1
def encode_with(coder)
-
coder.represent_scalar nil, to_str
-
end
-
-
1
UNSAFE_STRING_METHODS.each do |unsafe_method|
-
20
if unsafe_method.respond_to?(unsafe_method)
-
20
class_eval <<-EOT, __FILE__, __LINE__ + 1
-
def #{unsafe_method}(*args, &block) # def capitalize(*args, &block)
-
to_str.#{unsafe_method}(*args, &block) # to_str.capitalize(*args, &block)
-
end # end
-
-
def #{unsafe_method}!(*args) # def capitalize!(*args)
-
@html_safe = false # @html_safe = false
-
super # super
-
end # end
-
EOT
-
end
-
end
-
-
1
private
-
-
1
def html_escape_interpolated_argument(arg)
-
(!html_safe? || arg.html_safe?) ? arg : ERB::Util.h(arg)
-
end
-
end
-
end
-
-
1
class String
-
1
def html_safe
-
ActiveSupport::SafeBuffer.new(self)
-
end
-
end
-
1
class String
-
1
alias_method :starts_with?, :start_with?
-
1
alias_method :ends_with?, :end_with?
-
end
-
1
require 'active_support/core_ext/object/try'
-
-
1
class String
-
# Strips indentation in heredocs.
-
#
-
# For example in
-
#
-
# if options[:usage]
-
# puts <<-USAGE.strip_heredoc
-
# This command does such and such.
-
#
-
# Supported options are:
-
# -h This message
-
# ...
-
# USAGE
-
# end
-
#
-
# the user would see the usage message aligned against the left margin.
-
#
-
# Technically, it looks for the least indented line in the whole string, and removes
-
# that amount of leading whitespace.
-
1
def strip_heredoc
-
indent = scan(/^[ \t]*(?=\S)/).min.try(:size) || 0
-
gsub(/^[ \t]{#{indent}}/, '')
-
end
-
end
-
1
require 'active_support/core_ext/string/conversions'
-
1
require 'active_support/core_ext/time/zones'
-
-
1
class String
-
# Converts String to a TimeWithZone in the current zone if Time.zone or Time.zone_default
-
# is set, otherwise converts String to a Time via String#to_time
-
1
def in_time_zone(zone = ::Time.zone)
-
if zone
-
::Time.find_zone!(zone).parse(self)
-
else
-
to_time
-
end
-
end
-
end
-
# Backport of Struct#to_h from Ruby 2.0
-
class Struct # :nodoc:
-
def to_h
-
Hash[members.zip(values)]
-
end
-
1
end unless Struct.instance_methods.include?(:to_h)
-
class Thread
-
LOCK = Mutex.new # :nodoc:
-
-
# Returns the value of a thread local variable that has been set. Note that
-
# these are different than fiber local values.
-
#
-
# Thread local values are carried along with threads, and do not respect
-
# fibers. For example:
-
#
-
# Thread.new {
-
# Thread.current.thread_variable_set("foo", "bar") # set a thread local
-
# Thread.current["foo"] = "bar" # set a fiber local
-
#
-
# Fiber.new {
-
# Fiber.yield [
-
# Thread.current.thread_variable_get("foo"), # get the thread local
-
# Thread.current["foo"], # get the fiber local
-
# ]
-
# }.resume
-
# }.join.value # => ['bar', nil]
-
#
-
# The value <tt>"bar"</tt> is returned for the thread local, where +nil+ is returned
-
# for the fiber local. The fiber is executed in the same thread, so the
-
# thread local values are available.
-
def thread_variable_get(key)
-
_locals[key.to_sym]
-
end
-
-
# Sets a thread local with +key+ to +value+. Note that these are local to
-
# threads, and not to fibers. Please see Thread#thread_variable_get for
-
# more information.
-
def thread_variable_set(key, value)
-
_locals[key.to_sym] = value
-
end
-
-
# Returns an array of the names of the thread-local variables (as Symbols).
-
#
-
# thr = Thread.new do
-
# Thread.current.thread_variable_set(:cat, 'meow')
-
# Thread.current.thread_variable_set("dog", 'woof')
-
# end
-
# thr.join # => #<Thread:0x401b3f10 dead>
-
# thr.thread_variables # => [:dog, :cat]
-
#
-
# Note that these are not fiber local variables. Please see Thread#thread_variable_get
-
# for more details.
-
def thread_variables
-
_locals.keys
-
end
-
-
# Returns <tt>true</tt> if the given string (or symbol) exists as a
-
# thread-local variable.
-
#
-
# me = Thread.current
-
# me.thread_variable_set(:oliver, "a")
-
# me.thread_variable?(:oliver) # => true
-
# me.thread_variable?(:stanley) # => false
-
#
-
# Note that these are not fiber local variables. Please see Thread#thread_variable_get
-
# for more details.
-
def thread_variable?(key)
-
_locals.has_key?(key.to_sym)
-
end
-
-
def freeze
-
_locals.freeze
-
super
-
end
-
-
private
-
-
def _locals
-
if defined?(@_locals)
-
@_locals
-
else
-
LOCK.synchronize { @_locals ||= {} }
-
end
-
end
-
1
end unless Thread.instance_methods.include?(:thread_variable_set)
-
1
require 'active_support/core_ext/time/acts_like'
-
1
require 'active_support/core_ext/time/calculations'
-
1
require 'active_support/core_ext/time/conversions'
-
1
require 'active_support/core_ext/time/marshal'
-
1
require 'active_support/core_ext/time/zones'
-
1
require 'active_support/core_ext/object/acts_like'
-
-
1
class Time
-
# Duck-types as a Time-like class. See Object#acts_like?.
-
1
def acts_like_time?
-
true
-
end
-
end
-
1
require 'active_support/duration'
-
1
require 'active_support/core_ext/time/conversions'
-
1
require 'active_support/time_with_zone'
-
1
require 'active_support/core_ext/time/zones'
-
1
require 'active_support/core_ext/date_and_time/calculations'
-
-
1
class Time
-
1
include DateAndTime::Calculations
-
-
1
COMMON_YEAR_DAYS_IN_MONTH = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
-
-
1
class << self
-
# Overriding case equality method so that it returns true for ActiveSupport::TimeWithZone instances
-
1
def ===(other)
-
super || (self == Time && other.is_a?(ActiveSupport::TimeWithZone))
-
end
-
-
# Return the number of days in the given month.
-
# If no year is specified, it will use the current year.
-
1
def days_in_month(month, year = now.year)
-
if month == 2 && ::Date.gregorian_leap?(year)
-
29
-
else
-
COMMON_YEAR_DAYS_IN_MONTH[month]
-
end
-
end
-
-
# Returns <tt>Time.zone.now</tt> when <tt>Time.zone</tt> or <tt>config.time_zone</tt> are set, otherwise just returns <tt>Time.now</tt>.
-
1
def current
-
::Time.zone ? ::Time.zone.now : ::Time.now
-
end
-
-
# Layers additional behavior on Time.at so that ActiveSupport::TimeWithZone and DateTime
-
# instances can be used when called with a single argument
-
1
def at_with_coercion(*args)
-
return at_without_coercion(*args) if args.size != 1
-
-
# Time.at can be called with a time or numerical value
-
time_or_number = args.first
-
-
if time_or_number.is_a?(ActiveSupport::TimeWithZone) || time_or_number.is_a?(DateTime)
-
at_without_coercion(time_or_number.to_f).getlocal
-
else
-
at_without_coercion(time_or_number)
-
end
-
end
-
1
alias_method :at_without_coercion, :at
-
1
alias_method :at, :at_with_coercion
-
end
-
-
# Seconds since midnight: Time.now.seconds_since_midnight
-
1
def seconds_since_midnight
-
to_i - change(:hour => 0).to_i + (usec / 1.0e+6)
-
end
-
-
# Returns the number of seconds until 23:59:59.
-
#
-
# Time.new(2012, 8, 29, 0, 0, 0).seconds_until_end_of_day # => 86399
-
# Time.new(2012, 8, 29, 12, 34, 56).seconds_until_end_of_day # => 41103
-
# Time.new(2012, 8, 29, 23, 59, 59).seconds_until_end_of_day # => 0
-
1
def seconds_until_end_of_day
-
end_of_day.to_i - to_i
-
end
-
-
# Returns a new Time where one or more of the elements have been changed according
-
# to the +options+ parameter. The time options (<tt>:hour</tt>, <tt>:min</tt>,
-
# <tt>:sec</tt>, <tt>:usec</tt>) reset cascadingly, so if only the hour is passed,
-
# then minute, sec, and usec is set to 0. If the hour and minute is passed, then
-
# sec and usec is set to 0. The +options+ parameter takes a hash with any of these
-
# keys: <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>, <tt>:hour</tt>, <tt>:min</tt>,
-
# <tt>:sec</tt>, <tt>:usec</tt>.
-
#
-
# Time.new(2012, 8, 29, 22, 35, 0).change(day: 1) # => Time.new(2012, 8, 1, 22, 35, 0)
-
# Time.new(2012, 8, 29, 22, 35, 0).change(year: 1981, day: 1) # => Time.new(1981, 8, 1, 22, 35, 0)
-
# Time.new(2012, 8, 29, 22, 35, 0).change(year: 1981, hour: 0) # => Time.new(1981, 8, 29, 0, 0, 0)
-
1
def change(options)
-
new_year = options.fetch(:year, year)
-
new_month = options.fetch(:month, month)
-
new_day = options.fetch(:day, day)
-
new_hour = options.fetch(:hour, hour)
-
new_min = options.fetch(:min, options[:hour] ? 0 : min)
-
new_sec = options.fetch(:sec, (options[:hour] || options[:min]) ? 0 : sec)
-
new_usec = options.fetch(:usec, (options[:hour] || options[:min] || options[:sec]) ? 0 : Rational(nsec, 1000))
-
-
if utc?
-
::Time.utc(new_year, new_month, new_day, new_hour, new_min, new_sec, new_usec)
-
elsif zone
-
::Time.local(new_year, new_month, new_day, new_hour, new_min, new_sec, new_usec)
-
else
-
::Time.new(new_year, new_month, new_day, new_hour, new_min, new_sec + (new_usec.to_r / 1000000), utc_offset)
-
end
-
end
-
-
# Uses Date to provide precise Time calculations for years, months, and days
-
# according to the proleptic Gregorian calendar. The +options+ parameter
-
# takes a hash with any of these keys: <tt>:years</tt>, <tt>:months</tt>,
-
# <tt>:weeks</tt>, <tt>:days</tt>, <tt>:hours</tt>, <tt>:minutes</tt>,
-
# <tt>:seconds</tt>.
-
1
def advance(options)
-
unless options[:weeks].nil?
-
options[:weeks], partial_weeks = options[:weeks].divmod(1)
-
options[:days] = options.fetch(:days, 0) + 7 * partial_weeks
-
end
-
-
unless options[:days].nil?
-
options[:days], partial_days = options[:days].divmod(1)
-
options[:hours] = options.fetch(:hours, 0) + 24 * partial_days
-
end
-
-
d = to_date.advance(options)
-
d = d.gregorian if d.julian?
-
time_advanced_by_date = change(:year => d.year, :month => d.month, :day => d.day)
-
seconds_to_advance = \
-
options.fetch(:seconds, 0) +
-
options.fetch(:minutes, 0) * 60 +
-
options.fetch(:hours, 0) * 3600
-
-
if seconds_to_advance.zero?
-
time_advanced_by_date
-
else
-
time_advanced_by_date.since(seconds_to_advance)
-
end
-
end
-
-
# Returns a new Time representing the time a number of seconds ago, this is basically a wrapper around the Numeric extension
-
1
def ago(seconds)
-
since(-seconds)
-
end
-
-
# Returns a new Time representing the time a number of seconds since the instance time
-
1
def since(seconds)
-
self + seconds
-
rescue
-
to_datetime.since(seconds)
-
end
-
1
alias :in :since
-
-
# Returns a new Time representing the start of the day (0:00)
-
1
def beginning_of_day
-
#(self - seconds_since_midnight).change(usec: 0)
-
change(:hour => 0)
-
end
-
1
alias :midnight :beginning_of_day
-
1
alias :at_midnight :beginning_of_day
-
1
alias :at_beginning_of_day :beginning_of_day
-
-
# Returns a new Time representing the middle of the day (12:00)
-
1
def middle_of_day
-
change(:hour => 12)
-
end
-
1
alias :midday :middle_of_day
-
1
alias :noon :middle_of_day
-
1
alias :at_midday :middle_of_day
-
1
alias :at_noon :middle_of_day
-
1
alias :at_middle_of_day :middle_of_day
-
-
# Returns a new Time representing the end of the day, 23:59:59.999999 (.999999999 in ruby1.9)
-
1
def end_of_day
-
change(
-
:hour => 23,
-
:min => 59,
-
:sec => 59,
-
:usec => Rational(999999999, 1000)
-
)
-
end
-
1
alias :at_end_of_day :end_of_day
-
-
# Returns a new Time representing the start of the hour (x:00)
-
1
def beginning_of_hour
-
change(:min => 0)
-
end
-
1
alias :at_beginning_of_hour :beginning_of_hour
-
-
# Returns a new Time representing the end of the hour, x:59:59.999999 (.999999999 in ruby1.9)
-
1
def end_of_hour
-
change(
-
:min => 59,
-
:sec => 59,
-
:usec => Rational(999999999, 1000)
-
)
-
end
-
1
alias :at_end_of_hour :end_of_hour
-
-
# Returns a new Time representing the start of the minute (x:xx:00)
-
1
def beginning_of_minute
-
change(:sec => 0)
-
end
-
1
alias :at_beginning_of_minute :beginning_of_minute
-
-
# Returns a new Time representing the end of the minute, x:xx:59.999999 (.999999999 in ruby1.9)
-
1
def end_of_minute
-
change(
-
:sec => 59,
-
:usec => Rational(999999999, 1000)
-
)
-
end
-
1
alias :at_end_of_minute :end_of_minute
-
-
# Returns a Range representing the whole day of the current time.
-
1
def all_day
-
beginning_of_day..end_of_day
-
end
-
-
1
def plus_with_duration(other) #:nodoc:
-
if ActiveSupport::Duration === other
-
other.since(self)
-
else
-
plus_without_duration(other)
-
end
-
end
-
1
alias_method :plus_without_duration, :+
-
1
alias_method :+, :plus_with_duration
-
-
1
def minus_with_duration(other) #:nodoc:
-
9
if ActiveSupport::Duration === other
-
other.until(self)
-
else
-
9
minus_without_duration(other)
-
end
-
end
-
1
alias_method :minus_without_duration, :-
-
1
alias_method :-, :minus_with_duration
-
-
# Time#- can also be used to determine the number of seconds between two Time instances.
-
# We're layering on additional behavior so that ActiveSupport::TimeWithZone instances
-
# are coerced into values that Time#- will recognize
-
1
def minus_with_coercion(other)
-
9
other = other.comparable_time if other.respond_to?(:comparable_time)
-
9
other.is_a?(DateTime) ? to_f - other.to_f : minus_without_coercion(other)
-
end
-
1
alias_method :minus_without_coercion, :-
-
1
alias_method :-, :minus_with_coercion
-
-
# Layers additional behavior on Time#<=> so that DateTime and ActiveSupport::TimeWithZone instances
-
# can be chronologically compared with a Time
-
1
def compare_with_coercion(other)
-
# we're avoiding Time#to_datetime cause it's expensive
-
255
if other.is_a?(Time)
-
255
compare_without_coercion(other.to_time)
-
else
-
to_datetime <=> other
-
end
-
end
-
1
alias_method :compare_without_coercion, :<=>
-
1
alias_method :<=>, :compare_with_coercion
-
-
# Layers additional behavior on Time#eql? so that ActiveSupport::TimeWithZone instances
-
# can be eql? to an equivalent Time
-
1
def eql_with_coercion(other)
-
# if other is an ActiveSupport::TimeWithZone, coerce a Time instance from it so we can do eql? comparison
-
other = other.comparable_time if other.respond_to?(:comparable_time)
-
eql_without_coercion(other)
-
end
-
1
alias_method :eql_without_coercion, :eql?
-
1
alias_method :eql?, :eql_with_coercion
-
-
end
-
1
require 'active_support/inflector/methods'
-
1
require 'active_support/values/time_zone'
-
-
1
class Time
-
1
DATE_FORMATS = {
-
:db => '%Y-%m-%d %H:%M:%S',
-
:number => '%Y%m%d%H%M%S',
-
:nsec => '%Y%m%d%H%M%S%9N',
-
:time => '%H:%M',
-
:short => '%d %b %H:%M',
-
:long => '%B %d, %Y %H:%M',
-
:long_ordinal => lambda { |time|
-
day_format = ActiveSupport::Inflector.ordinalize(time.day)
-
time.strftime("%B #{day_format}, %Y %H:%M")
-
},
-
:rfc822 => lambda { |time|
-
offset_format = time.formatted_offset(false)
-
time.strftime("%a, %d %b %Y %H:%M:%S #{offset_format}")
-
},
-
:iso8601 => lambda { |time| time.iso8601 }
-
}
-
-
# Converts to a formatted string. See DATE_FORMATS for builtin formats.
-
#
-
# This method is aliased to <tt>to_s</tt>.
-
#
-
# time = Time.now # => Thu Jan 18 06:10:17 CST 2007
-
#
-
# time.to_formatted_s(:time) # => "06:10"
-
# time.to_s(:time) # => "06:10"
-
#
-
# time.to_formatted_s(:db) # => "2007-01-18 06:10:17"
-
# time.to_formatted_s(:number) # => "20070118061017"
-
# time.to_formatted_s(:short) # => "18 Jan 06:10"
-
# time.to_formatted_s(:long) # => "January 18, 2007 06:10"
-
# time.to_formatted_s(:long_ordinal) # => "January 18th, 2007 06:10"
-
# time.to_formatted_s(:rfc822) # => "Thu, 18 Jan 2007 06:10:17 -0600"
-
# time.to_formatted_s(:iso8601) # => "2007-01-18T06:10:17-06:00"
-
#
-
# == Adding your own time formats to +to_formatted_s+
-
# You can add your own formats to the Time::DATE_FORMATS hash.
-
# Use the format name as the hash key and either a strftime string
-
# or Proc instance that takes a time argument as the value.
-
#
-
# # config/initializers/time_formats.rb
-
# Time::DATE_FORMATS[:month_and_year] = '%B %Y'
-
# Time::DATE_FORMATS[:short_ordinal] = ->(time) { time.strftime("%B #{time.day.ordinalize}") }
-
1
def to_formatted_s(format = :default)
-
if formatter = DATE_FORMATS[format]
-
formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter)
-
else
-
to_default_s
-
end
-
end
-
1
alias_method :to_default_s, :to_s
-
1
alias_method :to_s, :to_formatted_s
-
-
# Returns the UTC offset as an +HH:MM formatted string.
-
#
-
# Time.local(2000).formatted_offset # => "-06:00"
-
# Time.local(2000).formatted_offset(false) # => "-0600"
-
1
def formatted_offset(colon = true, alternate_utc_string = nil)
-
utc? && alternate_utc_string || ActiveSupport::TimeZone.seconds_to_utc_offset(utc_offset, colon)
-
end
-
end
-
# Ruby 1.9.2 adds utc_offset and zone to Time, but marshaling only
-
# preserves utc_offset. Preserve zone also, even though it may not
-
# work in some edge cases.
-
1
if Time.local(2010).zone != Marshal.load(Marshal.dump(Time.local(2010))).zone
-
class Time
-
class << self
-
alias_method :_load_without_zone, :_load
-
def _load(marshaled_time)
-
time = _load_without_zone(marshaled_time)
-
time.instance_eval do
-
if zone = defined?(@_zone) && remove_instance_variable('@_zone')
-
ary = to_a
-
ary[0] += subsec if ary[0] == sec
-
ary[-1] = zone
-
utc? ? Time.utc(*ary) : Time.local(*ary)
-
else
-
self
-
end
-
end
-
end
-
end
-
-
alias_method :_dump_without_zone, :_dump
-
def _dump(*args)
-
obj = dup
-
obj.instance_variable_set('@_zone', zone)
-
obj.send :_dump_without_zone, *args
-
end
-
end
-
end
-
1
require 'active_support/time_with_zone'
-
1
require 'active_support/core_ext/date_and_time/zones'
-
-
1
class Time
-
1
include DateAndTime::Zones
-
1
class << self
-
1
attr_accessor :zone_default
-
-
# Returns the TimeZone for the current request, if this has been set (via Time.zone=).
-
# If <tt>Time.zone</tt> has not been set for the current request, returns the TimeZone specified in <tt>config.time_zone</tt>.
-
1
def zone
-
Thread.current[:time_zone] || zone_default
-
end
-
-
# Sets <tt>Time.zone</tt> to a TimeZone object for the current request/thread.
-
#
-
# This method accepts any of the following:
-
#
-
# * A Rails TimeZone object.
-
# * An identifier for a Rails TimeZone object (e.g., "Eastern Time (US & Canada)", <tt>-5.hours</tt>).
-
# * A TZInfo::Timezone object.
-
# * An identifier for a TZInfo::Timezone object (e.g., "America/New_York").
-
#
-
# Here's an example of how you might set <tt>Time.zone</tt> on a per request basis and reset it when the request is done.
-
# <tt>current_user.time_zone</tt> just needs to return a string identifying the user's preferred time zone:
-
#
-
# class ApplicationController < ActionController::Base
-
# around_filter :set_time_zone
-
#
-
# def set_time_zone
-
# if logged_in?
-
# Time.use_zone(current_user.time_zone) { yield }
-
# else
-
# yield
-
# end
-
# end
-
# end
-
1
def zone=(time_zone)
-
Thread.current[:time_zone] = find_zone!(time_zone)
-
end
-
-
# Allows override of <tt>Time.zone</tt> locally inside supplied block; resets <tt>Time.zone</tt> to existing value when done.
-
1
def use_zone(time_zone)
-
new_zone = find_zone!(time_zone)
-
begin
-
old_zone, ::Time.zone = ::Time.zone, new_zone
-
yield
-
ensure
-
::Time.zone = old_zone
-
end
-
end
-
-
# Returns a TimeZone instance or nil, or raises an ArgumentError for invalid timezones.
-
1
def find_zone!(time_zone)
-
1
if !time_zone || time_zone.is_a?(ActiveSupport::TimeZone)
-
time_zone
-
else
-
# lookup timezone based on identifier (unless we've been passed a TZInfo::Timezone)
-
1
unless time_zone.respond_to?(:period_for_local)
-
1
time_zone = ActiveSupport::TimeZone[time_zone] || TZInfo::Timezone.get(time_zone)
-
end
-
-
# Return if a TimeZone instance, or wrap in a TimeZone instance if a TZInfo::Timezone
-
1
if time_zone.is_a?(ActiveSupport::TimeZone)
-
1
time_zone
-
else
-
ActiveSupport::TimeZone.create(time_zone.name, nil, time_zone)
-
end
-
end
-
rescue TZInfo::InvalidTimezoneIdentifier
-
raise ArgumentError, "Invalid Timezone: #{time_zone}"
-
end
-
-
1
def find_zone(time_zone)
-
find_zone!(time_zone) rescue nil
-
end
-
end
-
end
-
# encoding: utf-8
-
-
1
require 'uri'
-
1
str = "\xE6\x97\xA5\xE6\x9C\xAC\xE8\xAA\x9E" # Ni-ho-nn-go in UTF-8, means Japanese.
-
1
parser = URI::Parser.new
-
-
1
unless str == parser.unescape(parser.escape(str))
-
1
URI::Parser.class_eval do
-
1
remove_method :unescape
-
1
def unescape(str, escaped = /%[a-fA-F\d]{2}/)
-
# TODO: Are we actually sure that ASCII == UTF-8?
-
# YK: My initial experiments say yes, but let's be sure please
-
enc = str.encoding
-
enc = Encoding::UTF_8 if enc == Encoding::US_ASCII
-
str.gsub(escaped) { [$&[1, 2].hex].pack('C') }.force_encoding(enc)
-
end
-
end
-
end
-
-
1
module URI
-
1
class << self
-
1
def parser
-
73
@parser ||= URI::Parser.new
-
end
-
end
-
end
-
1
require 'set'
-
1
require 'thread'
-
1
require 'thread_safe'
-
1
require 'pathname'
-
1
require 'active_support/core_ext/module/aliasing'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/module/introspection'
-
1
require 'active_support/core_ext/module/anonymous'
-
1
require 'active_support/core_ext/module/qualified_const'
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'active_support/core_ext/kernel/reporting'
-
1
require 'active_support/core_ext/load_error'
-
1
require 'active_support/core_ext/name_error'
-
1
require 'active_support/core_ext/string/starts_ends_with'
-
1
require 'active_support/inflector'
-
-
1
module ActiveSupport #:nodoc:
-
1
module Dependencies #:nodoc:
-
1
extend self
-
-
# Should we turn on Ruby warnings on the first load of dependent files?
-
1
mattr_accessor :warnings_on_first_load
-
1
self.warnings_on_first_load = false
-
-
# All files ever loaded.
-
1
mattr_accessor :history
-
1
self.history = Set.new
-
-
# All files currently loaded.
-
1
mattr_accessor :loaded
-
1
self.loaded = Set.new
-
-
# Should we load files or require them?
-
1
mattr_accessor :mechanism
-
1
self.mechanism = ENV['NO_RELOAD'] ? :require : :load
-
-
# The set of directories from which we may automatically load files. Files
-
# under these directories will be reloaded on each request in development mode,
-
# unless the directory also appears in autoload_once_paths.
-
1
mattr_accessor :autoload_paths
-
1
self.autoload_paths = []
-
-
# The set of directories from which automatically loaded constants are loaded
-
# only once. All directories in this set must also be present in +autoload_paths+.
-
1
mattr_accessor :autoload_once_paths
-
1
self.autoload_once_paths = []
-
-
# An array of qualified constant names that have been loaded. Adding a name
-
# to this array will cause it to be unloaded the next time Dependencies are
-
# cleared.
-
1
mattr_accessor :autoloaded_constants
-
1
self.autoloaded_constants = []
-
-
# An array of constant names that need to be unloaded on every request. Used
-
# to allow arbitrary constants to be marked for unloading.
-
1
mattr_accessor :explicitly_unloadable_constants
-
1
self.explicitly_unloadable_constants = []
-
-
# The logger is used for generating information on the action run-time
-
# (including benchmarking) if available. Can be set to nil for no logging.
-
# Compatible with both Ruby's own Logger and Log4r loggers.
-
1
mattr_accessor :logger
-
-
# Set to +true+ to enable logging of const_missing and file loads.
-
1
mattr_accessor :log_activity
-
1
self.log_activity = false
-
-
# The WatchStack keeps a stack of the modules being watched as files are
-
# loaded. If a file in the process of being loaded (parent.rb) triggers the
-
# load of another file (child.rb) the stack will ensure that child.rb
-
# handles the new constants.
-
#
-
# If child.rb is being autoloaded, its constants will be added to
-
# autoloaded_constants. If it was being `require`d, they will be discarded.
-
#
-
# This is handled by walking back up the watch stack and adding the constants
-
# found by child.rb to the list of original constants in parent.rb.
-
1
class WatchStack
-
1
include Enumerable
-
-
# @watching is a stack of lists of constants being watched. For instance,
-
# if parent.rb is autoloaded, the stack will look like [[Object]]. If
-
# parent.rb then requires namespace/child.rb, the stack will look like
-
# [[Object], [Namespace]].
-
-
1
def initialize
-
1
@watching = []
-
1
@stack = Hash.new { |h,k| h[k] = [] }
-
end
-
-
1
def each(&block)
-
@stack.each(&block)
-
end
-
-
1
def watching?
-
673
!@watching.empty?
-
end
-
-
# Returns a list of new constants found since the last call to
-
# <tt>watch_namespaces</tt>.
-
1
def new_constants
-
constants = []
-
-
# Grab the list of namespaces that we're looking for new constants under
-
@watching.last.each do |namespace|
-
# Retrieve the constants that were present under the namespace when watch_namespaces
-
# was originally called
-
original_constants = @stack[namespace].last
-
-
mod = Inflector.constantize(namespace) if Dependencies.qualified_const_defined?(namespace)
-
next unless mod.is_a?(Module)
-
-
# Get a list of the constants that were added
-
new_constants = mod.local_constants - original_constants
-
-
# self[namespace] returns an Array of the constants that are being evaluated
-
# for that namespace. For instance, if parent.rb requires child.rb, the first
-
# element of self[Object] will be an Array of the constants that were present
-
# before parent.rb was required. The second element will be an Array of the
-
# constants that were present before child.rb was required.
-
@stack[namespace].each do |namespace_constants|
-
namespace_constants.concat(new_constants)
-
end
-
-
# Normalize the list of new constants, and add them to the list we will return
-
new_constants.each do |suffix|
-
constants << ([namespace, suffix] - ["Object"]).join("::")
-
end
-
end
-
constants
-
ensure
-
# A call to new_constants is always called after a call to watch_namespaces
-
pop_modules(@watching.pop)
-
end
-
-
# Add a set of modules to the watch stack, remembering the initial
-
# constants.
-
1
def watch_namespaces(namespaces)
-
@watching << namespaces.map do |namespace|
-
module_name = Dependencies.to_constant_name(namespace)
-
original_constants = Dependencies.qualified_const_defined?(module_name) ?
-
Inflector.constantize(module_name).local_constants : []
-
-
@stack[module_name] << original_constants
-
module_name
-
end
-
end
-
-
1
private
-
1
def pop_modules(modules)
-
modules.each { |mod| @stack[mod].pop }
-
end
-
end
-
-
# An internal stack used to record which constants are loaded by any block.
-
1
mattr_accessor :constant_watch_stack
-
1
self.constant_watch_stack = WatchStack.new
-
-
# Module includes this module.
-
1
module ModuleConstMissing #:nodoc:
-
1
def self.append_features(base)
-
1
base.class_eval do
-
# Emulate #exclude via an ivar
-
1
return if defined?(@_const_missing) && @_const_missing
-
1
@_const_missing = instance_method(:const_missing)
-
1
remove_method(:const_missing)
-
end
-
1
super
-
end
-
-
1
def self.exclude_from(base)
-
base.class_eval do
-
define_method :const_missing, @_const_missing
-
@_const_missing = nil
-
end
-
end
-
-
1
def const_missing(const_name)
-
3
from_mod = anonymous? ? guess_for_anonymous(const_name) : self
-
3
Dependencies.load_missing_constant(from_mod, const_name)
-
end
-
-
# Dependencies assumes the name of the module reflects the nesting (unless
-
# it can be proven that is not the case), and the path to the file that
-
# defines the constant. Anonymous modules cannot follow these conventions
-
# and we assume therefore the user wants to refer to a top-level constant.
-
1
def guess_for_anonymous(const_name)
-
if Object.const_defined?(const_name)
-
raise NameError, "#{const_name} cannot be autoloaded from an anonymous class or module"
-
else
-
Object
-
end
-
end
-
-
1
def unloadable(const_desc = self)
-
super(const_desc)
-
end
-
end
-
-
# Object includes this module.
-
1
module Loadable #:nodoc:
-
1
def self.exclude_from(base)
-
base.class_eval { define_method(:load, Kernel.instance_method(:load)) }
-
end
-
-
1
def require_or_load(file_name)
-
Dependencies.require_or_load(file_name)
-
end
-
-
# Interprets a file using <tt>mechanism</tt> and marks its defined
-
# constants as autoloaded. <tt>file_name</tt> can be either a string or
-
# respond to <tt>to_path</tt>.
-
#
-
# Use this method in code that absolutely needs a certain constant to be
-
# defined at that point. A typical use case is to make constant name
-
# resolution deterministic for constants with the same relative name in
-
# different namespaces whose evaluation would depend on load order
-
# otherwise.
-
1
def require_dependency(file_name, message = "No such file to load -- %s")
-
16
file_name = file_name.to_path if file_name.respond_to?(:to_path)
-
16
unless file_name.is_a?(String)
-
raise ArgumentError, "the file name must either be a String or implement #to_path -- you passed #{file_name.inspect}"
-
end
-
-
16
Dependencies.depend_on(file_name, message)
-
end
-
-
1
def load_dependency(file)
-
1105
if Dependencies.load? && ActiveSupport::Dependencies.constant_watch_stack.watching?
-
Dependencies.new_constants_in(Object) { yield }
-
else
-
1105
yield
-
end
-
rescue Exception => exception # errors from loading file
-
11
exception.blame_file! file if exception.respond_to? :blame_file!
-
11
raise
-
end
-
-
1
def load(file, wrap = false)
-
9
result = false
-
18
load_dependency(file) { result = super }
-
9
result
-
end
-
-
1
def require(file)
-
1096
result = false
-
2192
load_dependency(file) { result = super }
-
1085
result
-
end
-
-
# Mark the given constant as unloadable. Unloadable constants are removed
-
# each time dependencies are cleared.
-
#
-
# Note that marking a constant for unloading need only be done once. Setup
-
# or init scripts may list each unloadable constant that may need unloading;
-
# each constant will be removed for every subsequent clear, as opposed to
-
# for the first clear.
-
#
-
# The provided constant descriptor may be a (non-anonymous) module or class,
-
# or a qualified constant name as a string or symbol.
-
#
-
# Returns +true+ if the constant was not previously marked for unloading,
-
# +false+ otherwise.
-
1
def unloadable(const_desc)
-
Dependencies.mark_for_unload const_desc
-
end
-
end
-
-
# Exception file-blaming.
-
1
module Blamable #:nodoc:
-
1
def blame_file!(file)
-
11
(@blamed_files ||= []).unshift file
-
end
-
-
1
def blamed_files
-
1
@blamed_files ||= []
-
end
-
-
1
def describe_blame
-
return nil if blamed_files.empty?
-
"This error occurred while loading the following files:\n #{blamed_files.join "\n "}"
-
end
-
-
1
def copy_blame!(exc)
-
1
@blamed_files = exc.blamed_files.clone
-
1
self
-
end
-
end
-
-
1
def hook!
-
2
Object.class_eval { include Loadable }
-
2
Module.class_eval { include ModuleConstMissing }
-
2
Exception.class_eval { include Blamable }
-
end
-
-
1
def unhook!
-
ModuleConstMissing.exclude_from(Module)
-
Loadable.exclude_from(Object)
-
end
-
-
1
def load?
-
1123
mechanism == :load
-
end
-
-
1
def depend_on(file_name, message = "No such file to load -- %s.rb")
-
16
path = search_for_file(file_name)
-
16
require_or_load(path || file_name)
-
rescue LoadError => load_error
-
1
if file_name = load_error.message[/ -- (.*?)(\.rb)?$/, 1]
-
1
load_error.message.replace(message % file_name)
-
1
load_error.copy_blame!(load_error)
-
end
-
1
raise
-
end
-
-
1
def clear
-
log_call
-
loaded.clear
-
remove_unloadable_constants!
-
end
-
-
1
def require_or_load(file_name, const_path = nil)
-
18
log_call file_name, const_path
-
18
file_name = $` if file_name =~ /\.rb\z/
-
18
expanded = File.expand_path(file_name)
-
18
return if loaded.include?(expanded)
-
-
# Record that we've seen this file *before* loading it to avoid an
-
# infinite loop with mutual dependencies.
-
18
loaded << expanded
-
-
18
begin
-
18
if load?
-
log "loading #{file_name}"
-
-
# Enable warnings if this file has not been loaded before and
-
# warnings_on_first_load is set.
-
load_args = ["#{file_name}.rb"]
-
load_args << const_path unless const_path.nil?
-
-
if !warnings_on_first_load or history.include?(expanded)
-
result = load_file(*load_args)
-
else
-
enable_warnings { result = load_file(*load_args) }
-
end
-
else
-
18
log "requiring #{file_name}"
-
18
result = require file_name
-
end
-
rescue Exception
-
1
loaded.delete expanded
-
1
raise
-
end
-
-
# Record history *after* loading so first load gets warnings.
-
17
history << expanded
-
17
result
-
end
-
-
# Is the provided constant path defined?
-
1
def qualified_const_defined?(path)
-
3
Object.qualified_const_defined?(path.sub(/^::/, ''), false)
-
end
-
-
# Given +path+, a filesystem path to a ruby file, return an array of
-
# constant paths which would cause Dependencies to attempt to load this
-
# file.
-
1
def loadable_constants_for_path(path, bases = autoload_paths)
-
path = $` if path =~ /\.rb\z/
-
expanded_path = File.expand_path(path)
-
paths = []
-
-
bases.each do |root|
-
expanded_root = File.expand_path(root)
-
next unless %r{\A#{Regexp.escape(expanded_root)}(/|\\)} =~ expanded_path
-
-
nesting = expanded_path[(expanded_root.size)..-1]
-
nesting = nesting[1..-1] if nesting && nesting[0] == ?/
-
next if nesting.blank?
-
-
paths << nesting.camelize
-
end
-
-
paths.uniq!
-
paths
-
end
-
-
# Search for a file in autoload_paths matching the provided suffix.
-
1
def search_for_file(path_suffix)
-
19
path_suffix = path_suffix.sub(/(\.rb)?$/, ".rb")
-
-
19
autoload_paths.each do |root|
-
104
path = File.join(root, path_suffix)
-
104
return path if File.file? path
-
end
-
nil # Gee, I sure wish we had first_match ;-)
-
end
-
-
# Does the provided path_suffix correspond to an autoloadable module?
-
# Instead of returning a boolean, the autoload base for this module is
-
# returned.
-
1
def autoloadable_module?(path_suffix)
-
1
autoload_paths.each do |load_path|
-
15
return load_path if File.directory? File.join(load_path, path_suffix)
-
end
-
nil
-
end
-
-
1
def load_once_path?(path)
-
# to_s works around a ruby1.9 issue where String#starts_with?(Pathname)
-
# will raise a TypeError: no implicit conversion of Pathname into String
-
autoload_once_paths.any? { |base| path.starts_with? base.to_s }
-
end
-
-
# Attempt to autoload the provided module name by searching for a directory
-
# matching the expected path suffix. If found, the module is created and
-
# assigned to +into+'s constants with the name +const_name+. Provided that
-
# the directory was loaded from a reloadable base path, it is added to the
-
# set of constants that are to be unloaded.
-
1
def autoload_module!(into, const_name, qualified_name, path_suffix)
-
1
return nil unless base_path = autoloadable_module?(path_suffix)
-
mod = Module.new
-
into.const_set const_name, mod
-
autoloaded_constants << qualified_name unless autoload_once_paths.include?(base_path)
-
mod
-
end
-
-
# Load the file at the provided path. +const_paths+ is a set of qualified
-
# constant names. When loading the file, Dependencies will watch for the
-
# addition of these constants. Each that is defined will be marked as
-
# autoloaded, and will be removed when Dependencies.clear is next called.
-
#
-
# If the second parameter is left off, then Dependencies will construct a
-
# set of names that the file at +path+ may define. See
-
# +loadable_constants_for_path+ for more details.
-
1
def load_file(path, const_paths = loadable_constants_for_path(path))
-
log_call path, const_paths
-
const_paths = [const_paths].compact unless const_paths.is_a? Array
-
parent_paths = const_paths.collect { |const_path| const_path[/.*(?=::)/] || ::Object }
-
-
result = nil
-
newly_defined_paths = new_constants_in(*parent_paths) do
-
result = Kernel.load path
-
end
-
-
autoloaded_constants.concat newly_defined_paths unless load_once_path?(path)
-
autoloaded_constants.uniq!
-
log "loading #{path} defined #{newly_defined_paths * ', '}" unless newly_defined_paths.empty?
-
result
-
end
-
-
# Returns the constant path for the provided parent and constant name.
-
1
def qualified_name_for(mod, name)
-
3
mod_name = to_constant_name mod
-
3
mod_name == "Object" ? name.to_s : "#{mod_name}::#{name}"
-
end
-
-
# Load the constant named +const_name+ which is missing from +from_mod+. If
-
# it is not possible to load the constant into from_mod, try its parent
-
# module using +const_missing+.
-
1
def load_missing_constant(from_mod, const_name)
-
3
log_call from_mod, const_name
-
-
3
unless qualified_const_defined?(from_mod.name) && Inflector.constantize(from_mod.name).equal?(from_mod)
-
raise ArgumentError, "A copy of #{from_mod} has been removed from the module tree but is still active!"
-
end
-
-
3
qualified_name = qualified_name_for from_mod, const_name
-
3
path_suffix = qualified_name.underscore
-
-
3
file_path = search_for_file(path_suffix)
-
-
3
if file_path
-
2
expanded = File.expand_path(file_path)
-
2
expanded.sub!(/\.rb\z/, '')
-
-
2
if loaded.include?(expanded)
-
raise "Circular dependency detected while autoloading constant #{qualified_name}"
-
else
-
2
require_or_load(expanded, qualified_name)
-
2
raise LoadError, "Unable to autoload constant #{qualified_name}, expected #{file_path} to define it" unless from_mod.const_defined?(const_name, false)
-
2
return from_mod.const_get(const_name)
-
end
-
elsif mod = autoload_module!(from_mod, const_name, qualified_name, path_suffix)
-
return mod
-
1
elsif (parent = from_mod.parent) && parent != from_mod &&
-
1
! from_mod.parents.any? { |p| p.const_defined?(const_name, false) }
-
# If our parents do not have a constant named +const_name+ then we are free
-
# to attempt to load upwards. If they do have such a constant, then this
-
# const_missing must be due to from_mod::const_name, which should not
-
# return constants from from_mod's parents.
-
1
begin
-
# Since Ruby does not pass the nesting at the point the unknown
-
# constant triggered the callback we cannot fully emulate constant
-
# name lookup and need to make a trade-off: we are going to assume
-
# that the nesting in the body of Foo::Bar is [Foo::Bar, Foo] even
-
# though it might not be. Counterexamples are
-
#
-
# class Foo::Bar
-
# Module.nesting # => [Foo::Bar]
-
# end
-
#
-
# or
-
#
-
# module M::N
-
# module S::T
-
# Module.nesting # => [S::T, M::N]
-
# end
-
# end
-
#
-
# for example.
-
1
return parent.const_missing(const_name)
-
rescue NameError => e
-
raise unless e.missing_name? qualified_name_for(parent, const_name)
-
end
-
end
-
-
raise NameError,
-
"uninitialized constant #{qualified_name}",
-
caller.reject { |l| l.starts_with? __FILE__ }
-
end
-
-
# Remove the constants that have been autoloaded, and those that have been
-
# marked for unloading. Before each constant is removed a callback is sent
-
# to its class/module if it implements +before_remove_const+.
-
#
-
# The callback implementation should be restricted to cleaning up caches, etc.
-
# as the environment will be in an inconsistent state, e.g. other constants
-
# may have already been unloaded and not accessible.
-
1
def remove_unloadable_constants!
-
autoloaded_constants.each { |const| remove_constant const }
-
autoloaded_constants.clear
-
Reference.clear!
-
explicitly_unloadable_constants.each { |const| remove_constant const }
-
end
-
-
1
class ClassCache
-
1
def initialize
-
1
@store = ThreadSafe::Cache.new
-
end
-
-
1
def empty?
-
@store.empty?
-
end
-
-
1
def key?(key)
-
@store.key?(key)
-
end
-
-
1
def get(key)
-
5
key = key.name if key.respond_to?(:name)
-
5
@store[key] ||= Inflector.constantize(key)
-
end
-
1
alias :[] :get
-
-
1
def safe_get(key)
-
key = key.name if key.respond_to?(:name)
-
@store[key] ||= Inflector.safe_constantize(key)
-
end
-
-
1
def store(klass)
-
2
return self unless klass.respond_to?(:name)
-
raise(ArgumentError, 'anonymous classes cannot be cached') if klass.name.empty?
-
@store[klass.name] = klass
-
self
-
end
-
-
1
def clear!
-
@store.clear
-
end
-
end
-
-
1
Reference = ClassCache.new
-
-
# Store a reference to a class +klass+.
-
1
def reference(klass)
-
2
Reference.store klass
-
end
-
-
# Get the reference for class named +name+.
-
# Raises an exception if referenced class does not exist.
-
1
def constantize(name)
-
3
Reference.get(name)
-
end
-
-
# Get the reference for class named +name+ if one exists.
-
# Otherwise returns +nil+.
-
1
def safe_constantize(name)
-
Reference.safe_get(name)
-
end
-
-
# Determine if the given constant has been automatically loaded.
-
1
def autoloaded?(desc)
-
return false if desc.is_a?(Module) && desc.anonymous?
-
name = to_constant_name desc
-
return false unless qualified_const_defined? name
-
return autoloaded_constants.include?(name)
-
end
-
-
# Will the provided constant descriptor be unloaded?
-
1
def will_unload?(const_desc)
-
autoloaded?(const_desc) ||
-
explicitly_unloadable_constants.include?(to_constant_name(const_desc))
-
end
-
-
# Mark the provided constant name for unloading. This constant will be
-
# unloaded on each request, not just the next one.
-
1
def mark_for_unload(const_desc)
-
name = to_constant_name const_desc
-
if explicitly_unloadable_constants.include? name
-
false
-
else
-
explicitly_unloadable_constants << name
-
true
-
end
-
end
-
-
# Run the provided block and detect the new constants that were loaded during
-
# its execution. Constants may only be regarded as 'new' once -- so if the
-
# block calls +new_constants_in+ again, then the constants defined within the
-
# inner call will not be reported in this one.
-
#
-
# If the provided block does not run to completion, and instead raises an
-
# exception, any new constants are regarded as being only partially defined
-
# and will be removed immediately.
-
1
def new_constants_in(*descs)
-
log_call(*descs)
-
-
constant_watch_stack.watch_namespaces(descs)
-
aborting = true
-
-
begin
-
yield # Now yield to the code that is to define new constants.
-
aborting = false
-
ensure
-
new_constants = constant_watch_stack.new_constants
-
-
log "New constants: #{new_constants * ', '}"
-
return new_constants unless aborting
-
-
log "Error during loading, removing partially loaded constants "
-
new_constants.each { |c| remove_constant(c) }.clear
-
end
-
-
[]
-
end
-
-
# Convert the provided const desc to a qualified constant name (as a string).
-
# A module, class, symbol, or string may be provided.
-
1
def to_constant_name(desc) #:nodoc:
-
3
case desc
-
when String then desc.sub(/^::/, '')
-
when Symbol then desc.to_s
-
when Module
-
desc.name ||
-
3
raise(ArgumentError, "Anonymous modules have no name to be referenced by")
-
else raise TypeError, "Not a valid constant descriptor: #{desc.inspect}"
-
end
-
end
-
-
1
def remove_constant(const) #:nodoc:
-
# Normalize ::Foo, ::Object::Foo, Object::Foo, Object::Object::Foo, etc. as Foo.
-
normalized = const.to_s.sub(/\A::/, '')
-
normalized.sub!(/\A(Object::)+/, '')
-
-
constants = normalized.split('::')
-
to_remove = constants.pop
-
-
# Remove the file path from the loaded list.
-
file_path = search_for_file(const.underscore)
-
if file_path
-
expanded = File.expand_path(file_path)
-
expanded.sub!(/\.rb\z/, '')
-
self.loaded.delete(expanded)
-
end
-
-
if constants.empty?
-
parent = Object
-
else
-
# This method is robust to non-reachable constants.
-
#
-
# Non-reachable constants may be passed if some of the parents were
-
# autoloaded and already removed. It is easier to do a sanity check
-
# here than require the caller to be clever. We check the parent
-
# rather than the very const argument because we do not want to
-
# trigger Kernel#autoloads, see the comment below.
-
parent_name = constants.join('::')
-
return unless qualified_const_defined?(parent_name)
-
parent = constantize(parent_name)
-
end
-
-
log "removing constant #{const}"
-
-
# In an autoloaded user.rb like this
-
#
-
# autoload :Foo, 'foo'
-
#
-
# class User < ActiveRecord::Base
-
# end
-
#
-
# we correctly register "Foo" as being autoloaded. But if the app does
-
# not use the "Foo" constant we need to be careful not to trigger
-
# loading "foo.rb" ourselves. While #const_defined? and #const_get? do
-
# require the file, #autoload? and #remove_const don't.
-
#
-
# We are going to remove the constant nonetheless ---which exists as
-
# far as Ruby is concerned--- because if the user removes the macro
-
# call from a class or module that were not autoloaded, as in the
-
# example above with Object, accessing to that constant must err.
-
unless parent.autoload?(to_remove)
-
begin
-
constantized = parent.const_get(to_remove, false)
-
rescue NameError
-
log "the constant #{const} is not reachable anymore, skipping"
-
return
-
else
-
constantized.before_remove_const if constantized.respond_to?(:before_remove_const)
-
end
-
end
-
-
begin
-
parent.instance_eval { remove_const to_remove }
-
rescue NameError
-
log "the constant #{const} is not reachable anymore, skipping"
-
end
-
end
-
-
1
protected
-
1
def log_call(*args)
-
21
if log_activity?
-
arg_str = args.collect { |arg| arg.inspect } * ', '
-
/in `([a-z_\?\!]+)'/ =~ caller(1).first
-
selector = $1 || '<unknown>'
-
log "called #{selector}(#{arg_str})"
-
end
-
end
-
-
1
def log(msg)
-
18
logger.debug "Dependencies: #{msg}" if log_activity?
-
end
-
-
1
def log_activity?
-
39
logger && log_activity
-
end
-
end
-
end
-
-
1
ActiveSupport::Dependencies.hook!
-
1
require "active_support/inflector/methods"
-
-
1
module ActiveSupport
-
# Autoload and eager load conveniences for your library.
-
#
-
# This module allows you to define autoloads based on
-
# Rails conventions (i.e. no need to define the path
-
# it is automatically guessed based on the filename)
-
# and also define a set of constants that needs to be
-
# eager loaded:
-
#
-
# module MyLib
-
# extend ActiveSupport::Autoload
-
#
-
# autoload :Model
-
#
-
# eager_autoload do
-
# autoload :Cache
-
# end
-
# end
-
#
-
# Then your library can be eager loaded by simply calling:
-
#
-
# MyLib.eager_load!
-
1
module Autoload
-
1
def self.extended(base) # :nodoc:
-
24
base.class_eval do
-
24
@_autoloads = {}
-
24
@_under_path = nil
-
24
@_at_path = nil
-
24
@_eager_autoload = false
-
end
-
end
-
-
1
def autoload(const_name, path = @_at_path)
-
333
unless path
-
255
full = [name, @_under_path, const_name.to_s].compact.join("::")
-
255
path = Inflector.underscore(full)
-
end
-
-
333
if @_eager_autoload
-
122
@_autoloads[const_name] = path
-
end
-
-
333
super const_name, path
-
end
-
-
1
def autoload_under(path)
-
7
@_under_path, old_path = path, @_under_path
-
7
yield
-
ensure
-
7
@_under_path = old_path
-
end
-
-
1
def autoload_at(path)
-
7
@_at_path, old_path = path, @_at_path
-
7
yield
-
ensure
-
7
@_at_path = old_path
-
end
-
-
1
def eager_autoload
-
16
old_eager, @_eager_autoload = @_eager_autoload, true
-
16
yield
-
ensure
-
16
@_eager_autoload = old_eager
-
end
-
-
1
def eager_load!
-
@_autoloads.values.each { |file| require file }
-
end
-
-
1
def autoloads
-
@_autoloads
-
end
-
end
-
end
-
1
require 'singleton'
-
-
1
module ActiveSupport
-
# \Deprecation specifies the API used by Rails to deprecate methods, instance
-
# variables, objects and constants.
-
1
class Deprecation
-
# active_support.rb sets an autoload for ActiveSupport::Deprecation.
-
#
-
# If these requires were at the top of the file the constant would not be
-
# defined by the time their files were loaded. Since some of them reopen
-
# ActiveSupport::Deprecation its autoload would be triggered, resulting in
-
# a circular require warning for active_support/deprecation.rb.
-
#
-
# So, we define the constant first, and load dependencies later.
-
1
require 'active_support/deprecation/instance_delegator'
-
1
require 'active_support/deprecation/behaviors'
-
1
require 'active_support/deprecation/reporting'
-
1
require 'active_support/deprecation/method_wrappers'
-
1
require 'active_support/deprecation/proxy_wrappers'
-
1
require 'active_support/core_ext/module/deprecation'
-
-
1
include Singleton
-
1
include InstanceDelegator
-
1
include Behavior
-
1
include Reporting
-
1
include MethodWrapper
-
-
# The version number in which the deprecated behavior will be removed, by default.
-
1
attr_accessor :deprecation_horizon
-
-
# It accepts two parameters on initialization. The first is a version of library
-
# and the second is a library name
-
#
-
# ActiveSupport::Deprecation.new('2.0', 'MyLibrary')
-
1
def initialize(deprecation_horizon = '4.2', gem_name = 'Rails')
-
1
self.gem_name = gem_name
-
1
self.deprecation_horizon = deprecation_horizon
-
# By default, warnings are not silenced and debugging is off.
-
1
self.silenced = false
-
1
self.debug = false
-
end
-
end
-
end
-
1
require "active_support/notifications"
-
-
1
module ActiveSupport
-
1
class DeprecationException < StandardError
-
end
-
-
1
class Deprecation
-
# Default warning behaviors per Rails.env.
-
1
DEFAULT_BEHAVIORS = {
-
raise: ->(message, callstack) {
-
e = DeprecationException.new(message)
-
e.set_backtrace(callstack)
-
raise e
-
},
-
-
stderr: ->(message, callstack) {
-
$stderr.puts(message)
-
$stderr.puts callstack.join("\n ") if debug
-
},
-
-
log: ->(message, callstack) {
-
logger =
-
if defined?(Rails) && Rails.logger
-
Rails.logger
-
else
-
require 'active_support/logger'
-
ActiveSupport::Logger.new($stderr)
-
end
-
logger.warn message
-
logger.debug callstack.join("\n ") if debug
-
},
-
-
notify: ->(message, callstack) {
-
ActiveSupport::Notifications.instrument("deprecation.rails",
-
:message => message, :callstack => callstack)
-
},
-
-
silence: ->(message, callstack) {},
-
}
-
-
1
module Behavior
-
# Whether to print a backtrace along with the warning.
-
1
attr_accessor :debug
-
-
# Returns the current behavior or if one isn't set, defaults to +:stderr+.
-
1
def behavior
-
@behavior ||= [DEFAULT_BEHAVIORS[:stderr]]
-
end
-
-
# Sets the behavior to the specified value. Can be a single value, array,
-
# or an object that responds to +call+.
-
#
-
# Available behaviors:
-
#
-
# [+raise+] Raise <tt>ActiveSupport::DeprecationException</tt>.
-
# [+stderr+] Log all deprecation warnings to +$stderr+.
-
# [+log+] Log all deprecation warnings to +Rails.logger+.
-
# [+notify+] Use +ActiveSupport::Notifications+ to notify +deprecation.rails+.
-
# [+silence+] Do nothing.
-
#
-
# Setting behaviors only affects deprecations that happen after boot time.
-
# Deprecation warnings raised by gems are not affected by this setting
-
# because they happen before Rails boots up.
-
#
-
# ActiveSupport::Deprecation.behavior = :stderr
-
# ActiveSupport::Deprecation.behavior = [:stderr, :log]
-
# ActiveSupport::Deprecation.behavior = MyCustomHandler
-
# ActiveSupport::Deprecation.behavior = ->(message, callstack) {
-
# # custom stuff
-
# }
-
1
def behavior=(behavior)
-
2
@behavior = Array(behavior).map { |b| DEFAULT_BEHAVIORS[b] || b }
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/kernel/singleton_class'
-
1
require 'active_support/core_ext/module/delegation'
-
-
1
module ActiveSupport
-
1
class Deprecation
-
1
module InstanceDelegator # :nodoc:
-
1
def self.included(base)
-
1
base.extend(ClassMethods)
-
1
base.public_class_method :new
-
end
-
-
1
module ClassMethods # :nodoc:
-
1
def include(included_module)
-
15
included_module.instance_methods.each { |m| method_added(m) }
-
3
super
-
end
-
-
1
def method_added(method_name)
-
15
singleton_class.delegate(method_name, to: :instance)
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/aliasing'
-
1
require 'active_support/core_ext/array/extract_options'
-
-
1
module ActiveSupport
-
1
class Deprecation
-
1
module MethodWrapper
-
# Declare that a method has been deprecated.
-
#
-
# module Fred
-
# extend self
-
#
-
# def foo; end
-
# def bar; end
-
# def baz; end
-
# end
-
#
-
# ActiveSupport::Deprecation.deprecate_methods(Fred, :foo, bar: :qux, baz: 'use Bar#baz instead')
-
# # => [:foo, :bar, :baz]
-
#
-
# Fred.foo
-
# # => "DEPRECATION WARNING: foo is deprecated and will be removed from Rails 4.1."
-
#
-
# Fred.bar
-
# # => "DEPRECATION WARNING: bar is deprecated and will be removed from Rails 4.1 (use qux instead)."
-
#
-
# Fred.baz
-
# # => "DEPRECATION WARNING: baz is deprecated and will be removed from Rails 4.1 (use Bar#baz instead)."
-
1
def deprecate_methods(target_module, *method_names)
-
options = method_names.extract_options!
-
deprecator = options.delete(:deprecator) || ActiveSupport::Deprecation.instance
-
method_names += options.keys
-
-
method_names.each do |method_name|
-
target_module.alias_method_chain(method_name, :deprecation) do |target, punctuation|
-
target_module.send(:define_method, "#{target}_with_deprecation#{punctuation}") do |*args, &block|
-
deprecator.deprecation_warning(method_name, options[method_name])
-
send(:"#{target}_without_deprecation#{punctuation}", *args, &block)
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/inflector/methods'
-
-
1
module ActiveSupport
-
1
class Deprecation
-
1
class DeprecationProxy #:nodoc:
-
1
def self.new(*args, &block)
-
2
object = args.first
-
-
2
return object unless object
-
2
super
-
end
-
-
86
instance_methods.each { |m| undef_method m unless m =~ /^__|^object_id$/ }
-
-
# Don't give a deprecation warning on inspect since test/unit and error
-
# logs rely on it for diagnostics.
-
1
def inspect
-
target.inspect
-
end
-
-
1
private
-
1
def method_missing(called, *args, &block)
-
warn caller, called, args
-
target.__send__(called, *args, &block)
-
end
-
end
-
-
# This DeprecatedObjectProxy transforms object to deprecated object.
-
#
-
# @old_object = DeprecatedObjectProxy.new(Object.new, "Don't use this object anymore!")
-
# @old_object = DeprecatedObjectProxy.new(Object.new, "Don't use this object anymore!", deprecator_instance)
-
#
-
# When someone executes any method except +inspect+ on proxy object this will
-
# trigger +warn+ method on +deprecator_instance+.
-
#
-
# Default deprecator is <tt>ActiveSupport::Deprecation</tt>
-
1
class DeprecatedObjectProxy < DeprecationProxy
-
1
def initialize(object, message, deprecator = ActiveSupport::Deprecation.instance)
-
@object = object
-
@message = message
-
@deprecator = deprecator
-
end
-
-
1
private
-
1
def target
-
@object
-
end
-
-
1
def warn(callstack, called, args)
-
@deprecator.warn(@message, callstack)
-
end
-
end
-
-
# This DeprecatedInstanceVariableProxy transforms instance variable to
-
# deprecated instance variable.
-
#
-
# class Example
-
# def initialize(deprecator)
-
# @request = ActiveSupport::Deprecation::DeprecatedInstanceVariableProxy.new(self, :request, :@request, deprecator)
-
# @_request = :a_request
-
# end
-
#
-
# def request
-
# @_request
-
# end
-
#
-
# def old_request
-
# @request
-
# end
-
# end
-
#
-
# When someone execute any method on @request variable this will trigger
-
# +warn+ method on +deprecator_instance+ and will fetch <tt>@_request</tt>
-
# variable via +request+ method and execute the same method on non-proxy
-
# instance variable.
-
#
-
# Default deprecator is <tt>ActiveSupport::Deprecation</tt>.
-
1
class DeprecatedInstanceVariableProxy < DeprecationProxy
-
1
def initialize(instance, method, var = "@#{method}", deprecator = ActiveSupport::Deprecation.instance)
-
@instance = instance
-
@method = method
-
@var = var
-
@deprecator = deprecator
-
end
-
-
1
private
-
1
def target
-
@instance.__send__(@method)
-
end
-
-
1
def warn(callstack, called, args)
-
@deprecator.warn("#{@var} is deprecated! Call #{@method}.#{called} instead of #{@var}.#{called}. Args: #{args.inspect}", callstack)
-
end
-
end
-
-
# This DeprecatedConstantProxy transforms constant to deprecated constant.
-
#
-
# OLD_CONST = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('OLD_CONST', 'NEW_CONST')
-
# OLD_CONST = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('OLD_CONST', 'NEW_CONST', deprecator_instance)
-
#
-
# When someone use old constant this will trigger +warn+ method on
-
# +deprecator_instance+.
-
#
-
# Default deprecator is <tt>ActiveSupport::Deprecation</tt>.
-
1
class DeprecatedConstantProxy < DeprecationProxy
-
1
def initialize(old_const, new_const, deprecator = ActiveSupport::Deprecation.instance)
-
2
@old_const = old_const
-
2
@new_const = new_const
-
2
@deprecator = deprecator
-
end
-
-
1
def class
-
target.class
-
end
-
-
1
private
-
1
def target
-
ActiveSupport::Inflector.constantize(@new_const.to_s)
-
end
-
-
1
def warn(callstack, called, args)
-
@deprecator.warn("#{@old_const} is deprecated! Use #{@new_const} instead.", callstack)
-
end
-
end
-
end
-
end
-
1
module ActiveSupport
-
1
class Deprecation
-
1
module Reporting
-
# Whether to print a message (silent mode)
-
1
attr_accessor :silenced
-
# Name of gem where method is deprecated
-
1
attr_accessor :gem_name
-
-
# Outputs a deprecation warning to the output configured by
-
# <tt>ActiveSupport::Deprecation.behavior</tt>.
-
#
-
# ActiveSupport::Deprecation.warn('something broke!')
-
# # => "DEPRECATION WARNING: something broke! (called from your_code.rb:1)"
-
1
def warn(message = nil, callstack = nil)
-
return if silenced
-
-
callstack ||= caller(2)
-
deprecation_message(callstack, message).tap do |m|
-
behavior.each { |b| b.call(m, callstack) }
-
end
-
end
-
-
# Silence deprecation warnings within the block.
-
#
-
# ActiveSupport::Deprecation.warn('something broke!')
-
# # => "DEPRECATION WARNING: something broke! (called from your_code.rb:1)"
-
#
-
# ActiveSupport::Deprecation.silence do
-
# ActiveSupport::Deprecation.warn('something broke!')
-
# end
-
# # => nil
-
1
def silence
-
old_silenced, @silenced = @silenced, true
-
yield
-
ensure
-
@silenced = old_silenced
-
end
-
-
1
def deprecation_warning(deprecated_method_name, message = nil, caller_backtrace = nil)
-
caller_backtrace ||= caller(2)
-
deprecated_method_warning(deprecated_method_name, message).tap do |msg|
-
warn(msg, caller_backtrace)
-
end
-
end
-
-
1
private
-
# Outputs a deprecation warning message
-
#
-
# ActiveSupport::Deprecation.deprecated_method_warning(:method_name)
-
# # => "method_name is deprecated and will be removed from Rails #{deprecation_horizon}"
-
# ActiveSupport::Deprecation.deprecated_method_warning(:method_name, :another_method)
-
# # => "method_name is deprecated and will be removed from Rails #{deprecation_horizon} (use another_method instead)"
-
# ActiveSupport::Deprecation.deprecated_method_warning(:method_name, "Optional message")
-
# # => "method_name is deprecated and will be removed from Rails #{deprecation_horizon} (Optional message)"
-
1
def deprecated_method_warning(method_name, message = nil)
-
warning = "#{method_name} is deprecated and will be removed from #{gem_name} #{deprecation_horizon}"
-
case message
-
when Symbol then "#{warning} (use #{message} instead)"
-
when String then "#{warning} (#{message})"
-
else warning
-
end
-
end
-
-
1
def deprecation_message(callstack, message = nil)
-
message ||= "You are using deprecated behavior which will be removed from the next major or minor release."
-
message += '.' unless message =~ /\.$/
-
"DEPRECATION WARNING: #{message} #{deprecation_caller_message(callstack)}"
-
end
-
-
1
def deprecation_caller_message(callstack)
-
file, line, method = extract_callstack(callstack)
-
if file
-
if line && method
-
"(called from #{method} at #{file}:#{line})"
-
else
-
"(called from #{file}:#{line})"
-
end
-
end
-
end
-
-
1
def extract_callstack(callstack)
-
rails_gem_root = File.expand_path("../../../../..", __FILE__) + "/"
-
offending_line = callstack.find { |line| !line.start_with?(rails_gem_root) } || callstack.first
-
if offending_line
-
if md = offending_line.match(/^(.+?):(\d+)(?::in `(.*?)')?/)
-
md.captures
-
else
-
offending_line
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveSupport
-
# This module provides an internal implementation to track descendants
-
# which is faster than iterating through ObjectSpace.
-
1
module DescendantsTracker
-
1
@@direct_descendants = {}
-
-
1
class << self
-
1
def direct_descendants(klass)
-
@@direct_descendants[klass] || []
-
end
-
-
1
def descendants(klass)
-
72
arr = []
-
72
accumulate_descendants(klass, arr)
-
72
arr
-
end
-
-
1
def clear
-
if defined? ActiveSupport::Dependencies
-
@@direct_descendants.each do |klass, descendants|
-
if ActiveSupport::Dependencies.autoloaded?(klass)
-
@@direct_descendants.delete(klass)
-
else
-
descendants.reject! { |v| ActiveSupport::Dependencies.autoloaded?(v) }
-
end
-
end
-
else
-
@@direct_descendants.clear
-
end
-
end
-
-
# This is the only method that is not thread safe, but is only ever called
-
# during the eager loading phase.
-
1
def store_inherited(klass, descendant)
-
12
(@@direct_descendants[klass] ||= []) << descendant
-
end
-
-
1
private
-
1
def accumulate_descendants(klass, acc)
-
72
if direct_descendants = @@direct_descendants[klass]
-
acc.concat(direct_descendants)
-
direct_descendants.each { |direct_descendant| accumulate_descendants(direct_descendant, acc) }
-
end
-
end
-
end
-
-
1
def inherited(base)
-
12
DescendantsTracker.store_inherited(self, base)
-
12
super
-
end
-
-
1
def direct_descendants
-
DescendantsTracker.direct_descendants(self)
-
end
-
-
1
def descendants
-
1
DescendantsTracker.descendants(self)
-
end
-
end
-
end
-
1
require 'active_support/proxy_object'
-
1
require 'active_support/core_ext/array/conversions'
-
1
require 'active_support/core_ext/object/acts_like'
-
-
1
module ActiveSupport
-
# Provides accurate date and time measurements using Date#advance and
-
# Time#advance, respectively. It mainly supports the methods on Numeric.
-
#
-
# 1.month.ago # equivalent to Time.now.advance(months: -1)
-
1
class Duration < ProxyObject
-
1
attr_accessor :value, :parts
-
-
1
def initialize(value, parts) #:nodoc:
-
9
@value, @parts = value, parts
-
end
-
-
# Adds another Duration or a Numeric to this Duration. Numeric values
-
# are treated as seconds.
-
1
def +(other)
-
if Duration === other
-
Duration.new(value + other.value, @parts + other.parts)
-
else
-
Duration.new(value + other, @parts + [[:seconds, other]])
-
end
-
end
-
-
# Subtracts another Duration or a Numeric from this Duration. Numeric
-
# values are treated as seconds.
-
1
def -(other)
-
self + (-other)
-
end
-
-
1
def -@ #:nodoc:
-
Duration.new(-value, parts.map { |type,number| [type, -number] })
-
end
-
-
1
def is_a?(klass) #:nodoc:
-
Duration == klass || value.is_a?(klass)
-
end
-
1
alias :kind_of? :is_a?
-
-
# Returns +true+ if +other+ is also a Duration instance with the
-
# same +value+, or if <tt>other == value</tt>.
-
1
def ==(other)
-
if Duration === other
-
other.value == value
-
else
-
other == value
-
end
-
end
-
-
1
def self.===(other) #:nodoc:
-
9
other.is_a?(Duration)
-
rescue ::NoMethodError
-
false
-
end
-
-
# Calculates a new Time or Date that is as far in the future
-
# as this Duration represents.
-
1
def since(time = ::Time.current)
-
sum(1, time)
-
end
-
1
alias :from_now :since
-
-
# Calculates a new Time or Date that is as far in the past
-
# as this Duration represents.
-
1
def ago(time = ::Time.current)
-
sum(-1, time)
-
end
-
1
alias :until :ago
-
-
1
def inspect #:nodoc:
-
parts.
-
reduce(::Hash.new(0)) { |h,(l,r)| h[l] += r; h }.
-
sort_by {|unit, _ | [:years, :months, :days, :minutes, :seconds].index(unit)}.
-
map {|unit, val| "#{val} #{val == 1 ? unit.to_s.chop : unit.to_s}"}.
-
to_sentence(:locale => :en)
-
end
-
-
1
def as_json(options = nil) #:nodoc:
-
to_i
-
end
-
-
1
protected
-
-
1
def sum(sign, time = ::Time.current) #:nodoc:
-
parts.inject(time) do |t,(type,number)|
-
if t.acts_like?(:time) || t.acts_like?(:date)
-
if type == :seconds
-
t.since(sign * number)
-
else
-
t.advance(type => sign * number)
-
end
-
else
-
raise ::ArgumentError, "expected a time or date, got #{time.inspect}"
-
end
-
end
-
end
-
-
1
private
-
-
# We define it as a workaround to Ruby 2.0.0-p353 bug.
-
# For more information, check rails/rails#13055.
-
# It should be dropped once a new Ruby patch-level
-
# release after 2.0.0-p353 happens.
-
1
def ===(other) #:nodoc:
-
value === other
-
end
-
-
1
def method_missing(method, *args, &block) #:nodoc:
-
6
value.send(method, *args, &block)
-
end
-
end
-
end
-
1
module ActiveSupport
-
# FileUpdateChecker specifies the API used by Rails to watch files
-
# and control reloading. The API depends on four methods:
-
#
-
# * +initialize+ which expects two parameters and one block as
-
# described below.
-
#
-
# * +updated?+ which returns a boolean if there were updates in
-
# the filesystem or not.
-
#
-
# * +execute+ which executes the given block on initialization
-
# and updates the latest watched files and timestamp.
-
#
-
# * +execute_if_updated+ which just executes the block if it was updated.
-
#
-
# After initialization, a call to +execute_if_updated+ must execute
-
# the block only if there was really a change in the filesystem.
-
#
-
# This class is used by Rails to reload the I18n framework whenever
-
# they are changed upon a new request.
-
#
-
# i18n_reloader = ActiveSupport::FileUpdateChecker.new(paths) do
-
# I18n.reload!
-
# end
-
#
-
# ActionDispatch::Reloader.to_prepare do
-
# i18n_reloader.execute_if_updated
-
# end
-
1
class FileUpdateChecker
-
# It accepts two parameters on initialization. The first is an array
-
# of files and the second is an optional hash of directories. The hash must
-
# have directories as keys and the value is an array of extensions to be
-
# watched under that directory.
-
#
-
# This method must also receive a block that will be called once a path
-
# changes. The array of files and list of directories cannot be changed
-
# after FileUpdateChecker has been initialized.
-
1
def initialize(files, dirs={}, &block)
-
3
@files = files.freeze
-
3
@glob = compile_glob(dirs)
-
3
@block = block
-
-
3
@watched = nil
-
3
@updated_at = nil
-
-
3
@last_watched = watched
-
3
@last_update_at = updated_at(@last_watched)
-
end
-
-
# Check if any of the entries were updated. If so, the watched and/or
-
# updated_at values are cached until the block is executed via +execute+
-
# or +execute_if_updated+.
-
1
def updated?
-
1
current_watched = watched
-
1
if @last_watched.size != current_watched.size
-
@watched = current_watched
-
true
-
else
-
1
current_updated_at = updated_at(current_watched)
-
1
if @last_update_at < current_updated_at
-
@watched = current_watched
-
@updated_at = current_updated_at
-
true
-
else
-
1
false
-
end
-
end
-
end
-
-
# Executes the given block and updates the latest watched files and
-
# timestamp.
-
1
def execute
-
2
@last_watched = watched
-
2
@last_update_at = updated_at(@last_watched)
-
2
@block.call
-
ensure
-
2
@watched = nil
-
2
@updated_at = nil
-
end
-
-
# Execute the block given if updated.
-
1
def execute_if_updated
-
1
if updated?
-
execute
-
true
-
else
-
1
false
-
end
-
end
-
-
1
private
-
-
1
def watched
-
@watched || begin
-
85
all = @files.select { |f| File.exist?(f) }
-
6
all.concat(Dir[@glob]) if @glob
-
6
all
-
6
end
-
end
-
-
1
def updated_at(paths)
-
6
@updated_at || max_mtime(paths) || Time.at(0)
-
end
-
-
# This method returns the maximum mtime of the files in +paths+, or +nil+
-
# if the array is empty.
-
#
-
# Files with a mtime in the future are ignored. Such abnormal situation
-
# can happen for example if the user changes the clock by hand. It is
-
# healthy to consider this edge case because with mtimes in the future
-
# reloading is not triggered.
-
1
def max_mtime(paths)
-
6
time_now = Time.now
-
266
paths.map {|path| File.mtime(path)}.reject {|mtime| time_now < mtime}.max
-
end
-
-
1
def compile_glob(hash)
-
3
hash.freeze # Freeze so changes aren't accidentally pushed
-
3
return if hash.empty?
-
-
1
globs = hash.map do |key, value|
-
15
"#{escape(key)}/**/*#{compile_ext(value)}"
-
end
-
1
"{#{globs.join(",")}}"
-
end
-
-
1
def escape(key)
-
15
key.gsub(',','\,')
-
end
-
-
1
def compile_ext(array)
-
15
array = Array(array)
-
15
return if array.empty?
-
15
".{#{array.join(",")}}"
-
end
-
end
-
end
-
1
module ActiveSupport
-
# Returns the version of the currently loaded ActiveSupport as a <tt>Gem::Version</tt>
-
1
def self.gem_version
-
Gem::Version.new VERSION::STRING
-
end
-
-
1
module VERSION
-
1
MAJOR = 4
-
1
MINOR = 1
-
1
TINY = 0
-
1
PRE = nil
-
-
1
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
-
end
-
end
-
1
require 'active_support/core_ext/hash/keys'
-
-
1
module ActiveSupport
-
# Implements a hash where keys <tt>:foo</tt> and <tt>"foo"</tt> are considered
-
# to be the same.
-
#
-
# rgb = ActiveSupport::HashWithIndifferentAccess.new
-
#
-
# rgb[:black] = '#000000'
-
# rgb[:black] # => '#000000'
-
# rgb['black'] # => '#000000'
-
#
-
# rgb['white'] = '#FFFFFF'
-
# rgb[:white] # => '#FFFFFF'
-
# rgb['white'] # => '#FFFFFF'
-
#
-
# Internally symbols are mapped to strings when used as keys in the entire
-
# writing interface (calling <tt>[]=</tt>, <tt>merge</tt>, etc). This
-
# mapping belongs to the public interface. For example, given:
-
#
-
# hash = ActiveSupport::HashWithIndifferentAccess.new(a: 1)
-
#
-
# You are guaranteed that the key is returned as a string:
-
#
-
# hash.keys # => ["a"]
-
#
-
# Technically other types of keys are accepted:
-
#
-
# hash = ActiveSupport::HashWithIndifferentAccess.new(a: 1)
-
# hash[0] = 0
-
# hash # => {"a"=>1, 0=>0}
-
#
-
# but this class is intended for use cases where strings or symbols are the
-
# expected keys and it is convenient to understand both as the same. For
-
# example the +params+ hash in Ruby on Rails.
-
#
-
# Note that core extensions define <tt>Hash#with_indifferent_access</tt>:
-
#
-
# rgb = { black: '#000000', white: '#FFFFFF' }.with_indifferent_access
-
#
-
# which may be handy.
-
1
class HashWithIndifferentAccess < Hash
-
# Returns +true+ so that <tt>Array#extract_options!</tt> finds members of
-
# this class.
-
1
def extractable_options?
-
true
-
end
-
-
1
def with_indifferent_access
-
dup
-
end
-
-
1
def nested_under_indifferent_access
-
self
-
end
-
-
1
def initialize(constructor = {})
-
if constructor.is_a?(Hash)
-
super()
-
update(constructor)
-
else
-
super(constructor)
-
end
-
end
-
-
1
def default(key = nil)
-
if key.is_a?(Symbol) && include?(key = key.to_s)
-
self[key]
-
else
-
super
-
end
-
end
-
-
1
def self.new_from_hash_copying_default(hash)
-
new(hash).tap do |new_hash|
-
new_hash.default = hash.default
-
end
-
end
-
-
1
def self.[](*args)
-
new.merge!(Hash[*args])
-
end
-
-
1
alias_method :regular_writer, :[]= unless method_defined?(:regular_writer)
-
1
alias_method :regular_update, :update unless method_defined?(:regular_update)
-
-
# Assigns a new value to the hash:
-
#
-
# hash = ActiveSupport::HashWithIndifferentAccess.new
-
# hash[:key] = 'value'
-
#
-
# This value can be later fetched using either +:key+ or +'key'+.
-
1
def []=(key, value)
-
regular_writer(convert_key(key), convert_value(value, for: :assignment))
-
end
-
-
1
alias_method :store, :[]=
-
-
# Updates the receiver in-place, merging in the hash passed as argument:
-
#
-
# hash_1 = ActiveSupport::HashWithIndifferentAccess.new
-
# hash_1[:key] = 'value'
-
#
-
# hash_2 = ActiveSupport::HashWithIndifferentAccess.new
-
# hash_2[:key] = 'New Value!'
-
#
-
# hash_1.update(hash_2) # => {"key"=>"New Value!"}
-
#
-
# The argument can be either an
-
# <tt>ActiveSupport::HashWithIndifferentAccess</tt> or a regular +Hash+.
-
# In either case the merge respects the semantics of indifferent access.
-
#
-
# If the argument is a regular hash with keys +:key+ and +"key"+ only one
-
# of the values end up in the receiver, but which one is unspecified.
-
#
-
# When given a block, the value for duplicated keys will be determined
-
# by the result of invoking the block with the duplicated key, the value
-
# in the receiver, and the value in +other_hash+. The rules for duplicated
-
# keys follow the semantics of indifferent access:
-
#
-
# hash_1[:key] = 10
-
# hash_2['key'] = 12
-
# hash_1.update(hash_2) { |key, old, new| old + new } # => {"key"=>22}
-
1
def update(other_hash)
-
if other_hash.is_a? HashWithIndifferentAccess
-
super(other_hash)
-
else
-
other_hash.each_pair do |key, value|
-
if block_given? && key?(key)
-
value = yield(convert_key(key), self[key], value)
-
end
-
regular_writer(convert_key(key), convert_value(value))
-
end
-
self
-
end
-
end
-
-
1
alias_method :merge!, :update
-
-
# Checks the hash for a key matching the argument passed in:
-
#
-
# hash = ActiveSupport::HashWithIndifferentAccess.new
-
# hash['key'] = 'value'
-
# hash.key?(:key) # => true
-
# hash.key?('key') # => true
-
1
def key?(key)
-
super(convert_key(key))
-
end
-
-
1
alias_method :include?, :key?
-
1
alias_method :has_key?, :key?
-
1
alias_method :member?, :key?
-
-
# Same as <tt>Hash#fetch</tt> where the key passed as argument can be
-
# either a string or a symbol:
-
#
-
# counters = ActiveSupport::HashWithIndifferentAccess.new
-
# counters[:foo] = 1
-
#
-
# counters.fetch('foo') # => 1
-
# counters.fetch(:bar, 0) # => 0
-
# counters.fetch(:bar) { |key| 0 } # => 0
-
# counters.fetch(:zoo) # => KeyError: key not found: "zoo"
-
1
def fetch(key, *extras)
-
super(convert_key(key), *extras)
-
end
-
-
# Returns an array of the values at the specified indices:
-
#
-
# hash = ActiveSupport::HashWithIndifferentAccess.new
-
# hash[:a] = 'x'
-
# hash[:b] = 'y'
-
# hash.values_at('a', 'b') # => ["x", "y"]
-
1
def values_at(*indices)
-
indices.collect { |key| self[convert_key(key)] }
-
end
-
-
# Returns an exact copy of the hash.
-
1
def dup
-
self.class.new(self).tap do |new_hash|
-
new_hash.default = default
-
end
-
end
-
-
# This method has the same semantics of +update+, except it does not
-
# modify the receiver but rather returns a new hash with indifferent
-
# access with the result of the merge.
-
1
def merge(hash, &block)
-
self.dup.update(hash, &block)
-
end
-
-
# Like +merge+ but the other way around: Merges the receiver into the
-
# argument and returns a new hash with indifferent access as result:
-
#
-
# hash = ActiveSupport::HashWithIndifferentAccess.new
-
# hash['a'] = nil
-
# hash.reverse_merge(a: 0, b: 1) # => {"a"=>nil, "b"=>1}
-
1
def reverse_merge(other_hash)
-
super(self.class.new_from_hash_copying_default(other_hash))
-
end
-
-
# Same semantics as +reverse_merge+ but modifies the receiver in-place.
-
1
def reverse_merge!(other_hash)
-
replace(reverse_merge( other_hash ))
-
end
-
-
# Replaces the contents of this hash with other_hash.
-
#
-
# h = { "a" => 100, "b" => 200 }
-
# h.replace({ "c" => 300, "d" => 400 }) # => {"c"=>300, "d"=>400}
-
1
def replace(other_hash)
-
super(self.class.new_from_hash_copying_default(other_hash))
-
end
-
-
# Removes the specified key from the hash.
-
1
def delete(key)
-
super(convert_key(key))
-
end
-
-
1
def stringify_keys!; self end
-
1
def deep_stringify_keys!; self end
-
1
def stringify_keys; dup end
-
1
def deep_stringify_keys; dup end
-
1
undef :symbolize_keys!
-
1
undef :deep_symbolize_keys!
-
1
def symbolize_keys; to_hash.symbolize_keys! end
-
1
def deep_symbolize_keys; to_hash.deep_symbolize_keys! end
-
1
def to_options!; self end
-
-
1
def select(*args, &block)
-
dup.tap { |hash| hash.select!(*args, &block) }
-
end
-
-
1
def reject(*args, &block)
-
dup.tap { |hash| hash.reject!(*args, &block) }
-
end
-
-
# Convert to a regular hash with string keys.
-
1
def to_hash
-
_new_hash= {}
-
each do |key, value|
-
_new_hash[convert_key(key)] = convert_value(value, for: :to_hash)
-
end
-
Hash.new(default).merge!(_new_hash)
-
end
-
-
1
protected
-
1
def convert_key(key)
-
key.kind_of?(Symbol) ? key.to_s : key
-
end
-
-
1
def convert_value(value, options = {})
-
if value.is_a? Hash
-
if options[:for] == :to_hash
-
value.to_hash
-
else
-
value.nested_under_indifferent_access
-
end
-
elsif value.is_a?(Array)
-
unless options[:for] == :assignment
-
value = value.dup
-
end
-
value.map! { |e| convert_value(e, options) }
-
else
-
value
-
end
-
end
-
end
-
end
-
-
1
HashWithIndifferentAccess = ActiveSupport::HashWithIndifferentAccess
-
1
require 'active_support/core_ext/hash/deep_merge'
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/hash/slice'
-
1
begin
-
1
require 'i18n'
-
rescue LoadError => e
-
$stderr.puts "The i18n gem is not available. Please add it to your Gemfile and run bundle install"
-
raise e
-
end
-
1
require 'active_support/lazy_load_hooks'
-
-
1
ActiveSupport.run_load_hooks(:i18n)
-
1
I18n.load_path << "#{File.dirname(__FILE__)}/locale/en.yml"
-
1
require "active_support"
-
1
require "active_support/file_update_checker"
-
1
require "active_support/core_ext/array/wrap"
-
-
1
module I18n
-
1
class Railtie < Rails::Railtie
-
1
config.i18n = ActiveSupport::OrderedOptions.new
-
1
config.i18n.railties_load_path = []
-
1
config.i18n.load_path = []
-
1
config.i18n.fallbacks = ActiveSupport::OrderedOptions.new
-
# Enforce I18n to check the available locales when setting a locale.
-
1
config.i18n.enforce_available_locales = true
-
-
# Set the i18n configuration after initialization since a lot of
-
# configuration is still usually done in application initializers.
-
1
config.after_initialize do |app|
-
1
I18n::Railtie.initialize_i18n(app)
-
end
-
-
# Trigger i18n config before any eager loading has happened
-
# so it's ready if any classes require it when eager loaded.
-
1
config.before_eager_load do |app|
-
I18n::Railtie.initialize_i18n(app)
-
end
-
-
1
protected
-
-
1
@i18n_inited = false
-
-
# Setup i18n configuration.
-
1
def self.initialize_i18n(app)
-
1
return if @i18n_inited
-
-
1
fallbacks = app.config.i18n.delete(:fallbacks)
-
-
# Avoid issues with setting the default_locale by disabling available locales
-
# check while configuring.
-
1
enforce_available_locales = app.config.i18n.delete(:enforce_available_locales)
-
1
enforce_available_locales = I18n.enforce_available_locales unless I18n.enforce_available_locales.nil?
-
1
I18n.enforce_available_locales = false
-
-
1
app.config.i18n.each do |setting, value|
-
2
case setting
-
when :railties_load_path
-
1
app.config.i18n.load_path.unshift(*value)
-
when :load_path
-
1
I18n.load_path += value
-
else
-
I18n.send("#{setting}=", value)
-
end
-
end
-
-
1
init_fallbacks(fallbacks) if fallbacks && validate_fallbacks(fallbacks)
-
-
# Restore available locales check so it will take place from now on.
-
1
I18n.enforce_available_locales = enforce_available_locales
-
-
2
reloader = ActiveSupport::FileUpdateChecker.new(I18n.load_path.dup){ I18n.reload! }
-
1
app.reloaders << reloader
-
1
ActionDispatch::Reloader.to_prepare { reloader.execute_if_updated }
-
1
reloader.execute
-
-
1
@i18n_inited = true
-
end
-
-
1
def self.include_fallbacks_module
-
I18n.backend.class.send(:include, I18n::Backend::Fallbacks)
-
end
-
-
1
def self.init_fallbacks(fallbacks)
-
include_fallbacks_module
-
-
args = case fallbacks
-
when ActiveSupport::OrderedOptions
-
[*(fallbacks[:defaults] || []) << fallbacks[:map]].compact
-
when Hash, Array
-
Array.wrap(fallbacks)
-
else # TrueClass
-
[]
-
end
-
-
I18n.fallbacks = I18n::Locale::Fallbacks.new(*args)
-
end
-
-
1
def self.validate_fallbacks(fallbacks)
-
1
case fallbacks
-
when ActiveSupport::OrderedOptions
-
1
!fallbacks.empty?
-
when TrueClass, Array, Hash
-
true
-
else
-
raise "Unexpected fallback type #{fallbacks.inspect}"
-
end
-
end
-
end
-
end
-
1
require 'active_support/inflector/inflections'
-
-
#--
-
# Defines the standard inflection rules. These are the starting point for
-
# new projects and are not considered complete. The current set of inflection
-
# rules is frozen. This means, we do not change them to become more complete.
-
# This is a safety measure to keep existing applications from breaking.
-
#++
-
1
module ActiveSupport
-
1
Inflector.inflections(:en) do |inflect|
-
1
inflect.plural(/$/, 's')
-
1
inflect.plural(/s$/i, 's')
-
1
inflect.plural(/^(ax|test)is$/i, '\1es')
-
1
inflect.plural(/(octop|vir)us$/i, '\1i')
-
1
inflect.plural(/(octop|vir)i$/i, '\1i')
-
1
inflect.plural(/(alias|status)$/i, '\1es')
-
1
inflect.plural(/(bu)s$/i, '\1ses')
-
1
inflect.plural(/(buffal|tomat)o$/i, '\1oes')
-
1
inflect.plural(/([ti])um$/i, '\1a')
-
1
inflect.plural(/([ti])a$/i, '\1a')
-
1
inflect.plural(/sis$/i, 'ses')
-
1
inflect.plural(/(?:([^f])fe|([lr])f)$/i, '\1\2ves')
-
1
inflect.plural(/(hive)$/i, '\1s')
-
1
inflect.plural(/([^aeiouy]|qu)y$/i, '\1ies')
-
1
inflect.plural(/(x|ch|ss|sh)$/i, '\1es')
-
1
inflect.plural(/(matr|vert|ind)(?:ix|ex)$/i, '\1ices')
-
1
inflect.plural(/^(m|l)ouse$/i, '\1ice')
-
1
inflect.plural(/^(m|l)ice$/i, '\1ice')
-
1
inflect.plural(/^(ox)$/i, '\1en')
-
1
inflect.plural(/^(oxen)$/i, '\1')
-
1
inflect.plural(/(quiz)$/i, '\1zes')
-
-
1
inflect.singular(/s$/i, '')
-
1
inflect.singular(/(ss)$/i, '\1')
-
1
inflect.singular(/(n)ews$/i, '\1ews')
-
1
inflect.singular(/([ti])a$/i, '\1um')
-
1
inflect.singular(/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '\1sis')
-
1
inflect.singular(/(^analy)(sis|ses)$/i, '\1sis')
-
1
inflect.singular(/([^f])ves$/i, '\1fe')
-
1
inflect.singular(/(hive)s$/i, '\1')
-
1
inflect.singular(/(tive)s$/i, '\1')
-
1
inflect.singular(/([lr])ves$/i, '\1f')
-
1
inflect.singular(/([^aeiouy]|qu)ies$/i, '\1y')
-
1
inflect.singular(/(s)eries$/i, '\1eries')
-
1
inflect.singular(/(m)ovies$/i, '\1ovie')
-
1
inflect.singular(/(x|ch|ss|sh)es$/i, '\1')
-
1
inflect.singular(/^(m|l)ice$/i, '\1ouse')
-
1
inflect.singular(/(bus)(es)?$/i, '\1')
-
1
inflect.singular(/(o)es$/i, '\1')
-
1
inflect.singular(/(shoe)s$/i, '\1')
-
1
inflect.singular(/(cris|test)(is|es)$/i, '\1is')
-
1
inflect.singular(/^(a)x[ie]s$/i, '\1xis')
-
1
inflect.singular(/(octop|vir)(us|i)$/i, '\1us')
-
1
inflect.singular(/(alias|status)(es)?$/i, '\1')
-
1
inflect.singular(/^(ox)en/i, '\1')
-
1
inflect.singular(/(vert|ind)ices$/i, '\1ex')
-
1
inflect.singular(/(matr)ices$/i, '\1ix')
-
1
inflect.singular(/(quiz)zes$/i, '\1')
-
1
inflect.singular(/(database)s$/i, '\1')
-
-
1
inflect.irregular('person', 'people')
-
1
inflect.irregular('man', 'men')
-
1
inflect.irregular('child', 'children')
-
1
inflect.irregular('sex', 'sexes')
-
1
inflect.irregular('move', 'moves')
-
1
inflect.irregular('zombie', 'zombies')
-
-
1
inflect.uncountable(%w(equipment information rice money species series fish sheep jeans police))
-
end
-
end
-
# in case active_support/inflector is required without the rest of active_support
-
1
require 'active_support/inflector/inflections'
-
1
require 'active_support/inflector/transliterate'
-
1
require 'active_support/inflector/methods'
-
-
1
require 'active_support/inflections'
-
1
require 'active_support/core_ext/string/inflections'
-
1
require 'thread_safe'
-
1
require 'active_support/core_ext/array/prepend_and_append'
-
1
require 'active_support/i18n'
-
-
1
module ActiveSupport
-
1
module Inflector
-
1
extend self
-
-
# A singleton instance of this class is yielded by Inflector.inflections,
-
# which can then be used to specify additional inflection rules. If passed
-
# an optional locale, rules for other languages can be specified. The
-
# default locale is <tt>:en</tt>. Only rules for English are provided.
-
#
-
# ActiveSupport::Inflector.inflections(:en) do |inflect|
-
# inflect.plural /^(ox)$/i, '\1\2en'
-
# inflect.singular /^(ox)en/i, '\1'
-
#
-
# inflect.irregular 'octopus', 'octopi'
-
#
-
# inflect.uncountable 'equipment'
-
# end
-
#
-
# New rules are added at the top. So in the example above, the irregular
-
# rule for octopus will now be the first of the pluralization and
-
# singularization rules that is runs. This guarantees that your rules run
-
# before any of the rules that may already have been loaded.
-
1
class Inflections
-
1
@__instance__ = ThreadSafe::Cache.new
-
-
1
def self.instance(locale = :en)
-
557
@__instance__[locale] ||= new
-
end
-
-
1
attr_reader :plurals, :singulars, :uncountables, :humans, :acronyms, :acronym_regex
-
-
1
def initialize
-
1
@plurals, @singulars, @uncountables, @humans, @acronyms, @acronym_regex = [], [], [], [], {}, /(?=a)b/
-
end
-
-
# Private, for the test suite.
-
1
def initialize_dup(orig) # :nodoc:
-
%w(plurals singulars uncountables humans acronyms acronym_regex).each do |scope|
-
instance_variable_set("@#{scope}", orig.send(scope).dup)
-
end
-
end
-
-
# Specifies a new acronym. An acronym must be specified as it will appear
-
# in a camelized string. An underscore string that contains the acronym
-
# will retain the acronym when passed to +camelize+, +humanize+, or
-
# +titleize+. A camelized string that contains the acronym will maintain
-
# the acronym when titleized or humanized, and will convert the acronym
-
# into a non-delimited single lowercase word when passed to +underscore+.
-
#
-
# acronym 'HTML'
-
# titleize 'html' # => 'HTML'
-
# camelize 'html' # => 'HTML'
-
# underscore 'MyHTML' # => 'my_html'
-
#
-
# The acronym, however, must occur as a delimited unit and not be part of
-
# another word for conversions to recognize it:
-
#
-
# acronym 'HTTP'
-
# camelize 'my_http_delimited' # => 'MyHTTPDelimited'
-
# camelize 'https' # => 'Https', not 'HTTPs'
-
# underscore 'HTTPS' # => 'http_s', not 'https'
-
#
-
# acronym 'HTTPS'
-
# camelize 'https' # => 'HTTPS'
-
# underscore 'HTTPS' # => 'https'
-
#
-
# Note: Acronyms that are passed to +pluralize+ will no longer be
-
# recognized, since the acronym will not occur as a delimited unit in the
-
# pluralized result. To work around this, you must specify the pluralized
-
# form as an acronym as well:
-
#
-
# acronym 'API'
-
# camelize(pluralize('api')) # => 'Apis'
-
#
-
# acronym 'APIs'
-
# camelize(pluralize('api')) # => 'APIs'
-
#
-
# +acronym+ may be used to specify any word that contains an acronym or
-
# otherwise needs to maintain a non-standard capitalization. The only
-
# restriction is that the word must begin with a capital letter.
-
#
-
# acronym 'RESTful'
-
# underscore 'RESTful' # => 'restful'
-
# underscore 'RESTfulController' # => 'restful_controller'
-
# titleize 'RESTfulController' # => 'RESTful Controller'
-
# camelize 'restful' # => 'RESTful'
-
# camelize 'restful_controller' # => 'RESTfulController'
-
#
-
# acronym 'McDonald'
-
# underscore 'McDonald' # => 'mcdonald'
-
# camelize 'mcdonald' # => 'McDonald'
-
1
def acronym(word)
-
@acronyms[word.downcase] = word
-
@acronym_regex = /#{@acronyms.values.join("|")}/
-
end
-
-
# Specifies a new pluralization rule and its replacement. The rule can
-
# either be a string or a regular expression. The replacement should
-
# always be a string that may include references to the matched data from
-
# the rule.
-
1
def plural(rule, replacement)
-
33
@uncountables.delete(rule) if rule.is_a?(String)
-
33
@uncountables.delete(replacement)
-
33
@plurals.prepend([rule, replacement])
-
end
-
-
# Specifies a new singularization rule and its replacement. The rule can
-
# either be a string or a regular expression. The replacement should
-
# always be a string that may include references to the matched data from
-
# the rule.
-
1
def singular(rule, replacement)
-
39
@uncountables.delete(rule) if rule.is_a?(String)
-
39
@uncountables.delete(replacement)
-
39
@singulars.prepend([rule, replacement])
-
end
-
-
# Specifies a new irregular that applies to both pluralization and
-
# singularization at the same time. This can only be used for strings, not
-
# regular expressions. You simply pass the irregular in singular and
-
# plural form.
-
#
-
# irregular 'octopus', 'octopi'
-
# irregular 'person', 'people'
-
1
def irregular(singular, plural)
-
6
@uncountables.delete(singular)
-
6
@uncountables.delete(plural)
-
-
6
s0 = singular[0]
-
6
srest = singular[1..-1]
-
-
6
p0 = plural[0]
-
6
prest = plural[1..-1]
-
-
6
if s0.upcase == p0.upcase
-
6
plural(/(#{s0})#{srest}$/i, '\1' + prest)
-
6
plural(/(#{p0})#{prest}$/i, '\1' + prest)
-
-
6
singular(/(#{s0})#{srest}$/i, '\1' + srest)
-
6
singular(/(#{p0})#{prest}$/i, '\1' + srest)
-
else
-
plural(/#{s0.upcase}(?i)#{srest}$/, p0.upcase + prest)
-
plural(/#{s0.downcase}(?i)#{srest}$/, p0.downcase + prest)
-
plural(/#{p0.upcase}(?i)#{prest}$/, p0.upcase + prest)
-
plural(/#{p0.downcase}(?i)#{prest}$/, p0.downcase + prest)
-
-
singular(/#{s0.upcase}(?i)#{srest}$/, s0.upcase + srest)
-
singular(/#{s0.downcase}(?i)#{srest}$/, s0.downcase + srest)
-
singular(/#{p0.upcase}(?i)#{prest}$/, s0.upcase + srest)
-
singular(/#{p0.downcase}(?i)#{prest}$/, s0.downcase + srest)
-
end
-
end
-
-
# Add uncountable words that shouldn't be attempted inflected.
-
#
-
# uncountable 'money'
-
# uncountable 'money', 'information'
-
# uncountable %w( money information rice )
-
1
def uncountable(*words)
-
1
(@uncountables << words).flatten!
-
end
-
-
# Specifies a humanized form of a string by a regular expression rule or
-
# by a string mapping. When using a regular expression based replacement,
-
# the normal humanize formatting is called after the replacement. When a
-
# string is used, the human form should be specified as desired (example:
-
# 'The name', not 'the_name').
-
#
-
# human /_cnt$/i, '\1_count'
-
# human 'legacy_col_person_name', 'Name'
-
1
def human(rule, replacement)
-
@humans.prepend([rule, replacement])
-
end
-
-
# Clears the loaded inflections within a given scope (default is
-
# <tt>:all</tt>). Give the scope as a symbol of the inflection type, the
-
# options are: <tt>:plurals</tt>, <tt>:singulars</tt>, <tt>:uncountables</tt>,
-
# <tt>:humans</tt>.
-
#
-
# clear :all
-
# clear :plurals
-
1
def clear(scope = :all)
-
case scope
-
when :all
-
@plurals, @singulars, @uncountables, @humans = [], [], [], []
-
else
-
instance_variable_set "@#{scope}", []
-
end
-
end
-
end
-
-
# Yields a singleton instance of Inflector::Inflections so you can specify
-
# additional inflector rules. If passed an optional locale, rules for other
-
# languages can be specified. If not specified, defaults to <tt>:en</tt>.
-
# Only rules for English are provided.
-
#
-
# ActiveSupport::Inflector.inflections(:en) do |inflect|
-
# inflect.uncountable 'rails'
-
# end
-
1
def inflections(locale = :en)
-
557
if block_given?
-
1
yield Inflections.instance(locale)
-
else
-
556
Inflections.instance(locale)
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
-
1
require 'active_support/inflections'
-
-
1
module ActiveSupport
-
# The Inflector transforms words from singular to plural, class names to table
-
# names, modularized class names to ones without, and class names to foreign
-
# keys. The default inflections for pluralization, singularization, and
-
# uncountable words are kept in inflections.rb.
-
#
-
# The Rails core team has stated patches for the inflections library will not
-
# be accepted in order to avoid breaking legacy applications which may be
-
# relying on errant inflections. If you discover an incorrect inflection and
-
# require it for your application or wish to define rules for languages other
-
# than English, please correct or add them yourself (explained below).
-
1
module Inflector
-
1
extend self
-
-
# Returns the plural form of the word in the string.
-
#
-
# If passed an optional +locale+ parameter, the word will be
-
# pluralized using rules defined for that language. By default,
-
# this parameter is set to <tt>:en</tt>.
-
#
-
# 'post'.pluralize # => "posts"
-
# 'octopus'.pluralize # => "octopi"
-
# 'sheep'.pluralize # => "sheep"
-
# 'words'.pluralize # => "words"
-
# 'CamelOctopus'.pluralize # => "CamelOctopi"
-
# 'ley'.pluralize(:es) # => "leyes"
-
1
def pluralize(word, locale = :en)
-
8
apply_inflections(word, inflections(locale).plurals)
-
end
-
-
# The reverse of +pluralize+, returns the singular form of a word in a
-
# string.
-
#
-
# If passed an optional +locale+ parameter, the word will be
-
# singularized using rules defined for that language. By default,
-
# this parameter is set to <tt>:en</tt>.
-
#
-
# 'posts'.singularize # => "post"
-
# 'octopi'.singularize # => "octopus"
-
# 'sheep'.singularize # => "sheep"
-
# 'word'.singularize # => "word"
-
# 'CamelOctopi'.singularize # => "CamelOctopus"
-
# 'leyes'.singularize(:es) # => "ley"
-
1
def singularize(word, locale = :en)
-
38
apply_inflections(word, inflections(locale).singulars)
-
end
-
-
# By default, +camelize+ converts strings to UpperCamelCase. If the argument
-
# to +camelize+ is set to <tt>:lower</tt> then +camelize+ produces
-
# lowerCamelCase.
-
#
-
# +camelize+ will also convert '/' to '::' which is useful for converting
-
# paths to namespaces.
-
#
-
# 'active_model'.camelize # => "ActiveModel"
-
# 'active_model'.camelize(:lower) # => "activeModel"
-
# 'active_model/errors'.camelize # => "ActiveModel::Errors"
-
# 'active_model/errors'.camelize(:lower) # => "activeModel::Errors"
-
#
-
# As a rule of thumb you can think of +camelize+ as the inverse of
-
# +underscore+, though there are cases where that does not hold:
-
#
-
# 'SSLError'.underscore.camelize # => "SslError"
-
1
def camelize(term, uppercase_first_letter = true)
-
59
string = term.to_s
-
59
if uppercase_first_letter
-
118
string = string.sub(/^[a-z\d]*/) { inflections.acronyms[$&] || $&.capitalize }
-
else
-
string = string.sub(/^(?:#{inflections.acronym_regex}(?=\b|[A-Z_])|\w)/) { $&.downcase }
-
end
-
122
string.gsub!(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{inflections.acronyms[$2] || $2.capitalize}" }
-
59
string.gsub!('/', '::')
-
59
string
-
end
-
-
# Makes an underscored, lowercase form from the expression in the string.
-
#
-
# Changes '::' to '/' to convert namespaces to paths.
-
#
-
# 'ActiveModel'.underscore # => "active_model"
-
# 'ActiveModel::Errors'.underscore # => "active_model/errors"
-
#
-
# As a rule of thumb you can think of +underscore+ as the inverse of
-
# +camelize+, though there are cases where that does not hold:
-
#
-
# 'SSLError'.underscore.camelize # => "SslError"
-
1
def underscore(camel_cased_word)
-
311
word = camel_cased_word.to_s.gsub('::', '/')
-
311
word.gsub!(/(?:([A-Za-z\d])|^)(#{inflections.acronym_regex})(?=\b|[^a-z])/) { "#{$1}#{$1 && '_'}#{$2.downcase}" }
-
311
word.gsub!(/([A-Z\d]+)([A-Z][a-z])/,'\1_\2')
-
311
word.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
-
311
word.tr!("-", "_")
-
311
word.downcase!
-
311
word
-
end
-
-
# Capitalizes the first word, turns underscores into spaces, and strips a
-
# trailing '_id' if present.
-
# Like +titleize+, this is meant for creating pretty output.
-
#
-
# The capitalization of the first word can be turned off by setting the
-
# optional parameter +capitalize+ to false.
-
# By default, this parameter is true.
-
#
-
# humanize('employee_salary') # => "Employee salary"
-
# humanize('author_id') # => "Author"
-
# humanize('author_id', capitalize: false) # => "author"
-
1
def humanize(lower_case_and_underscored_word, options = {})
-
6
result = lower_case_and_underscored_word.to_s.dup
-
6
inflections.humans.each { |(rule, replacement)| break if result.sub!(rule, replacement) }
-
6
result.gsub!(/_id$/, "")
-
6
result.tr!('_', ' ')
-
6
result.gsub!(/([a-z\d]*)/i) { |match|
-
25
"#{inflections.acronyms[match] || match.downcase}"
-
}
-
12
result.gsub!(/^\w/) { |match| match.upcase } if options.fetch(:capitalize, true)
-
6
result
-
end
-
-
# Capitalizes all the words and replaces some characters in the string to
-
# create a nicer looking title. +titleize+ is meant for creating pretty
-
# output. It is not used in the Rails internals.
-
#
-
# +titleize+ is also aliased as +titlecase+.
-
#
-
# 'man from the boondocks'.titleize # => "Man From The Boondocks"
-
# 'x-men: the last stand'.titleize # => "X Men: The Last Stand"
-
# 'TheManWithoutAPast'.titleize # => "The Man Without A Past"
-
# 'raiders_of_the_lost_ark'.titleize # => "Raiders Of The Lost Ark"
-
1
def titleize(word)
-
humanize(underscore(word)).gsub(/\b(?<!['’`])[a-z]/) { $&.capitalize }
-
end
-
-
# Create the name of a table like Rails does for models to table names. This
-
# method uses the +pluralize+ method on the last word in the string.
-
#
-
# 'RawScaledScorer'.tableize # => "raw_scaled_scorers"
-
# 'egg_and_ham'.tableize # => "egg_and_hams"
-
# 'fancyCategory'.tableize # => "fancy_categories"
-
1
def tableize(class_name)
-
pluralize(underscore(class_name))
-
end
-
-
# Create a class name from a plural table name like Rails does for table
-
# names to models. Note that this returns a string and not a Class (To
-
# convert to an actual class follow +classify+ with +constantize+).
-
#
-
# 'egg_and_hams'.classify # => "EggAndHam"
-
# 'posts'.classify # => "Post"
-
#
-
# Singular names are not handled correctly:
-
#
-
# 'business'.classify # => "Busines"
-
1
def classify(table_name)
-
# strip out any leading schema name
-
12
camelize(singularize(table_name.to_s.sub(/.*\./, '')))
-
end
-
-
# Replaces underscores with dashes in the string.
-
#
-
# 'puni_puni'.dasherize # => "puni-puni"
-
1
def dasherize(underscored_word)
-
72
underscored_word.tr('_', '-')
-
end
-
-
# Removes the module part from the expression in the string.
-
#
-
# 'ActiveRecord::CoreExtensions::String::Inflections'.demodulize # => "Inflections"
-
# 'Inflections'.demodulize # => "Inflections"
-
#
-
# See also +deconstantize+.
-
1
def demodulize(path)
-
path = path.to_s
-
if i = path.rindex('::')
-
path[(i+2)..-1]
-
else
-
path
-
end
-
end
-
-
# Removes the rightmost segment from the constant expression in the string.
-
#
-
# 'Net::HTTP'.deconstantize # => "Net"
-
# '::Net::HTTP'.deconstantize # => "::Net"
-
# 'String'.deconstantize # => ""
-
# '::String'.deconstantize # => ""
-
# ''.deconstantize # => ""
-
#
-
# See also +demodulize+.
-
1
def deconstantize(path)
-
path.to_s[0, path.rindex('::') || 0] # implementation based on the one in facets' Module#spacename
-
end
-
-
# Creates a foreign key name from a class name.
-
# +separate_class_name_and_id_with_underscore+ sets whether
-
# the method should put '_' between the name and 'id'.
-
#
-
# 'Message'.foreign_key # => "message_id"
-
# 'Message'.foreign_key(false) # => "messageid"
-
# 'Admin::Post'.foreign_key # => "post_id"
-
1
def foreign_key(class_name, separate_class_name_and_id_with_underscore = true)
-
underscore(demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? "_id" : "id")
-
end
-
-
# Tries to find a constant with the name specified in the argument string.
-
#
-
# 'Module'.constantize # => Module
-
# 'Test::Unit'.constantize # => Test::Unit
-
#
-
# The name is assumed to be the one of a top-level constant, no matter
-
# whether it starts with "::" or not. No lexical context is taken into
-
# account:
-
#
-
# C = 'outside'
-
# module M
-
# C = 'inside'
-
# C # => 'inside'
-
# 'C'.constantize # => 'outside', same as ::C
-
# end
-
#
-
# NameError is raised when the name is not in CamelCase or the constant is
-
# unknown.
-
1
def constantize(camel_cased_word)
-
25
names = camel_cased_word.split('::')
-
-
# Trigger a builtin NameError exception including the ill-formed constant in the message.
-
25
Object.const_get(camel_cased_word) if names.empty?
-
-
# Remove the first blank element in case of '::ClassName' notation.
-
25
names.shift if names.size > 1 && names.first.empty?
-
-
25
names.inject(Object) do |constant, name|
-
32
if constant == Object
-
25
constant.const_get(name)
-
else
-
7
candidate = constant.const_get(name)
-
7
next candidate if constant.const_defined?(name, false)
-
next candidate unless Object.const_defined?(name)
-
-
# Go down the ancestors to check it it's owned
-
# directly before we reach Object or the end of ancestors.
-
constant = constant.ancestors.inject do |const, ancestor|
-
break const if ancestor == Object
-
break ancestor if ancestor.const_defined?(name, false)
-
const
-
end
-
-
# owner is in Object, so raise
-
constant.const_get(name, false)
-
end
-
end
-
end
-
-
# Tries to find a constant with the name specified in the argument string.
-
#
-
# 'Module'.safe_constantize # => Module
-
# 'Test::Unit'.safe_constantize # => Test::Unit
-
#
-
# The name is assumed to be the one of a top-level constant, no matter
-
# whether it starts with "::" or not. No lexical context is taken into
-
# account:
-
#
-
# C = 'outside'
-
# module M
-
# C = 'inside'
-
# C # => 'inside'
-
# 'C'.safe_constantize # => 'outside', same as ::C
-
# end
-
#
-
# +nil+ is returned when the name is not in CamelCase or the constant (or
-
# part of it) is unknown.
-
#
-
# 'blargle'.safe_constantize # => nil
-
# 'UnknownModule'.safe_constantize # => nil
-
# 'UnknownModule::Foo::Bar'.safe_constantize # => nil
-
1
def safe_constantize(camel_cased_word)
-
constantize(camel_cased_word)
-
rescue NameError => e
-
raise unless e.message =~ /(uninitialized constant|wrong constant name) #{const_regexp(camel_cased_word)}$/ ||
-
e.name.to_s == camel_cased_word.to_s
-
rescue ArgumentError => e
-
raise unless e.message =~ /not missing constant #{const_regexp(camel_cased_word)}\!$/
-
end
-
-
# Returns the suffix that should be added to a number to denote the position
-
# in an ordered sequence such as 1st, 2nd, 3rd, 4th.
-
#
-
# ordinal(1) # => "st"
-
# ordinal(2) # => "nd"
-
# ordinal(1002) # => "nd"
-
# ordinal(1003) # => "rd"
-
# ordinal(-11) # => "th"
-
# ordinal(-1021) # => "st"
-
1
def ordinal(number)
-
abs_number = number.to_i.abs
-
-
if (11..13).include?(abs_number % 100)
-
"th"
-
else
-
case abs_number % 10
-
when 1; "st"
-
when 2; "nd"
-
when 3; "rd"
-
else "th"
-
end
-
end
-
end
-
-
# Turns a number into an ordinal string used to denote the position in an
-
# ordered sequence such as 1st, 2nd, 3rd, 4th.
-
#
-
# ordinalize(1) # => "1st"
-
# ordinalize(2) # => "2nd"
-
# ordinalize(1002) # => "1002nd"
-
# ordinalize(1003) # => "1003rd"
-
# ordinalize(-11) # => "-11th"
-
# ordinalize(-1021) # => "-1021st"
-
1
def ordinalize(number)
-
"#{number}#{ordinal(number)}"
-
end
-
-
1
private
-
-
# Mount a regular expression that will match part by part of the constant.
-
#
-
# const_regexp("Foo::Bar::Baz") # => /Foo(::Bar(::Baz)?)?/
-
# const_regexp("::") # => /::/
-
1
def const_regexp(camel_cased_word) #:nodoc:
-
parts = camel_cased_word.split("::")
-
-
return Regexp.escape(camel_cased_word) if parts.blank?
-
-
last = parts.pop
-
-
parts.reverse.inject(last) do |acc, part|
-
part.empty? ? acc : "#{part}(::#{acc})?"
-
end
-
end
-
-
# Applies inflection rules for +singularize+ and +pluralize+.
-
#
-
# apply_inflections('post', inflections.plurals) # => "posts"
-
# apply_inflections('posts', inflections.singulars) # => "post"
-
1
def apply_inflections(word, rules)
-
46
result = word.to_s.dup
-
-
46
if word.empty? || inflections.uncountables.include?(result.downcase[/\b\w+\Z/])
-
result
-
else
-
1665
rules.each { |(rule, replacement)| break if result.sub!(rule, replacement) }
-
46
result
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
1
require 'active_support/core_ext/string/multibyte'
-
1
require 'active_support/i18n'
-
-
1
module ActiveSupport
-
1
module Inflector
-
-
# Replaces non-ASCII characters with an ASCII approximation, or if none
-
# exists, a replacement character which defaults to "?".
-
#
-
# transliterate('Ærøskøbing')
-
# # => "AEroskobing"
-
#
-
# Default approximations are provided for Western/Latin characters,
-
# e.g, "ø", "ñ", "é", "ß", etc.
-
#
-
# This method is I18n aware, so you can set up custom approximations for a
-
# locale. This can be useful, for example, to transliterate German's "ü"
-
# and "ö" to "ue" and "oe", or to add support for transliterating Russian
-
# to ASCII.
-
#
-
# In order to make your custom transliterations available, you must set
-
# them as the <tt>i18n.transliterate.rule</tt> i18n key:
-
#
-
# # Store the transliterations in locales/de.yml
-
# i18n:
-
# transliterate:
-
# rule:
-
# ü: "ue"
-
# ö: "oe"
-
#
-
# # Or set them using Ruby
-
# I18n.backend.store_translations(:de, i18n: {
-
# transliterate: {
-
# rule: {
-
# 'ü' => 'ue',
-
# 'ö' => 'oe'
-
# }
-
# }
-
# })
-
#
-
# The value for <tt>i18n.transliterate.rule</tt> can be a simple Hash that
-
# maps characters to ASCII approximations as shown above, or, for more
-
# complex requirements, a Proc:
-
#
-
# I18n.backend.store_translations(:de, i18n: {
-
# transliterate: {
-
# rule: ->(string) { MyTransliterator.transliterate(string) }
-
# }
-
# })
-
#
-
# Now you can have different transliterations for each locale:
-
#
-
# I18n.locale = :en
-
# transliterate('Jürgen')
-
# # => "Jurgen"
-
#
-
# I18n.locale = :de
-
# transliterate('Jürgen')
-
# # => "Juergen"
-
1
def transliterate(string, replacement = "?")
-
I18n.transliterate(ActiveSupport::Multibyte::Unicode.normalize(
-
ActiveSupport::Multibyte::Unicode.tidy_bytes(string), :c),
-
:replacement => replacement)
-
end
-
-
# Replaces special characters in a string so that it may be used as part of
-
# a 'pretty' URL.
-
#
-
# class Person
-
# def to_param
-
# "#{id}-#{name.parameterize}"
-
# end
-
# end
-
#
-
# @person = Person.find(1)
-
# # => #<Person id: 1, name: "Donald E. Knuth">
-
#
-
# <%= link_to(@person.name, person_path(@person)) %>
-
# # => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a>
-
1
def parameterize(string, sep = '-')
-
# replace accented chars with their ascii equivalents
-
parameterized_string = transliterate(string)
-
# Turn unwanted chars into the separator
-
parameterized_string.gsub!(/[^a-z0-9\-_]+/i, sep)
-
unless sep.nil? || sep.empty?
-
re_sep = Regexp.escape(sep)
-
# No more than one of the separator in a row.
-
parameterized_string.gsub!(/#{re_sep}{2,}/, sep)
-
# Remove leading/trailing separator.
-
parameterized_string.gsub!(/^#{re_sep}|#{re_sep}$/i, '')
-
end
-
parameterized_string.downcase
-
end
-
-
end
-
end
-
1
require 'active_support/json/decoding'
-
1
require 'active_support/json/encoding'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/module/delegation'
-
1
require 'json'
-
-
1
module ActiveSupport
-
# Look for and parse json strings that look like ISO 8601 times.
-
1
mattr_accessor :parse_json_times
-
-
1
module JSON
-
# matches YAML-formatted dates
-
1
DATE_REGEX = /^(?:\d{4}-\d{2}-\d{2}|\d{4}-\d{1,2}-\d{1,2}[T \t]+\d{1,2}:\d{2}:\d{2}(\.[0-9]*)?(([ \t]*)Z|[-+]\d{2}?(:\d{2})?))$/
-
-
1
class << self
-
# Parses a JSON string (JavaScript Object Notation) into a hash.
-
# See www.json.org for more info.
-
#
-
# ActiveSupport::JSON.decode("{\"team\":\"rails\",\"players\":\"36\"}")
-
# => {"team" => "rails", "players" => "36"}
-
1
def decode(json, options = {})
-
if options.present?
-
raise ArgumentError, "In Rails 4.1, ActiveSupport::JSON.decode no longer " \
-
"accepts an options hash for MultiJSON. MultiJSON reached its end of life " \
-
"and has been removed."
-
end
-
-
data = ::JSON.parse(json, quirks_mode: true)
-
-
if ActiveSupport.parse_json_times
-
convert_dates_from(data)
-
else
-
data
-
end
-
end
-
-
# Returns the class of the error that will be raised when there is an
-
# error in decoding JSON. Using this method means you won't directly
-
# depend on the ActiveSupport's JSON implementation, in case it changes
-
# in the future.
-
#
-
# begin
-
# obj = ActiveSupport::JSON.decode(some_string)
-
# rescue ActiveSupport::JSON.parse_error
-
# Rails.logger.warn("Attempted to decode invalid JSON: #{some_string}")
-
# end
-
1
def parse_error
-
::JSON::ParserError
-
end
-
-
1
private
-
-
1
def convert_dates_from(data)
-
case data
-
when nil
-
nil
-
when DATE_REGEX
-
begin
-
DateTime.parse(data)
-
rescue ArgumentError
-
data
-
end
-
when Array
-
data.map! { |d| convert_dates_from(d) }
-
when Hash
-
data.each do |key, value|
-
data[key] = convert_dates_from(value)
-
end
-
else
-
data
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/object/json'
-
1
require 'active_support/core_ext/module/delegation'
-
-
1
module ActiveSupport
-
1
class << self
-
1
delegate :use_standard_json_time_format, :use_standard_json_time_format=,
-
:time_precision, :time_precision=,
-
:escape_html_entities_in_json, :escape_html_entities_in_json=,
-
:encode_big_decimal_as_string, :encode_big_decimal_as_string=,
-
:json_encoder, :json_encoder=,
-
:to => :'ActiveSupport::JSON::Encoding'
-
end
-
-
1
module JSON
-
# Dumps objects in JSON (JavaScript Object Notation).
-
# See www.json.org for more info.
-
#
-
# ActiveSupport::JSON.encode({ team: 'rails', players: '36' })
-
# # => "{\"team\":\"rails\",\"players\":\"36\"}"
-
1
def self.encode(value, options = nil)
-
Encoding.json_encoder.new(options).encode(value)
-
end
-
-
1
module Encoding #:nodoc:
-
1
class JSONGemEncoder #:nodoc:
-
1
attr_reader :options
-
-
1
def initialize(options = nil)
-
@options = options || {}
-
end
-
-
# Encode the given object into a JSON string
-
1
def encode(value)
-
stringify jsonify value.as_json(options.dup)
-
end
-
-
1
private
-
# Rails does more escaping than the JSON gem natively does (we
-
# escape \u2028 and \u2029 and optionally >, <, & to work around
-
# certain browser problems).
-
1
ESCAPED_CHARS = {
-
"\u2028" => '\u2028',
-
"\u2029" => '\u2029',
-
'>' => '\u003e',
-
'<' => '\u003c',
-
'&' => '\u0026',
-
}
-
-
1
ESCAPE_REGEX_WITH_HTML_ENTITIES = /[\u2028\u2029><&]/u
-
1
ESCAPE_REGEX_WITHOUT_HTML_ENTITIES = /[\u2028\u2029]/u
-
-
# This class wraps all the strings we see and does the extra escaping
-
1
class EscapedString < String #:nodoc:
-
1
def to_json(*)
-
if Encoding.escape_html_entities_in_json
-
super.gsub ESCAPE_REGEX_WITH_HTML_ENTITIES, ESCAPED_CHARS
-
else
-
super.gsub ESCAPE_REGEX_WITHOUT_HTML_ENTITIES, ESCAPED_CHARS
-
end
-
end
-
end
-
-
# Mark these as private so we don't leak encoding-specific constructs
-
1
private_constant :ESCAPED_CHARS, :ESCAPE_REGEX_WITH_HTML_ENTITIES,
-
:ESCAPE_REGEX_WITHOUT_HTML_ENTITIES, :EscapedString
-
-
# Convert an object into a "JSON-ready" representation composed of
-
# primitives like Hash, Array, String, Numeric, and true/false/nil.
-
# Recursively calls #as_json to the object to recursively build a
-
# fully JSON-ready object.
-
#
-
# This allows developers to implement #as_json without having to
-
# worry about what base types of objects they are allowed to return
-
# or having to remember to call #as_json recursively.
-
#
-
# Note: the +options+ hash passed to +object.to_json+ is only passed
-
# to +object.as_json+, not any of this method's recursive +#as_json+
-
# calls.
-
1
def jsonify(value)
-
case value
-
when String
-
EscapedString.new(value)
-
when Numeric, NilClass, TrueClass, FalseClass
-
value
-
when Hash
-
Hash[value.map { |k, v| [jsonify(k), jsonify(v)] }]
-
when Array
-
value.map { |v| jsonify(v) }
-
else
-
jsonify value.as_json
-
end
-
end
-
-
# Encode a "jsonified" Ruby data structure using the JSON gem
-
1
def stringify(jsonified)
-
::JSON.generate(jsonified, quirks_mode: true, max_nesting: false)
-
end
-
end
-
-
1
class << self
-
# If true, use ISO 8601 format for dates and times. Otherwise, fall back
-
# to the Active Support legacy format.
-
1
attr_accessor :use_standard_json_time_format
-
-
# If true, encode >, <, & as escaped unicode sequences (e.g. > as \u003e)
-
# as a safety measure.
-
1
attr_accessor :escape_html_entities_in_json
-
-
# Sets the precision of encoded time values.
-
# Defaults to 3 (equivalent to millisecond precision)
-
1
attr_accessor :time_precision
-
-
# Sets the encoder used by Rails to encode Ruby objects into JSON strings
-
# in +Object#to_json+ and +ActiveSupport::JSON.encode+.
-
1
attr_accessor :json_encoder
-
-
1
def encode_big_decimal_as_string=(as_string)
-
message = \
-
"The JSON encoder in Rails 4.1 no longer supports encoding BigDecimals as JSON numbers. Instead, " \
-
"the new encoder will always encode them as strings.\n\n" \
-
"You are seeing this error because you have 'active_support.encode_big_decimal_as_string' in " \
-
"your configuration file. If you have been setting this to true, you can safely remove it from " \
-
"your configuration. Otherwise, you should add the 'activesupport-json_encoder' gem to your " \
-
"Gemfile in order to restore this functionality."
-
-
raise NotImplementedError, message
-
end
-
-
1
def encode_big_decimal_as_string
-
message = \
-
"The JSON encoder in Rails 4.1 no longer supports encoding BigDecimals as JSON numbers. Instead, " \
-
"the new encoder will always encode them as strings.\n\n" \
-
"You are seeing this error because you are trying to check the value of the related configuration, " \
-
"'active_support.encode_big_decimal_as_string'. If your application depends on this option, you should " \
-
"add the 'activesupport-json_encoder' gem to your Gemfile. For now, this option will always be true. " \
-
"In the future, it will be removed from Rails, so you should stop checking its value."
-
-
ActiveSupport::Deprecation.warn message
-
-
true
-
end
-
-
# Deprecate CircularReferenceError
-
1
def const_missing(name)
-
if name == :CircularReferenceError
-
message = "The JSON encoder in Rails 4.1 no longer offers protection from circular references. " \
-
"You are seeing this warning because you are rescuing from (or otherwise referencing) " \
-
"ActiveSupport::Encoding::CircularReferenceError. In the future, this error will be " \
-
"removed from Rails. You should remove these rescue blocks from your code and ensure " \
-
"that your data structures are free of circular references so they can be properly " \
-
"serialized into JSON.\n\n" \
-
"For example, the following Hash contains a circular reference to itself:\n" \
-
" h = {}\n" \
-
" h['circular'] = h\n" \
-
"In this case, calling h.to_json would not work properly."
-
-
ActiveSupport::Deprecation.warn message
-
-
SystemStackError
-
else
-
super
-
end
-
end
-
end
-
-
1
self.use_standard_json_time_format = true
-
1
self.escape_html_entities_in_json = true
-
1
self.json_encoder = JSONGemEncoder
-
1
self.time_precision = 3
-
end
-
end
-
end
-
1
require 'thread_safe'
-
1
require 'openssl'
-
-
1
module ActiveSupport
-
# KeyGenerator is a simple wrapper around OpenSSL's implementation of PBKDF2
-
# It can be used to derive a number of keys for various purposes from a given secret.
-
# This lets Rails applications have a single secure secret, but avoid reusing that
-
# key in multiple incompatible contexts.
-
1
class KeyGenerator
-
1
def initialize(secret, options = {})
-
@secret = secret
-
# The default iterations are higher than required for our key derivation uses
-
# on the off chance someone uses this for password storage
-
@iterations = options[:iterations] || 2**16
-
end
-
-
# Returns a derived key suitable for use. The default key_size is chosen
-
# to be compatible with the default settings of ActiveSupport::MessageVerifier.
-
# i.e. OpenSSL::Digest::SHA1#block_length
-
1
def generate_key(salt, key_size=64)
-
OpenSSL::PKCS5.pbkdf2_hmac_sha1(@secret, salt, @iterations, key_size)
-
end
-
end
-
-
# CachingKeyGenerator is a wrapper around KeyGenerator which allows users to avoid
-
# re-executing the key generation process when it's called using the same salt and
-
# key_size
-
1
class CachingKeyGenerator
-
1
def initialize(key_generator)
-
@key_generator = key_generator
-
@cache_keys = ThreadSafe::Cache.new
-
end
-
-
# Returns a derived key suitable for use. The default key_size is chosen
-
# to be compatible with the default settings of ActiveSupport::MessageVerifier.
-
# i.e. OpenSSL::Digest::SHA1#block_length
-
1
def generate_key(salt, key_size=64)
-
@cache_keys["#{salt}#{key_size}"] ||= @key_generator.generate_key(salt, key_size)
-
end
-
end
-
-
1
class LegacyKeyGenerator # :nodoc:
-
1
SECRET_MIN_LENGTH = 30 # Characters
-
-
1
def initialize(secret)
-
ensure_secret_secure(secret)
-
@secret = secret
-
end
-
-
1
def generate_key(salt)
-
@secret
-
end
-
-
1
private
-
-
# To prevent users from using something insecure like "Password" we make sure that the
-
# secret they've provided is at least 30 characters in length.
-
1
def ensure_secret_secure(secret)
-
if secret.blank?
-
raise ArgumentError, "A secret is required to generate an integrity hash " \
-
"for cookie session data. Set a secret_key_base of at least " \
-
"#{SECRET_MIN_LENGTH} characters in config/secrets.yml."
-
end
-
-
if secret.length < SECRET_MIN_LENGTH
-
raise ArgumentError, "Secret should be something secure, " \
-
"like \"#{SecureRandom.hex(16)}\". The value you " \
-
"provided, \"#{secret}\", is shorter than the minimum length " \
-
"of #{SECRET_MIN_LENGTH} characters."
-
end
-
end
-
end
-
end
-
1
module ActiveSupport
-
# lazy_load_hooks allows Rails to lazily load a lot of components and thus
-
# making the app boot faster. Because of this feature now there is no need to
-
# require <tt>ActiveRecord::Base</tt> at boot time purely to apply
-
# configuration. Instead a hook is registered that applies configuration once
-
# <tt>ActiveRecord::Base</tt> is loaded. Here <tt>ActiveRecord::Base</tt> is
-
# used as example but this feature can be applied elsewhere too.
-
#
-
# Here is an example where +on_load+ method is called to register a hook.
-
#
-
# initializer 'active_record.initialize_timezone' do
-
# ActiveSupport.on_load(:active_record) do
-
# self.time_zone_aware_attributes = true
-
# self.default_timezone = :utc
-
# end
-
# end
-
#
-
# When the entirety of +activerecord/lib/active_record/base.rb+ has been
-
# evaluated then +run_load_hooks+ is invoked. The very last line of
-
# +activerecord/lib/active_record/base.rb+ is:
-
#
-
# ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Base)
-
11
@load_hooks = Hash.new { |h,k| h[k] = [] }
-
11
@loaded = Hash.new { |h,k| h[k] = [] }
-
-
1
def self.on_load(name, options = {}, &block)
-
55
@loaded[name].each do |base|
-
30
execute_hook(base, options, block)
-
end
-
-
55
@load_hooks[name] << [block, options]
-
end
-
-
1
def self.execute_hook(base, options, block)
-
52
if options[:yield]
-
11
block.call(base)
-
else
-
41
base.instance_eval(&block)
-
end
-
end
-
-
1
def self.run_load_hooks(name, base = Object)
-
8
@loaded[name] << base
-
8
@load_hooks[name].each do |hook, options|
-
22
execute_hook(base, options, hook)
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/class/attribute'
-
1
require 'active_support/subscriber'
-
-
1
module ActiveSupport
-
# ActiveSupport::LogSubscriber is an object set to consume
-
# ActiveSupport::Notifications with the sole purpose of logging them.
-
# The log subscriber dispatches notifications to a registered object based
-
# on its given namespace.
-
#
-
# An example would be Active Record log subscriber responsible for logging
-
# queries:
-
#
-
# module ActiveRecord
-
# class LogSubscriber < ActiveSupport::LogSubscriber
-
# def sql(event)
-
# "#{event.payload[:name]} (#{event.duration}) #{event.payload[:sql]}"
-
# end
-
# end
-
# end
-
#
-
# And it's finally registered as:
-
#
-
# ActiveRecord::LogSubscriber.attach_to :active_record
-
#
-
# Since we need to know all instance methods before attaching the log
-
# subscriber, the line above should be called after your
-
# <tt>ActiveRecord::LogSubscriber</tt> definition.
-
#
-
# After configured, whenever a "sql.active_record" notification is published,
-
# it will properly dispatch the event (ActiveSupport::Notifications::Event) to
-
# the sql method.
-
#
-
# Log subscriber also has some helpers to deal with logging and automatically
-
# flushes all logs when the request finishes (via action_dispatch.callback
-
# notification) in a Rails environment.
-
1
class LogSubscriber < Subscriber
-
# Embed in a String to clear all previous ANSI sequences.
-
1
CLEAR = "\e[0m"
-
1
BOLD = "\e[1m"
-
-
# Colors
-
1
BLACK = "\e[30m"
-
1
RED = "\e[31m"
-
1
GREEN = "\e[32m"
-
1
YELLOW = "\e[33m"
-
1
BLUE = "\e[34m"
-
1
MAGENTA = "\e[35m"
-
1
CYAN = "\e[36m"
-
1
WHITE = "\e[37m"
-
-
1
mattr_accessor :colorize_logging
-
1
self.colorize_logging = true
-
-
1
class << self
-
1
def logger
-
@logger ||= if defined?(Rails) && Rails.respond_to?(:logger)
-
Rails.logger
-
end
-
end
-
-
1
attr_writer :logger
-
-
1
def log_subscribers
-
subscribers
-
end
-
-
# Flush all log_subscribers' logger.
-
1
def flush_all!
-
logger.flush if logger.respond_to?(:flush)
-
end
-
end
-
-
1
def logger
-
LogSubscriber.logger
-
end
-
-
1
def start(name, id, payload)
-
9
super if logger
-
end
-
-
1
def finish(name, id, payload)
-
9
super if logger
-
rescue Exception => e
-
logger.error "Could not log #{name.inspect} event. #{e.class}: #{e.message} #{e.backtrace}"
-
end
-
-
1
protected
-
-
1
%w(info debug warn error fatal unknown).each do |level|
-
6
class_eval <<-METHOD, __FILE__, __LINE__ + 1
-
def #{level}(progname = nil, &block)
-
logger.#{level}(progname, &block) if logger
-
end
-
METHOD
-
end
-
-
# Set color by using a string or one of the defined constants. If a third
-
# option is set to +true+, it also adds bold to the string. This is based
-
# on the Highline implementation and will automatically append CLEAR to the
-
# end of the returned String.
-
1
def color(text, color, bold=false)
-
return text unless colorize_logging
-
color = self.class.const_get(color.upcase) if color.is_a?(Symbol)
-
bold = bold ? BOLD : ""
-
"#{bold}#{color}#{text}#{CLEAR}"
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/logger_silence'
-
1
require 'logger'
-
-
1
module ActiveSupport
-
1
class Logger < ::Logger
-
1
include LoggerSilence
-
-
# Broadcasts logs to multiple loggers.
-
1
def self.broadcast(logger) # :nodoc:
-
Module.new do
-
define_method(:add) do |*args, &block|
-
logger.add(*args, &block)
-
super(*args, &block)
-
end
-
-
define_method(:<<) do |x|
-
logger << x
-
super(x)
-
end
-
-
define_method(:close) do
-
logger.close
-
super()
-
end
-
-
define_method(:progname=) do |name|
-
logger.progname = name
-
super(name)
-
end
-
-
define_method(:formatter=) do |formatter|
-
logger.formatter = formatter
-
super(formatter)
-
end
-
-
define_method(:level=) do |level|
-
logger.level = level
-
super(level)
-
end
-
end
-
end
-
-
1
def initialize(*args)
-
1
super
-
1
@formatter = SimpleFormatter.new
-
end
-
-
# Simple formatter which only displays the message.
-
1
class SimpleFormatter < ::Logger::Formatter
-
# This method is invoked when a log event occurs
-
1
def call(severity, timestamp, progname, msg)
-
"#{String === msg ? msg : msg.inspect}\n"
-
end
-
end
-
end
-
end
-
1
require 'active_support/concern'
-
-
1
module LoggerSilence
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
cattr_accessor :silencer
-
1
self.silencer = true
-
end
-
-
# Silences the logger for the duration of the block.
-
1
def silence(temporary_level = Logger::ERROR)
-
if silencer
-
begin
-
old_logger_level, self.level = level, temporary_level
-
yield self
-
ensure
-
self.level = old_logger_level
-
end
-
else
-
yield self
-
end
-
end
-
end
-
1
require 'base64'
-
1
require 'active_support/core_ext/object/blank'
-
-
1
module ActiveSupport
-
# +MessageVerifier+ makes it easy to generate and verify messages which are
-
# signed to prevent tampering.
-
#
-
# This is useful for cases like remember-me tokens and auto-unsubscribe links
-
# where the session store isn't suitable or available.
-
#
-
# Remember Me:
-
# cookies[:remember_me] = @verifier.generate([@user.id, 2.weeks.from_now])
-
#
-
# In the authentication filter:
-
#
-
# id, time = @verifier.verify(cookies[:remember_me])
-
# if time < Time.now
-
# self.current_user = User.find(id)
-
# end
-
#
-
# By default it uses Marshal to serialize the message. If you want to use
-
# another serialization method, you can set the serializer in the options
-
# hash upon initialization:
-
#
-
# @verifier = ActiveSupport::MessageVerifier.new('s3Krit', serializer: YAML)
-
1
class MessageVerifier
-
1
class InvalidSignature < StandardError; end
-
-
1
def initialize(secret, options = {})
-
@secret = secret
-
@digest = options[:digest] || 'SHA1'
-
@serializer = options[:serializer] || Marshal
-
end
-
-
1
def verify(signed_message)
-
raise InvalidSignature if signed_message.blank?
-
-
data, digest = signed_message.split("--")
-
if data.present? && digest.present? && secure_compare(digest, generate_digest(data))
-
begin
-
@serializer.load(::Base64.strict_decode64(data))
-
rescue ArgumentError => argument_error
-
raise InvalidSignature if argument_error.message =~ %r{invalid base64}
-
raise
-
end
-
else
-
raise InvalidSignature
-
end
-
end
-
-
1
def generate(value)
-
data = ::Base64.strict_encode64(@serializer.dump(value))
-
"#{data}--#{generate_digest(data)}"
-
end
-
-
1
private
-
# constant-time comparison algorithm to prevent timing attacks
-
1
def secure_compare(a, b)
-
return false unless a.bytesize == b.bytesize
-
-
l = a.unpack "C#{a.bytesize}"
-
-
res = 0
-
b.each_byte { |byte| res |= byte ^ l.shift }
-
res == 0
-
end
-
-
1
def generate_digest(data)
-
require 'openssl' unless defined?(OpenSSL)
-
OpenSSL::HMAC.hexdigest(OpenSSL::Digest.const_get(@digest).new, @secret, data)
-
end
-
end
-
end
-
1
module ActiveSupport #:nodoc:
-
1
module Multibyte
-
1
autoload :Chars, 'active_support/multibyte/chars'
-
1
autoload :Unicode, 'active_support/multibyte/unicode'
-
-
# The proxy class returned when calling mb_chars. You can use this accessor
-
# to configure your own proxy class so you can support other encodings. See
-
# the ActiveSupport::Multibyte::Chars implementation for an example how to
-
# do this.
-
#
-
# ActiveSupport::Multibyte.proxy_class = CharsForUTF32
-
1
def self.proxy_class=(klass)
-
@proxy_class = klass
-
end
-
-
# Returns the current proxy class.
-
1
def self.proxy_class
-
@proxy_class ||= ActiveSupport::Multibyte::Chars
-
end
-
end
-
end
-
1
require 'active_support/notifications/instrumenter'
-
1
require 'active_support/notifications/fanout'
-
1
require 'active_support/per_thread_registry'
-
-
1
module ActiveSupport
-
# = Notifications
-
#
-
# <tt>ActiveSupport::Notifications</tt> provides an instrumentation API for
-
# Ruby.
-
#
-
# == Instrumenters
-
#
-
# To instrument an event you just need to do:
-
#
-
# ActiveSupport::Notifications.instrument('render', extra: :information) do
-
# render text: 'Foo'
-
# end
-
#
-
# That executes the block first and notifies all subscribers once done.
-
#
-
# In the example above +render+ is the name of the event, and the rest is called
-
# the _payload_. The payload is a mechanism that allows instrumenters to pass
-
# extra information to subscribers. Payloads consist of a hash whose contents
-
# are arbitrary and generally depend on the event.
-
#
-
# == Subscribers
-
#
-
# You can consume those events and the information they provide by registering
-
# a subscriber.
-
#
-
# ActiveSupport::Notifications.subscribe('render') do |name, start, finish, id, payload|
-
# name # => String, name of the event (such as 'render' from above)
-
# start # => Time, when the instrumented block started execution
-
# finish # => Time, when the instrumented block ended execution
-
# id # => String, unique ID for this notification
-
# payload # => Hash, the payload
-
# end
-
#
-
# For instance, let's store all "render" events in an array:
-
#
-
# events = []
-
#
-
# ActiveSupport::Notifications.subscribe('render') do |*args|
-
# events << ActiveSupport::Notifications::Event.new(*args)
-
# end
-
#
-
# That code returns right away, you are just subscribing to "render" events.
-
# The block is saved and will be called whenever someone instruments "render":
-
#
-
# ActiveSupport::Notifications.instrument('render', extra: :information) do
-
# render text: 'Foo'
-
# end
-
#
-
# event = events.first
-
# event.name # => "render"
-
# event.duration # => 10 (in milliseconds)
-
# event.payload # => { extra: :information }
-
#
-
# The block in the <tt>subscribe</tt> call gets the name of the event, start
-
# timestamp, end timestamp, a string with a unique identifier for that event
-
# (something like "535801666f04d0298cd6"), and a hash with the payload, in
-
# that order.
-
#
-
# If an exception happens during that particular instrumentation the payload will
-
# have a key <tt>:exception</tt> with an array of two elements as value: a string with
-
# the name of the exception class, and the exception message.
-
#
-
# As the previous example depicts, the class <tt>ActiveSupport::Notifications::Event</tt>
-
# is able to take the arguments as they come and provide an object-oriented
-
# interface to that data.
-
#
-
# It is also possible to pass an object as the second parameter passed to the
-
# <tt>subscribe</tt> method instead of a block:
-
#
-
# module ActionController
-
# class PageRequest
-
# def call(name, started, finished, unique_id, payload)
-
# Rails.logger.debug ['notification:', name, started, finished, unique_id, payload].join(' ')
-
# end
-
# end
-
# end
-
#
-
# ActiveSupport::Notifications.subscribe('process_action.action_controller', ActionController::PageRequest.new)
-
#
-
# resulting in the following output within the logs including a hash with the payload:
-
#
-
# notification: process_action.action_controller 2012-04-13 01:08:35 +0300 2012-04-13 01:08:35 +0300 af358ed7fab884532ec7 {
-
# controller: "Devise::SessionsController",
-
# action: "new",
-
# params: {"action"=>"new", "controller"=>"devise/sessions"},
-
# format: :html,
-
# method: "GET",
-
# path: "/login/sign_in",
-
# status: 200,
-
# view_runtime: 279.3080806732178,
-
# db_runtime: 40.053
-
# }
-
#
-
# You can also subscribe to all events whose name matches a certain regexp:
-
#
-
# ActiveSupport::Notifications.subscribe(/render/) do |*args|
-
# ...
-
# end
-
#
-
# and even pass no argument to <tt>subscribe</tt>, in which case you are subscribing
-
# to all events.
-
#
-
# == Temporary Subscriptions
-
#
-
# Sometimes you do not want to subscribe to an event for the entire life of
-
# the application. There are two ways to unsubscribe.
-
#
-
# WARNING: The instrumentation framework is designed for long-running subscribers,
-
# use this feature sparingly because it wipes some internal caches and that has
-
# a negative impact on performance.
-
#
-
# === Subscribe While a Block Runs
-
#
-
# You can subscribe to some event temporarily while some block runs. For
-
# example, in
-
#
-
# callback = lambda {|*args| ... }
-
# ActiveSupport::Notifications.subscribed(callback, "sql.active_record") do
-
# ...
-
# end
-
#
-
# the callback will be called for all "sql.active_record" events instrumented
-
# during the execution of the block. The callback is unsubscribed automatically
-
# after that.
-
#
-
# === Manual Unsubscription
-
#
-
# The +subscribe+ method returns a subscriber object:
-
#
-
# subscriber = ActiveSupport::Notifications.subscribe("render") do |*args|
-
# ...
-
# end
-
#
-
# To prevent that block from being called anymore, just unsubscribe passing
-
# that reference:
-
#
-
# ActiveSupport::Notifications.unsubscribe(subscriber)
-
#
-
# == Default Queue
-
#
-
# Notifications ships with a queue implementation that consumes and publishes events
-
# to all log subscribers. You can use any queue implementation you want.
-
#
-
1
module Notifications
-
1
class << self
-
1
attr_accessor :notifier
-
-
1
def publish(name, *args)
-
notifier.publish(name, *args)
-
end
-
-
1
def instrument(name, payload = {})
-
8
if notifier.listening?(name)
-
instrumenter.instrument(name, payload) { yield payload if block_given? }
-
else
-
8
yield payload if block_given?
-
end
-
end
-
-
1
def subscribe(*args, &block)
-
28
notifier.subscribe(*args, &block)
-
end
-
-
1
def subscribed(callback, *args, &block)
-
subscriber = subscribe(*args, &callback)
-
yield
-
ensure
-
unsubscribe(subscriber)
-
end
-
-
1
def unsubscribe(args)
-
notifier.unsubscribe(args)
-
end
-
-
1
def instrumenter
-
1
InstrumentationRegistry.instance.instrumenter_for(notifier)
-
end
-
end
-
-
# This class is a registry which holds all of the +Instrumenter+ objects
-
# in a particular thread local. To access the +Instrumenter+ object for a
-
# particular +notifier+, you can call the following method:
-
#
-
# InstrumentationRegistry.instrumenter_for(notifier)
-
#
-
# The instrumenters for multiple notifiers are held in a single instance of
-
# this class.
-
1
class InstrumentationRegistry # :nodoc:
-
1
extend ActiveSupport::PerThreadRegistry
-
-
1
def initialize
-
1
@registry = {}
-
end
-
-
1
def instrumenter_for(notifier)
-
1
@registry[notifier] ||= Instrumenter.new(notifier)
-
end
-
end
-
-
1
self.notifier = Fanout.new
-
end
-
end
-
1
require 'mutex_m'
-
1
require 'thread_safe'
-
-
1
module ActiveSupport
-
1
module Notifications
-
# This is a default queue implementation that ships with Notifications.
-
# It just pushes events to all registered log subscribers.
-
#
-
# This class is thread safe. All methods are reentrant.
-
1
class Fanout
-
1
include Mutex_m
-
-
1
def initialize
-
1
@subscribers = []
-
1
@listeners_for = ThreadSafe::Cache.new
-
1
super
-
end
-
-
1
def subscribe(pattern = nil, block = Proc.new)
-
28
subscriber = Subscribers.new pattern, block
-
28
synchronize do
-
28
@subscribers << subscriber
-
28
@listeners_for.clear
-
end
-
28
subscriber
-
end
-
-
1
def unsubscribe(subscriber)
-
synchronize do
-
@subscribers.reject! { |s| s.matches?(subscriber) }
-
@listeners_for.clear
-
end
-
end
-
-
1
def start(name, id, payload)
-
27
listeners_for(name).each { |s| s.start(name, id, payload) }
-
end
-
-
1
def finish(name, id, payload)
-
27
listeners_for(name).each { |s| s.finish(name, id, payload) }
-
end
-
-
1
def publish(name, *args)
-
listeners_for(name).each { |s| s.publish(name, *args) }
-
end
-
-
1
def listeners_for(name)
-
# this is correctly done double-checked locking (ThreadSafe::Cache's lookups have volatile semantics)
-
@listeners_for[name] || synchronize do
-
# use synchronisation when accessing @subscribers
-
54
@listeners_for[name] ||= @subscribers.select { |s| s.subscribed_to?(name) }
-
26
end
-
end
-
-
1
def listening?(name)
-
8
listeners_for(name).any?
-
end
-
-
# This is a sync queue, so there is no waiting.
-
1
def wait
-
end
-
-
1
module Subscribers # :nodoc:
-
1
def self.new(pattern, listener)
-
28
if listener.respond_to?(:start) and listener.respond_to?(:finish)
-
28
subscriber = Evented.new pattern, listener
-
else
-
subscriber = Timed.new pattern, listener
-
end
-
-
28
unless pattern
-
AllMessages.new(subscriber)
-
else
-
28
subscriber
-
end
-
end
-
-
1
class Evented #:nodoc:
-
1
def initialize(pattern, delegate)
-
28
@pattern = pattern
-
28
@delegate = delegate
-
28
@can_publish = delegate.respond_to?(:publish)
-
end
-
-
1
def publish(name, *args)
-
if @can_publish
-
@delegate.publish name, *args
-
end
-
end
-
-
1
def start(name, id, payload)
-
18
@delegate.start name, id, payload
-
end
-
-
1
def finish(name, id, payload)
-
18
@delegate.finish name, id, payload
-
end
-
-
1
def subscribed_to?(name)
-
52
@pattern === name.to_s
-
end
-
-
1
def matches?(subscriber_or_name)
-
self === subscriber_or_name ||
-
@pattern && @pattern === subscriber_or_name
-
end
-
end
-
-
1
class Timed < Evented
-
1
def publish(name, *args)
-
@delegate.call name, *args
-
end
-
-
1
def start(name, id, payload)
-
timestack = Thread.current[:_timestack] ||= []
-
timestack.push Time.now
-
end
-
-
1
def finish(name, id, payload)
-
timestack = Thread.current[:_timestack]
-
started = timestack.pop
-
@delegate.call(name, started, Time.now, id, payload)
-
end
-
end
-
-
1
class AllMessages # :nodoc:
-
1
def initialize(delegate)
-
@delegate = delegate
-
end
-
-
1
def start(name, id, payload)
-
@delegate.start name, id, payload
-
end
-
-
1
def finish(name, id, payload)
-
@delegate.finish name, id, payload
-
end
-
-
1
def publish(name, *args)
-
@delegate.publish name, *args
-
end
-
-
1
def subscribed_to?(name)
-
true
-
end
-
-
1
alias :matches? :===
-
end
-
end
-
end
-
end
-
end
-
1
require 'securerandom'
-
-
1
module ActiveSupport
-
1
module Notifications
-
# Instrumenters are stored in a thread local.
-
1
class Instrumenter
-
1
attr_reader :id
-
-
1
def initialize(notifier)
-
1
@id = unique_id
-
1
@notifier = notifier
-
end
-
-
# Instrument the given block by measuring the time taken to execute it
-
# and publish it. Notice that events get sent even if an error occurs
-
# in the passed-in block.
-
1
def instrument(name, payload={})
-
9
start name, payload
-
9
begin
-
9
yield payload
-
rescue Exception => e
-
payload[:exception] = [e.class.name, e.message]
-
raise e
-
ensure
-
9
finish name, payload
-
9
end
-
end
-
-
# Send a start notification with +name+ and +payload+.
-
1
def start(name, payload)
-
9
@notifier.start name, @id, payload
-
end
-
-
# Send a finish notification with +name+ and +payload+.
-
1
def finish(name, payload)
-
9
@notifier.finish name, @id, payload
-
end
-
-
1
private
-
-
1
def unique_id
-
1
SecureRandom.hex(10)
-
end
-
end
-
-
1
class Event
-
1
attr_reader :name, :time, :transaction_id, :payload, :children
-
1
attr_accessor :end
-
-
1
def initialize(name, start, ending, transaction_id, payload)
-
9
@name = name
-
9
@payload = payload.dup
-
9
@time = start
-
9
@transaction_id = transaction_id
-
9
@end = ending
-
9
@children = []
-
9
@duration = nil
-
end
-
-
1
def duration
-
9
@duration ||= 1000.0 * (self.end - time)
-
end
-
-
1
def <<(event)
-
@children << event
-
end
-
-
1
def parent_of?(event)
-
@children.include? event
-
end
-
end
-
end
-
end
-
1
module ActiveSupport
-
1
module NumberHelper
-
1
extend ActiveSupport::Autoload
-
-
1
eager_autoload do
-
1
autoload :NumberConverter
-
1
autoload :NumberToRoundedConverter
-
1
autoload :NumberToDelimitedConverter
-
1
autoload :NumberToHumanConverter
-
1
autoload :NumberToHumanSizeConverter
-
1
autoload :NumberToPhoneConverter
-
1
autoload :NumberToCurrencyConverter
-
1
autoload :NumberToPercentageConverter
-
end
-
-
1
extend self
-
-
# Formats a +number+ into a US phone number (e.g., (555)
-
# 123-9876). You can customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:area_code</tt> - Adds parentheses around the area code.
-
# * <tt>:delimiter</tt> - Specifies the delimiter to use
-
# (defaults to "-").
-
# * <tt>:extension</tt> - Specifies an extension to add to the
-
# end of the generated number.
-
# * <tt>:country_code</tt> - Sets the country code for the phone
-
# number.
-
# ==== Examples
-
#
-
# number_to_phone(5551234) # => 555-1234
-
# number_to_phone('5551234') # => 555-1234
-
# number_to_phone(1235551234) # => 123-555-1234
-
# number_to_phone(1235551234, area_code: true) # => (123) 555-1234
-
# number_to_phone(1235551234, delimiter: ' ') # => 123 555 1234
-
# number_to_phone(1235551234, area_code: true, extension: 555) # => (123) 555-1234 x 555
-
# number_to_phone(1235551234, country_code: 1) # => +1-123-555-1234
-
# number_to_phone('123a456') # => 123a456
-
#
-
# number_to_phone(1235551234, country_code: 1, extension: 1343, delimiter: '.')
-
# # => +1.123.555.1234 x 1343
-
1
def number_to_phone(number, options = {})
-
NumberToPhoneConverter.convert(number, options)
-
end
-
-
# Formats a +number+ into a currency string (e.g., $13.65). You
-
# can customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the level of precision (defaults
-
# to 2).
-
# * <tt>:unit</tt> - Sets the denomination of the currency
-
# (defaults to "$").
-
# * <tt>:separator</tt> - Sets the separator between the units
-
# (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to ",").
-
# * <tt>:format</tt> - Sets the format for non-negative numbers
-
# (defaults to "%u%n"). Fields are <tt>%u</tt> for the
-
# currency, and <tt>%n</tt> for the number.
-
# * <tt>:negative_format</tt> - Sets the format for negative
-
# numbers (defaults to prepending an hyphen to the formatted
-
# number given by <tt>:format</tt>). Accepts the same fields
-
# than <tt>:format</tt>, except <tt>%n</tt> is here the
-
# absolute value of the number.
-
#
-
# ==== Examples
-
#
-
# number_to_currency(1234567890.50) # => $1,234,567,890.50
-
# number_to_currency(1234567890.506) # => $1,234,567,890.51
-
# number_to_currency(1234567890.506, precision: 3) # => $1,234,567,890.506
-
# number_to_currency(1234567890.506, locale: :fr) # => 1 234 567 890,51 €
-
# number_to_currency('123a456') # => $123a456
-
#
-
# number_to_currency(-1234567890.50, negative_format: '(%u%n)')
-
# # => ($1,234,567,890.50)
-
# number_to_currency(1234567890.50, unit: '£', separator: ',', delimiter: '')
-
# # => £1234567890,50
-
# number_to_currency(1234567890.50, unit: '£', separator: ',', delimiter: '', format: '%n %u')
-
# # => 1234567890,50 £
-
1
def number_to_currency(number, options = {})
-
NumberToCurrencyConverter.convert(number, options)
-
end
-
-
# Formats a +number+ as a percentage string (e.g., 65%). You can
-
# customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +false+).
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +false+).
-
# * <tt>:format</tt> - Specifies the format of the percentage
-
# string The number field is <tt>%n</tt> (defaults to "%n%").
-
#
-
# ==== Examples
-
#
-
# number_to_percentage(100) # => 100.000%
-
# number_to_percentage('98') # => 98.000%
-
# number_to_percentage(100, precision: 0) # => 100%
-
# number_to_percentage(1000, delimiter: '.', separator: ',') # => 1.000,000%
-
# number_to_percentage(302.24398923423, precision: 5) # => 302.24399%
-
# number_to_percentage(1000, locale: :fr) # => 1 000,000%
-
# number_to_percentage('98a') # => 98a%
-
# number_to_percentage(100, format: '%n %') # => 100 %
-
1
def number_to_percentage(number, options = {})
-
NumberToPercentageConverter.convert(number, options)
-
end
-
-
# Formats a +number+ with grouped thousands using +delimiter+
-
# (e.g., 12,324). You can customize the format in the +options+
-
# hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to ",").
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
#
-
# ==== Examples
-
#
-
# number_to_delimited(12345678) # => 12,345,678
-
# number_to_delimited('123456') # => 123,456
-
# number_to_delimited(12345678.05) # => 12,345,678.05
-
# number_to_delimited(12345678, delimiter: '.') # => 12.345.678
-
# number_to_delimited(12345678, delimiter: ',') # => 12,345,678
-
# number_to_delimited(12345678.05, separator: ' ') # => 12,345,678 05
-
# number_to_delimited(12345678.05, locale: :fr) # => 12 345 678,05
-
# number_to_delimited('112a') # => 112a
-
# number_to_delimited(98765432.98, delimiter: ' ', separator: ',')
-
# # => 98 765 432,98
-
1
def number_to_delimited(number, options = {})
-
NumberToDelimitedConverter.convert(number, options)
-
end
-
-
# Formats a +number+ with the specified level of
-
# <tt>:precision</tt> (e.g., 112.32 has a precision of 2 if
-
# +:significant+ is +false+, and 5 if +:significant+ is +true+).
-
# You can customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +false+).
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +false+).
-
#
-
# ==== Examples
-
#
-
# number_to_rounded(111.2345) # => 111.235
-
# number_to_rounded(111.2345, precision: 2) # => 111.23
-
# number_to_rounded(13, precision: 5) # => 13.00000
-
# number_to_rounded(389.32314, precision: 0) # => 389
-
# number_to_rounded(111.2345, significant: true) # => 111
-
# number_to_rounded(111.2345, precision: 1, significant: true) # => 100
-
# number_to_rounded(13, precision: 5, significant: true) # => 13.000
-
# number_to_rounded(111.234, locale: :fr) # => 111,234
-
#
-
# number_to_rounded(13, precision: 5, significant: true, strip_insignificant_zeros: true)
-
# # => 13
-
#
-
# number_to_rounded(389.32314, precision: 4, significant: true) # => 389.3
-
# number_to_rounded(1111.2345, precision: 2, separator: ',', delimiter: '.')
-
# # => 1.111,23
-
1
def number_to_rounded(number, options = {})
-
NumberToRoundedConverter.convert(number, options)
-
end
-
-
# Formats the bytes in +number+ into a more understandable
-
# representation (e.g., giving it 1500 yields 1.5 KB). This
-
# method is useful for reporting file sizes to users. You can
-
# customize the format in the +options+ hash.
-
#
-
# See <tt>number_to_human</tt> if you want to pretty-print a
-
# generic number.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +true+)
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +true+)
-
# * <tt>:prefix</tt> - If +:si+ formats the number using the SI
-
# prefix (defaults to :binary)
-
#
-
# ==== Examples
-
#
-
# number_to_human_size(123) # => 123 Bytes
-
# number_to_human_size(1234) # => 1.21 KB
-
# number_to_human_size(12345) # => 12.1 KB
-
# number_to_human_size(1234567) # => 1.18 MB
-
# number_to_human_size(1234567890) # => 1.15 GB
-
# number_to_human_size(1234567890123) # => 1.12 TB
-
# number_to_human_size(1234567, precision: 2) # => 1.2 MB
-
# number_to_human_size(483989, precision: 2) # => 470 KB
-
# number_to_human_size(1234567, precision: 2, separator: ',') # => 1,2 MB
-
#
-
# Non-significant zeros after the fractional separator are stripped out by
-
# default (set <tt>:strip_insignificant_zeros</tt> to +false+ to change that):
-
#
-
# number_to_human_size(1234567890123, precision: 5) # => "1.1229 TB"
-
# number_to_human_size(524288000, precision: 5) # => "500 MB"
-
1
def number_to_human_size(number, options = {})
-
NumberToHumanSizeConverter.convert(number, options)
-
end
-
-
# Pretty prints (formats and approximates) a number in a way it
-
# is more readable by humans (eg.: 1200000000 becomes "1.2
-
# Billion"). This is useful for numbers that can get very large
-
# (and too hard to read).
-
#
-
# See <tt>number_to_human_size</tt> if you want to print a file
-
# size.
-
#
-
# You can also define your own unit-quantifier names if you want
-
# to use other decimal units (eg.: 1500 becomes "1.5
-
# kilometers", 0.150 becomes "150 milliliters", etc). You may
-
# define a wide range of unit quantifiers, even fractional ones
-
# (centi, deci, mili, etc).
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +true+)
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +true+)
-
# * <tt>:units</tt> - A Hash of unit quantifier names. Or a
-
# string containing an i18n scope where to find this hash. It
-
# might have the following keys:
-
# * *integers*: <tt>:unit</tt>, <tt>:ten</tt>,
-
# *<tt>:hundred</tt>, <tt>:thousand</tt>, <tt>:million</tt>,
-
# *<tt>:billion</tt>, <tt>:trillion</tt>,
-
# *<tt>:quadrillion</tt>
-
# * *fractionals*: <tt>:deci</tt>, <tt>:centi</tt>,
-
# *<tt>:mili</tt>, <tt>:micro</tt>, <tt>:nano</tt>,
-
# *<tt>:pico</tt>, <tt>:femto</tt>
-
# * <tt>:format</tt> - Sets the format of the output string
-
# (defaults to "%n %u"). The field types are:
-
# * %u - The quantifier (ex.: 'thousand')
-
# * %n - The number
-
#
-
# ==== Examples
-
#
-
# number_to_human(123) # => "123"
-
# number_to_human(1234) # => "1.23 Thousand"
-
# number_to_human(12345) # => "12.3 Thousand"
-
# number_to_human(1234567) # => "1.23 Million"
-
# number_to_human(1234567890) # => "1.23 Billion"
-
# number_to_human(1234567890123) # => "1.23 Trillion"
-
# number_to_human(1234567890123456) # => "1.23 Quadrillion"
-
# number_to_human(1234567890123456789) # => "1230 Quadrillion"
-
# number_to_human(489939, precision: 2) # => "490 Thousand"
-
# number_to_human(489939, precision: 4) # => "489.9 Thousand"
-
# number_to_human(1234567, precision: 4,
-
# significant: false) # => "1.2346 Million"
-
# number_to_human(1234567, precision: 1,
-
# separator: ',',
-
# significant: false) # => "1,2 Million"
-
#
-
# Non-significant zeros after the decimal separator are stripped
-
# out by default (set <tt>:strip_insignificant_zeros</tt> to
-
# +false+ to change that):
-
#
-
# number_to_human(12345012345, significant_digits: 6) # => "12.345 Billion"
-
# number_to_human(500000000, precision: 5) # => "500 Million"
-
#
-
# ==== Custom Unit Quantifiers
-
#
-
# You can also use your own custom unit quantifiers:
-
# number_to_human(500000, units: { unit: 'ml', thousand: 'lt' }) # => "500 lt"
-
#
-
# If in your I18n locale you have:
-
#
-
# distance:
-
# centi:
-
# one: "centimeter"
-
# other: "centimeters"
-
# unit:
-
# one: "meter"
-
# other: "meters"
-
# thousand:
-
# one: "kilometer"
-
# other: "kilometers"
-
# billion: "gazillion-distance"
-
#
-
# Then you could do:
-
#
-
# number_to_human(543934, units: :distance) # => "544 kilometers"
-
# number_to_human(54393498, units: :distance) # => "54400 kilometers"
-
# number_to_human(54393498000, units: :distance) # => "54.4 gazillion-distance"
-
# number_to_human(343, units: :distance, precision: 1) # => "300 meters"
-
# number_to_human(1, units: :distance) # => "1 meter"
-
# number_to_human(0.34, units: :distance) # => "34 centimeters"
-
1
def number_to_human(number, options = {})
-
NumberToHumanConverter.convert(number, options)
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/deep_merge'
-
-
1
module ActiveSupport
-
1
class OptionMerger #:nodoc:
-
1
instance_methods.each do |method|
-
83
undef_method(method) if method !~ /^(__|instance_eval|class|object_id)/
-
end
-
-
1
def initialize(context, options)
-
2
@context, @options = context, options
-
end
-
-
1
private
-
1
def method_missing(method, *arguments, &block)
-
12
if arguments.last.is_a?(Proc)
-
proc = arguments.pop
-
arguments << lambda { |*args| @options.deep_merge(proc.call(*args)) }
-
else
-
12
arguments << (arguments.last.respond_to?(:to_hash) ? @options.deep_merge(arguments.pop) : @options.dup)
-
end
-
-
12
@context.__send__(method, *arguments, &block)
-
end
-
end
-
end
-
1
require 'yaml'
-
-
1
YAML.add_builtin_type("omap") do |type, val|
-
ActiveSupport::OrderedHash[val.map{ |v| v.to_a.first }]
-
end
-
-
1
module ActiveSupport
-
# <tt>ActiveSupport::OrderedHash</tt> implements a hash that preserves
-
# insertion order.
-
#
-
# oh = ActiveSupport::OrderedHash.new
-
# oh[:a] = 1
-
# oh[:b] = 2
-
# oh.keys # => [:a, :b], this order is guaranteed
-
#
-
# Also, maps the +omap+ feature for YAML files
-
# (See http://yaml.org/type/omap.html) to support ordered items
-
# when loading from yaml.
-
#
-
# <tt>ActiveSupport::OrderedHash</tt> is namespaced to prevent conflicts
-
# with other implementations.
-
1
class OrderedHash < ::Hash
-
1
def to_yaml_type
-
"!tag:yaml.org,2002:omap"
-
end
-
-
1
def encode_with(coder)
-
coder.represent_seq '!omap', map { |k,v| { k => v } }
-
end
-
-
1
def select(*args, &block)
-
dup.tap { |hash| hash.select!(*args, &block) }
-
end
-
-
1
def reject(*args, &block)
-
dup.tap { |hash| hash.reject!(*args, &block) }
-
end
-
-
1
def nested_under_indifferent_access
-
self
-
end
-
-
# Returns true to make sure that this hash is extractable via <tt>Array#extract_options!</tt>
-
1
def extractable_options?
-
true
-
end
-
end
-
end
-
1
module ActiveSupport
-
# Usually key value pairs are handled something like this:
-
#
-
# h = {}
-
# h[:boy] = 'John'
-
# h[:girl] = 'Mary'
-
# h[:boy] # => 'John'
-
# h[:girl] # => 'Mary'
-
#
-
# Using +OrderedOptions+, the above code could be reduced to:
-
#
-
# h = ActiveSupport::OrderedOptions.new
-
# h.boy = 'John'
-
# h.girl = 'Mary'
-
# h.boy # => 'John'
-
# h.girl # => 'Mary'
-
1
class OrderedOptions < Hash
-
1
alias_method :_get, :[] # preserve the original #[] method
-
1
protected :_get # make it protected
-
-
1
def []=(key, value)
-
103
super(key.to_sym, value)
-
end
-
-
1
def [](key)
-
122
super(key.to_sym)
-
end
-
-
1
def method_missing(name, *args)
-
225
name_string = name.to_s
-
225
if name_string.chomp!('=')
-
103
self[name_string] = args.first
-
else
-
122
self[name]
-
end
-
end
-
-
1
def respond_to_missing?(name, include_private)
-
true
-
end
-
end
-
-
# +InheritableOptions+ provides a constructor to build an +OrderedOptions+
-
# hash inherited from another hash.
-
#
-
# Use this if you already have some hash and you want to create a new one based on it.
-
#
-
# h = ActiveSupport::InheritableOptions.new({ girl: 'Mary', boy: 'John' })
-
# h.girl # => 'Mary'
-
# h.boy # => 'John'
-
1
class InheritableOptions < OrderedOptions
-
1
def initialize(parent = nil)
-
6
if parent.kind_of?(OrderedOptions)
-
# use the faster _get when dealing with OrderedOptions
-
13
super() { |h,k| parent._get(k) }
-
2
elsif parent
-
super() { |h,k| parent[k] }
-
else
-
2
super()
-
end
-
end
-
-
1
def inheritable_copy
-
4
self.class.new(self)
-
end
-
end
-
end
-
1
module ActiveSupport
-
# This module is used to encapsulate access to thread local variables.
-
#
-
# Instead of polluting the thread locals namespace:
-
#
-
# Thread.current[:connection_handler]
-
#
-
# you define a class that extends this module:
-
#
-
# module ActiveRecord
-
# class RuntimeRegistry
-
# extend ActiveSupport::PerThreadRegistry
-
#
-
# attr_accessor :connection_handler
-
# end
-
# end
-
#
-
# and invoke the declared instance accessors as class methods. So
-
#
-
# ActiveRecord::RuntimeRegistry.connection_handler = connection_handler
-
#
-
# sets a connection handler local to the current thread, and
-
#
-
# ActiveRecord::RuntimeRegistry.connection_handler
-
#
-
# returns a connection handler local to the current thread.
-
#
-
# This feature is accomplished by instantiating the class and storing the
-
# instance as a thread local keyed by the class name. In the example above
-
# a key "ActiveRecord::RuntimeRegistry" is stored in <tt>Thread.current</tt>.
-
# The class methods proxy to said thread local instance.
-
#
-
# If the class has an initializer, it must accept no arguments.
-
1
module PerThreadRegistry
-
1
def self.extended(object)
-
6
object.instance_variable_set '@per_thread_registry_key', object.name.freeze
-
end
-
-
1
def instance
-
63
Thread.current[@per_thread_registry_key] ||= new
-
end
-
-
1
protected
-
1
def method_missing(name, *args, &block) # :nodoc:
-
# Caches the method definition as a singleton method of the receiver.
-
1
define_singleton_method(name) do |*a, &b|
-
9
instance.public_send(name, *a, &b)
-
end
-
-
1
send(name, *args, &block)
-
end
-
end
-
end
-
1
module ActiveSupport
-
# A class with no predefined methods that behaves similarly to Builder's
-
# BlankSlate. Used for proxy classes.
-
1
class ProxyObject < ::BasicObject
-
1
undef_method :==
-
1
undef_method :equal?
-
-
# Let ActiveSupport::ProxyObject at least raise exceptions.
-
1
def raise(*args)
-
::Object.send(:raise, *args)
-
end
-
end
-
end
-
# This is private interface.
-
#
-
# Rails components cherry pick from Active Support as needed, but there are a
-
# few features that are used for sure some way or another and it is not worth
-
# to put individual requires absolutely everywhere. Think blank? for example.
-
#
-
# This file is loaded by every Rails component except Active Support itself,
-
# but it does not belong to the Rails public interface. It is internal to
-
# Rails and can change anytime.
-
-
# Defines Object#blank? and Object#present?.
-
1
require 'active_support/core_ext/object/blank'
-
-
# Rails own autoload, eager_load, etc.
-
1
require 'active_support/dependencies/autoload'
-
-
# Support for ClassMethods and the included macro.
-
1
require 'active_support/concern'
-
-
# Defines Class#class_attribute.
-
1
require 'active_support/core_ext/class/attribute'
-
-
# Defines Module#delegate.
-
1
require 'active_support/core_ext/module/delegation'
-
-
# Defines ActiveSupport::Deprecation.
-
1
require 'active_support/deprecation'
-
1
require "active_support"
-
1
require "active_support/i18n_railtie"
-
-
1
module ActiveSupport
-
1
class Railtie < Rails::Railtie # :nodoc:
-
1
config.active_support = ActiveSupport::OrderedOptions.new
-
-
1
config.eager_load_namespaces << ActiveSupport
-
-
1
initializer "active_support.deprecation_behavior" do |app|
-
1
if deprecation = app.config.active_support.deprecation
-
1
ActiveSupport::Deprecation.behavior = deprecation
-
end
-
end
-
-
# Sets the default value for Time.zone
-
# If assigned value cannot be matched to a TimeZone, an exception will be raised.
-
1
initializer "active_support.initialize_time_zone" do |app|
-
1
require 'active_support/core_ext/time/zones'
-
1
zone_default = Time.find_zone!(app.config.time_zone)
-
-
1
unless zone_default
-
raise 'Value assigned to config.time_zone not recognized. ' \
-
'Run "rake -D time" for a list of tasks for finding appropriate time zone names.'
-
end
-
-
1
Time.zone_default = zone_default
-
end
-
-
# Sets the default week start
-
# If assigned value is not a valid day symbol (e.g. :sunday, :monday, ...), an exception will be raised.
-
1
initializer "active_support.initialize_beginning_of_week" do |app|
-
1
require 'active_support/core_ext/date/calculations'
-
1
beginning_of_week_default = Date.find_beginning_of_week!(app.config.beginning_of_week)
-
-
1
Date.beginning_of_week_default = beginning_of_week_default
-
end
-
-
1
initializer "active_support.set_configs" do |app|
-
1
app.config.active_support.each do |k, v|
-
1
k = "#{k}="
-
1
ActiveSupport.send(k, v) if ActiveSupport.respond_to? k
-
end
-
end
-
end
-
end
-
1
require 'active_support/concern'
-
1
require 'active_support/core_ext/class/attribute'
-
1
require 'active_support/core_ext/string/inflections'
-
1
require 'active_support/core_ext/array/extract_options'
-
-
1
module ActiveSupport
-
# Rescuable module adds support for easier exception handling.
-
1
module Rescuable
-
1
extend Concern
-
-
1
included do
-
1
class_attribute :rescue_handlers
-
1
self.rescue_handlers = []
-
end
-
-
1
module ClassMethods
-
# Rescue exceptions raised in controller actions.
-
#
-
# <tt>rescue_from</tt> receives a series of exception classes or class
-
# names, and a trailing <tt>:with</tt> option with the name of a method
-
# or a Proc object to be called to handle them. Alternatively a block can
-
# be given.
-
#
-
# Handlers that take one argument will be called with the exception, so
-
# that the exception can be inspected when dealing with it.
-
#
-
# Handlers are inherited. They are searched from right to left, from
-
# bottom to top, and up the hierarchy. The handler of the first class for
-
# which <tt>exception.is_a?(klass)</tt> holds true is the one invoked, if
-
# any.
-
#
-
# class ApplicationController < ActionController::Base
-
# rescue_from User::NotAuthorized, with: :deny_access # self defined exception
-
# rescue_from ActiveRecord::RecordInvalid, with: :show_errors
-
#
-
# rescue_from 'MyAppError::Base' do |exception|
-
# render xml: exception, status: 500
-
# end
-
#
-
# protected
-
# def deny_access
-
# ...
-
# end
-
#
-
# def show_errors(exception)
-
# exception.record.new_record? ? ...
-
# end
-
# end
-
#
-
# Exceptions raised inside exception handlers are not propagated up.
-
1
def rescue_from(*klasses, &block)
-
options = klasses.extract_options!
-
-
unless options.has_key?(:with)
-
if block_given?
-
options[:with] = block
-
else
-
raise ArgumentError, "Need a handler. Supply an options hash that has a :with key as the last argument."
-
end
-
end
-
-
klasses.each do |klass|
-
key = if klass.is_a?(Class) && klass <= Exception
-
klass.name
-
elsif klass.is_a?(String)
-
klass
-
else
-
raise ArgumentError, "#{klass} is neither an Exception nor a String"
-
end
-
-
# put the new handler at the end because the list is read in reverse
-
self.rescue_handlers += [[key, options[:with]]]
-
end
-
end
-
end
-
-
# Tries to rescue the exception by looking up and calling a registered handler.
-
1
def rescue_with_handler(exception)
-
if handler = handler_for_rescue(exception)
-
handler.arity != 0 ? handler.call(exception) : handler.call
-
true # don't rely on the return value of the handler
-
end
-
end
-
-
1
def handler_for_rescue(exception)
-
# We go from right to left because pairs are pushed onto rescue_handlers
-
# as rescue_from declarations are found.
-
_, rescuer = self.class.rescue_handlers.reverse.detect do |klass_name, handler|
-
# The purpose of allowing strings in rescue_from is to support the
-
# declaration of handler associations for exception classes whose
-
# definition is yet unknown.
-
#
-
# Since this loop needs the constants it would be inconsistent to
-
# assume they should exist at this point. An early raised exception
-
# could trigger some other handler and the array could include
-
# precisely a string whose corresponding constant has not yet been
-
# seen. This is why we are tolerant to unknown constants.
-
#
-
# Note that this tolerance only matters if the exception was given as
-
# a string, otherwise a NameError will be raised by the interpreter
-
# itself when rescue_from CONSTANT is executed.
-
klass = self.class.const_get(klass_name) rescue nil
-
klass ||= klass_name.constantize rescue nil
-
exception.is_a?(klass) if klass
-
end
-
-
case rescuer
-
when Symbol
-
method(rescuer)
-
when Proc
-
if rescuer.arity == 0
-
Proc.new { instance_exec(&rescuer) }
-
else
-
Proc.new { |_exception| instance_exec(_exception, &rescuer) }
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveSupport
-
# Wrapping a string in this class gives you a prettier way to test
-
# for equality. The value returned by <tt>Rails.env</tt> is wrapped
-
# in a StringInquirer object so instead of calling this:
-
#
-
# Rails.env == 'production'
-
#
-
# you can call this:
-
#
-
# Rails.env.production?
-
1
class StringInquirer < String
-
1
private
-
-
1
def respond_to_missing?(method_name, include_private = false)
-
method_name[-1] == '?'
-
end
-
-
1
def method_missing(method_name, *arguments)
-
9
if method_name[-1] == '?'
-
9
self == method_name[0..-2]
-
else
-
super
-
end
-
end
-
end
-
end
-
1
require 'active_support/per_thread_registry'
-
-
1
module ActiveSupport
-
# ActiveSupport::Subscriber is an object set to consume
-
# ActiveSupport::Notifications. The subscriber dispatches notifications to
-
# a registered object based on its given namespace.
-
#
-
# An example would be Active Record subscriber responsible for collecting
-
# statistics about queries:
-
#
-
# module ActiveRecord
-
# class StatsSubscriber < ActiveSupport::Subscriber
-
# def sql(event)
-
# Statsd.timing("sql.#{event.payload[:name]}", event.duration)
-
# end
-
# end
-
# end
-
#
-
# And it's finally registered as:
-
#
-
# ActiveRecord::StatsSubscriber.attach_to :active_record
-
#
-
# Since we need to know all instance methods before attaching the log
-
# subscriber, the line above should be called after your subscriber definition.
-
#
-
# After configured, whenever a "sql.active_record" notification is published,
-
# it will properly dispatch the event (ActiveSupport::Notifications::Event) to
-
# the +sql+ method.
-
1
class Subscriber
-
1
class << self
-
-
# Attach the subscriber to a namespace.
-
1
def attach_to(namespace, subscriber=new, notifier=ActiveSupport::Notifications)
-
4
@namespace = namespace
-
4
@subscriber = subscriber
-
4
@notifier = notifier
-
-
4
subscribers << subscriber
-
-
# Add event subscribers for all existing methods on the class.
-
4
subscriber.public_methods(false).each do |event|
-
27
add_event_subscriber(event)
-
end
-
end
-
-
# Adds event subscribers for all new methods added to the class.
-
1
def method_added(event)
-
# Only public methods are added as subscribers, and only if a notifier
-
# has been set up. This means that subscribers will only be set up for
-
# classes that call #attach_to.
-
55
if public_method_defined?(event) && notifier
-
add_event_subscriber(event)
-
end
-
end
-
-
1
def subscribers
-
4
@@subscribers ||= []
-
end
-
-
1
protected
-
-
1
attr_reader :subscriber, :notifier, :namespace
-
-
1
def add_event_subscriber(event)
-
27
return if %w{ start finish }.include?(event.to_s)
-
-
27
notifier.subscribe("#{event}.#{namespace}", subscriber)
-
end
-
end
-
-
1
def initialize
-
4
@queue_key = [self.class.name, object_id].join "-"
-
4
super
-
end
-
-
1
def start(name, id, payload)
-
9
e = ActiveSupport::Notifications::Event.new(name, Time.now, nil, id, payload)
-
9
parent = event_stack.last
-
9
parent << e if parent
-
-
9
event_stack.push e
-
end
-
-
1
def finish(name, id, payload)
-
9
finished = Time.now
-
9
event = event_stack.pop
-
9
event.end = finished
-
9
event.payload.merge!(payload)
-
-
9
method = name.split('.').first
-
9
send(method, event)
-
end
-
-
1
private
-
-
1
def event_stack
-
27
SubscriberQueueRegistry.instance.get_queue(@queue_key)
-
end
-
end
-
-
# This is a registry for all the event stacks kept for subscribers.
-
#
-
# See the documentation of <tt>ActiveSupport::PerThreadRegistry</tt>
-
# for further details.
-
1
class SubscriberQueueRegistry # :nodoc:
-
1
extend PerThreadRegistry
-
-
1
def initialize
-
1
@registry = {}
-
end
-
-
1
def get_queue(queue_key)
-
27
@registry[queue_key] ||= []
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/delegation'
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'logger'
-
1
require 'active_support/logger'
-
-
1
module ActiveSupport
-
# Wraps any standard Logger object to provide tagging capabilities.
-
#
-
# logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))
-
# logger.tagged('BCX') { logger.info 'Stuff' } # Logs "[BCX] Stuff"
-
# logger.tagged('BCX', "Jason") { logger.info 'Stuff' } # Logs "[BCX] [Jason] Stuff"
-
# logger.tagged('BCX') { logger.tagged('Jason') { logger.info 'Stuff' } } # Logs "[BCX] [Jason] Stuff"
-
#
-
# This is used by the default Rails.logger as configured by Railties to make
-
# it easy to stamp log lines with subdomains, request ids, and anything else
-
# to aid debugging of multi-user production applications.
-
1
module TaggedLogging
-
1
module Formatter # :nodoc:
-
# This method is invoked when a log event occurs.
-
1
def call(severity, timestamp, progname, msg)
-
super(severity, timestamp, progname, "#{tags_text}#{msg}")
-
end
-
-
1
def tagged(*tags)
-
new_tags = push_tags(*tags)
-
yield self
-
ensure
-
pop_tags(new_tags.size)
-
end
-
-
1
def push_tags(*tags)
-
tags.flatten.reject(&:blank?).tap do |new_tags|
-
current_tags.concat new_tags
-
end
-
end
-
-
1
def pop_tags(size = 1)
-
current_tags.pop size
-
end
-
-
1
def clear_tags!
-
current_tags.clear
-
end
-
-
1
def current_tags
-
Thread.current[:activesupport_tagged_logging_tags] ||= []
-
end
-
-
1
private
-
1
def tags_text
-
tags = current_tags
-
if tags.any?
-
tags.collect { |tag| "[#{tag}] " }.join
-
end
-
end
-
end
-
-
1
def self.new(logger)
-
# Ensure we set a default formatter so we aren't extending nil!
-
2
logger.formatter ||= ActiveSupport::Logger::SimpleFormatter.new
-
2
logger.formatter.extend Formatter
-
2
logger.extend(self)
-
end
-
-
1
delegate :push_tags, :pop_tags, :clear_tags!, to: :formatter
-
-
1
def tagged(*tags)
-
formatter.tagged(*tags) { yield self }
-
end
-
-
1
def flush
-
clear_tags!
-
super if defined?(super)
-
end
-
end
-
end
-
1
gem 'minitest' # make sure we get the gem, not stdlib
-
1
require 'minitest'
-
1
require 'active_support/testing/tagged_logging'
-
1
require 'active_support/testing/setup_and_teardown'
-
1
require 'active_support/testing/assertions'
-
1
require 'active_support/testing/deprecation'
-
1
require 'active_support/testing/declarative'
-
1
require 'active_support/testing/isolation'
-
1
require 'active_support/testing/constant_lookup'
-
1
require 'active_support/testing/time_helpers'
-
1
require 'active_support/core_ext/kernel/reporting'
-
1
require 'active_support/deprecation'
-
-
1
begin
-
2
silence_warnings { require 'mocha/setup' }
-
rescue LoadError
-
end
-
-
1
module ActiveSupport
-
1
class TestCase < ::Minitest::Test
-
1
Assertion = Minitest::Assertion
-
-
1
alias_method :method_name, :name
-
-
1
$tags = {}
-
1
def self.for_tag(tag)
-
yield if $tags[tag]
-
end
-
-
# FIXME: we have tests that depend on run order, we should fix that and
-
# remove this method call.
-
1
self.i_suck_and_my_tests_are_order_dependent!
-
-
1
include ActiveSupport::Testing::TaggedLogging
-
1
include ActiveSupport::Testing::SetupAndTeardown
-
1
include ActiveSupport::Testing::Assertions
-
1
include ActiveSupport::Testing::Deprecation
-
1
include ActiveSupport::Testing::TimeHelpers
-
1
extend ActiveSupport::Testing::Declarative
-
-
# test/unit backwards compatibility methods
-
1
alias :assert_raise :assert_raises
-
1
alias :assert_not_empty :refute_empty
-
1
alias :assert_not_equal :refute_equal
-
1
alias :assert_not_in_delta :refute_in_delta
-
1
alias :assert_not_in_epsilon :refute_in_epsilon
-
1
alias :assert_not_includes :refute_includes
-
1
alias :assert_not_instance_of :refute_instance_of
-
1
alias :assert_not_kind_of :refute_kind_of
-
1
alias :assert_no_match :refute_match
-
1
alias :assert_not_nil :refute_nil
-
1
alias :assert_not_operator :refute_operator
-
1
alias :assert_not_predicate :refute_predicate
-
1
alias :assert_not_respond_to :refute_respond_to
-
1
alias :assert_not_same :refute_same
-
-
# Fails if the block raises an exception.
-
#
-
# assert_nothing_raised do
-
# ...
-
# end
-
1
def assert_nothing_raised(*args)
-
yield
-
end
-
end
-
end
-
1
require 'active_support/core_ext/object/blank'
-
-
1
module ActiveSupport
-
1
module Testing
-
1
module Assertions
-
# Assert that an expression is not truthy. Passes if <tt>object</tt> is
-
# +nil+ or +false+. "Truthy" means "considered true in a conditional"
-
# like <tt>if foo</tt>.
-
#
-
# assert_not nil # => true
-
# assert_not false # => true
-
# assert_not 'foo' # => 'foo' is not nil or false
-
#
-
# An error message can be specified.
-
#
-
# assert_not foo, 'foo should be false'
-
1
def assert_not(object, message = nil)
-
message ||= "Expected #{mu_pp(object)} to be nil or false"
-
assert !object, message
-
end
-
-
# Test numeric difference between the return value of an expression as a
-
# result of what is evaluated in the yielded block.
-
#
-
# assert_difference 'Article.count' do
-
# post :create, article: {...}
-
# end
-
#
-
# An arbitrary expression is passed in and evaluated.
-
#
-
# assert_difference 'assigns(:article).comments(:reload).size' do
-
# post :create, comment: {...}
-
# end
-
#
-
# An arbitrary positive or negative difference can be specified.
-
# The default is <tt>1</tt>.
-
#
-
# assert_difference 'Article.count', -1 do
-
# post :delete, id: ...
-
# end
-
#
-
# An array of expressions can also be passed in and evaluated.
-
#
-
# assert_difference [ 'Article.count', 'Post.count' ], 2 do
-
# post :create, article: {...}
-
# end
-
#
-
# A lambda or a list of lambdas can be passed in and evaluated:
-
#
-
# assert_difference ->{ Article.count }, 2 do
-
# post :create, article: {...}
-
# end
-
#
-
# assert_difference [->{ Article.count }, ->{ Post.count }], 2 do
-
# post :create, article: {...}
-
# end
-
#
-
# An error message can be specified.
-
#
-
# assert_difference 'Article.count', -1, 'An Article should be destroyed' do
-
# post :delete, id: ...
-
# end
-
1
def assert_difference(expression, difference = 1, message = nil, &block)
-
expressions = Array(expression)
-
-
exps = expressions.map { |e|
-
e.respond_to?(:call) ? e : lambda { eval(e, block.binding) }
-
}
-
before = exps.map { |e| e.call }
-
-
yield
-
-
expressions.zip(exps).each_with_index do |(code, e), i|
-
error = "#{code.inspect} didn't change by #{difference}"
-
error = "#{message}.\n#{error}" if message
-
assert_equal(before[i] + difference, e.call, error)
-
end
-
end
-
-
# Assertion that the numeric result of evaluating an expression is not
-
# changed before and after invoking the passed in block.
-
#
-
# assert_no_difference 'Article.count' do
-
# post :create, article: invalid_attributes
-
# end
-
#
-
# An error message can be specified.
-
#
-
# assert_no_difference 'Article.count', 'An Article should not be created' do
-
# post :create, article: invalid_attributes
-
# end
-
1
def assert_no_difference(expression, message = nil, &block)
-
assert_difference expression, 0, message, &block
-
end
-
end
-
end
-
end
-
1
require "active_support/concern"
-
1
require "active_support/inflector"
-
-
1
module ActiveSupport
-
1
module Testing
-
# Resolves a constant from a minitest spec name.
-
#
-
# Given the following spec-style test:
-
#
-
# describe WidgetsController, :index do
-
# describe "authenticated user" do
-
# describe "returns widgets" do
-
# it "has a controller that exists" do
-
# assert_kind_of WidgetsController, @controller
-
# end
-
# end
-
# end
-
# end
-
#
-
# The test will have the following name:
-
#
-
# "WidgetsController::index::authenticated user::returns widgets"
-
#
-
# The constant WidgetsController can be resolved from the name.
-
# The following code will resolve the constant:
-
#
-
# controller = determine_constant_from_test_name(name) do |constant|
-
# Class === constant && constant < ::ActionController::Metal
-
# end
-
1
module ConstantLookup
-
1
extend ::ActiveSupport::Concern
-
-
1
module ClassMethods # :nodoc:
-
1
def determine_constant_from_test_name(test_name)
-
names = test_name.split "::"
-
while names.size > 0 do
-
names.last.sub!(/Test$/, "")
-
begin
-
constant = names.join("::").constantize
-
break(constant) if yield(constant)
-
rescue NoMethodError # subclass of NameError
-
raise
-
rescue NameError
-
# Constant wasn't found, move on
-
ensure
-
names.pop
-
end
-
end
-
end
-
end
-
-
end
-
end
-
end
-
1
module ActiveSupport
-
1
module Testing
-
1
module Declarative
-
-
1
def self.extended(klass) #:nodoc:
-
1
klass.class_eval do
-
-
1
unless method_defined?(:describe)
-
1
def self.describe(text)
-
if block_given?
-
super
-
else
-
message = "`describe` without a block is deprecated, please switch to: `def self.name; #{text.inspect}; end`\n"
-
ActiveSupport::Deprecation.warn message
-
-
class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
-
def self.name
-
"#{text}"
-
end
-
RUBY_EVAL
-
end
-
end
-
end
-
-
end
-
end
-
-
1
unless defined?(Spec)
-
# Helper to define a test method using a String. Under the hood, it replaces
-
# spaces with underscores and defines the test method.
-
#
-
# test "verify something" do
-
# ...
-
# end
-
1
def test(name, &block)
-
test_name = "test_#{name.gsub(/\s+/,'_')}".to_sym
-
defined = instance_method(test_name) rescue false
-
raise "#{test_name} is already defined in #{self}" if defined
-
if block_given?
-
define_method(test_name, &block)
-
else
-
define_method(test_name) do
-
flunk "No implementation provided for #{name}"
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/deprecation'
-
-
1
module ActiveSupport
-
1
module Testing
-
1
module Deprecation #:nodoc:
-
1
def assert_deprecated(match = nil, &block)
-
result, warnings = collect_deprecations(&block)
-
assert !warnings.empty?, "Expected a deprecation warning within the block but received none"
-
if match
-
match = Regexp.new(Regexp.escape(match)) unless match.is_a?(Regexp)
-
assert warnings.any? { |w| w =~ match }, "No deprecation warning matched #{match}: #{warnings.join(', ')}"
-
end
-
result
-
end
-
-
1
def assert_not_deprecated(&block)
-
result, deprecations = collect_deprecations(&block)
-
assert deprecations.empty?, "Expected no deprecation warning within the block but received #{deprecations.size}: \n #{deprecations * "\n "}"
-
result
-
end
-
-
1
def collect_deprecations
-
old_behavior = ActiveSupport::Deprecation.behavior
-
deprecations = []
-
ActiveSupport::Deprecation.behavior = Proc.new do |message, callstack|
-
deprecations << message
-
end
-
result = yield
-
[result, deprecations]
-
ensure
-
ActiveSupport::Deprecation.behavior = old_behavior
-
end
-
end
-
end
-
end
-
1
require 'rbconfig'
-
-
1
module ActiveSupport
-
1
module Testing
-
1
module Isolation
-
1
require 'thread'
-
-
1
def self.included(klass) #:nodoc:
-
klass.class_eval do
-
parallelize_me!
-
end
-
end
-
-
1
def self.forking_env?
-
1
!ENV["NO_FORK"] && ((RbConfig::CONFIG['host_os'] !~ /mswin|mingw/) && (RUBY_PLATFORM !~ /java/))
-
end
-
-
1
@@class_setup_mutex = Mutex.new
-
-
1
def _run_class_setup # class setup method should only happen in parent
-
@@class_setup_mutex.synchronize do
-
unless defined?(@@ran_class_setup) || ENV['ISOLATION_TEST']
-
self.class.setup if self.class.respond_to?(:setup)
-
@@ran_class_setup = true
-
end
-
end
-
end
-
-
1
def run
-
serialized = run_in_isolation do
-
super
-
end
-
-
Marshal.load(serialized)
-
end
-
-
1
module Forking
-
1
def run_in_isolation(&blk)
-
read, write = IO.pipe
-
read.binmode
-
write.binmode
-
-
pid = fork do
-
read.close
-
yield
-
write.puts [Marshal.dump(self.dup)].pack("m")
-
exit!
-
end
-
-
write.close
-
result = read.read
-
Process.wait2(pid)
-
return result.unpack("m")[0]
-
end
-
end
-
-
1
module Subprocess
-
1
ORIG_ARGV = ARGV.dup unless defined?(ORIG_ARGV)
-
-
# Crazy H4X to get this working in windows / jruby with
-
# no forking.
-
1
def run_in_isolation(&blk)
-
require "tempfile"
-
-
if ENV["ISOLATION_TEST"]
-
yield
-
File.open(ENV["ISOLATION_OUTPUT"], "w") do |file|
-
file.puts [Marshal.dump(self.dup)].pack("m")
-
end
-
exit!
-
else
-
Tempfile.open("isolation") do |tmpfile|
-
ENV["ISOLATION_TEST"] = self.class.name
-
ENV["ISOLATION_OUTPUT"] = tmpfile.path
-
-
load_paths = $-I.map {|p| "-I\"#{File.expand_path(p)}\"" }.join(" ")
-
`#{Gem.ruby} #{load_paths} #{$0} #{ORIG_ARGV.join(" ")}`
-
-
ENV.delete("ISOLATION_TEST")
-
ENV.delete("ISOLATION_OUTPUT")
-
-
return tmpfile.read.unpack("m")[0]
-
end
-
end
-
end
-
end
-
-
1
include forking_env? ? Forking : Subprocess
-
end
-
end
-
end
-
1
require 'active_support/concern'
-
1
require 'active_support/callbacks'
-
-
1
module ActiveSupport
-
1
module Testing
-
# Adds support for +setup+ and +teardown+ callbacks.
-
# These callbacks serve as a replacement to overwriting the
-
# <tt>#setup</tt> and <tt>#teardown</tt> methods of your TestCase.
-
#
-
# class ExampleTest < ActiveSupport::TestCase
-
# setup do
-
# # ...
-
# end
-
#
-
# teardown do
-
# # ...
-
# end
-
# end
-
1
module SetupAndTeardown
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
include ActiveSupport::Callbacks
-
1
define_callbacks :setup, :teardown
-
end
-
-
1
module ClassMethods
-
# Add a callback, which runs before <tt>TestCase#setup</tt>.
-
1
def setup(*args, &block)
-
7
set_callback(:setup, :before, *args, &block)
-
end
-
-
# Add a callback, which runs after <tt>TestCase#teardown</tt>.
-
1
def teardown(*args, &block)
-
3
set_callback(:teardown, :after, *args, &block)
-
end
-
end
-
-
1
def before_setup # :nodoc:
-
super
-
run_callbacks :setup
-
end
-
-
1
def after_teardown # :nodoc:
-
run_callbacks :teardown
-
super
-
end
-
end
-
end
-
end
-
1
module ActiveSupport
-
1
module Testing
-
# Logs a "PostsControllerTest: test name" heading before each test to
-
# make test.log easier to search and follow along with.
-
1
module TaggedLogging #:nodoc:
-
1
attr_writer :tagged_logger
-
-
1
def before_setup
-
if tagged_logger
-
heading = "#{self.class}: #{name}"
-
divider = '-' * heading.size
-
tagged_logger.info divider
-
tagged_logger.info heading
-
tagged_logger.info divider
-
end
-
super
-
end
-
-
1
private
-
1
def tagged_logger
-
@tagged_logger ||= (defined?(Rails.logger) && Rails.logger)
-
end
-
end
-
end
-
end
-
1
module ActiveSupport
-
1
module Testing
-
1
class SimpleStubs # :nodoc:
-
1
Stub = Struct.new(:object, :method_name, :original_method)
-
-
1
def initialize
-
@stubs = {}
-
end
-
-
1
def stub_object(object, method_name, return_value)
-
key = [object.object_id, method_name]
-
-
if stub = @stubs[key]
-
unstub_object(stub)
-
end
-
-
new_name = "__simple_stub__#{method_name}"
-
-
@stubs[key] = Stub.new(object, method_name, new_name)
-
-
object.singleton_class.send :alias_method, new_name, method_name
-
object.define_singleton_method(method_name) { return_value }
-
end
-
-
1
def unstub_all!
-
@stubs.each_value do |stub|
-
unstub_object(stub)
-
end
-
@stubs = {}
-
end
-
-
1
private
-
-
1
def unstub_object(stub)
-
singleton_class = stub.object.singleton_class
-
singleton_class.send :undef_method, stub.method_name
-
singleton_class.send :alias_method, stub.method_name, stub.original_method
-
singleton_class.send :undef_method, stub.original_method
-
end
-
end
-
-
# Containing helpers that helps you test passage of time.
-
1
module TimeHelpers
-
# Changes current time to the time in the future or in the past by a given time difference by
-
# stubbing +Time.now+ and +Date.today+.
-
#
-
# Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
-
# travel 1.day
-
# Time.current # => Sun, 10 Nov 2013 15:34:49 EST -05:00
-
# Date.current # => Sun, 10 Nov 2013
-
#
-
# This method also accepts a block, which will return the current time back to its original
-
# state at the end of the block:
-
#
-
# Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
-
# travel 1.day do
-
# User.create.created_at # => Sun, 10 Nov 2013 15:34:49 EST -05:00
-
# end
-
# Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
-
1
def travel(duration, &block)
-
travel_to Time.now + duration, &block
-
end
-
-
# Changes current time to the given time by stubbing +Time.now+ and
-
# +Date.today+ to return the time or date passed into this method.
-
#
-
# Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
-
# travel_to Time.new(2004, 11, 24, 01, 04, 44)
-
# Time.current # => Wed, 24 Nov 2004 01:04:44 EST -05:00
-
# Date.current # => Wed, 24 Nov 2004
-
#
-
# Dates are taken as their timestamp at the beginning of the day in the
-
# application time zone. <tt>Time.current</tt> returns said timestamp,
-
# and <tt>Time.now</tt> its equivalent in the system time zone. Similarly,
-
# <tt>Date.current</tt> returns a date equal to the argument, and
-
# <tt>Date.today</tt> the date according to <tt>Time.now</tt>, which may
-
# be different. (Note that you rarely want to deal with <tt>Time.now</tt>,
-
# or <tt>Date.today</tt>, in order to honor the application time zone
-
# please always use <tt>Time.current</tt> and <tt>Date.current</tt>.)
-
#
-
# This method also accepts a block, which will return the current time back to its original
-
# state at the end of the block:
-
#
-
# Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
-
# travel_to Time.new(2004, 11, 24, 01, 04, 44) do
-
# Time.current # => Wed, 24 Nov 2004 01:04:44 EST -05:00
-
# end
-
# Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
-
1
def travel_to(date_or_time, &block)
-
if date_or_time.is_a?(Date) && !date_or_time.is_a?(DateTime)
-
now = date_or_time.midnight.to_time
-
else
-
now = date_or_time.to_time
-
end
-
-
simple_stubs.stub_object(Time, :now, now)
-
simple_stubs.stub_object(Date, :today, now.to_date)
-
-
if block_given?
-
begin
-
block.call
-
ensure
-
travel_back
-
end
-
end
-
end
-
-
# Returns the current time back to its original state, by removing the stubs added by
-
# `travel` and `travel_to`.
-
#
-
# Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
-
# travel_to Time.new(2004, 11, 24, 01, 04, 44)
-
# Time.current # => Wed, 24 Nov 2004 01:04:44 EST -05:00
-
# travel_back
-
# Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
-
1
def travel_back
-
simple_stubs.unstub_all!
-
end
-
-
1
private
-
-
1
def simple_stubs
-
@simple_stubs ||= SimpleStubs.new
-
end
-
end
-
end
-
end
-
1
require 'active_support'
-
-
1
module ActiveSupport
-
1
autoload :Duration, 'active_support/duration'
-
1
autoload :TimeWithZone, 'active_support/time_with_zone'
-
1
autoload :TimeZone, 'active_support/values/time_zone'
-
end
-
-
1
require 'date'
-
1
require 'time'
-
-
1
require 'active_support/core_ext/time'
-
1
require 'active_support/core_ext/date'
-
1
require 'active_support/core_ext/date_time'
-
-
1
require 'active_support/core_ext/integer/time'
-
1
require 'active_support/core_ext/numeric/time'
-
-
1
require 'active_support/core_ext/string/conversions'
-
1
require 'active_support/core_ext/string/zones'
-
1
require 'active_support/values/time_zone'
-
1
require 'active_support/core_ext/object/acts_like'
-
-
1
module ActiveSupport
-
# A Time-like class that can represent a time in any time zone. Necessary
-
# because standard Ruby Time instances are limited to UTC and the
-
# system's <tt>ENV['TZ']</tt> zone.
-
#
-
# You shouldn't ever need to create a TimeWithZone instance directly via +new+.
-
# Instead use methods +local+, +parse+, +at+ and +now+ on TimeZone instances,
-
# and +in_time_zone+ on Time and DateTime instances.
-
#
-
# Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)'
-
# Time.zone.local(2007, 2, 10, 15, 30, 45) # => Sat, 10 Feb 2007 15:30:45 EST -05:00
-
# Time.zone.parse('2007-02-10 15:30:45') # => Sat, 10 Feb 2007 15:30:45 EST -05:00
-
# Time.zone.at(1170361845) # => Sat, 10 Feb 2007 15:30:45 EST -05:00
-
# Time.zone.now # => Sun, 18 May 2008 13:07:55 EDT -04:00
-
# Time.utc(2007, 2, 10, 20, 30, 45).in_time_zone # => Sat, 10 Feb 2007 15:30:45 EST -05:00
-
#
-
# See Time and TimeZone for further documentation of these methods.
-
#
-
# TimeWithZone instances implement the same API as Ruby Time instances, so
-
# that Time and TimeWithZone instances are interchangeable.
-
#
-
# t = Time.zone.now # => Sun, 18 May 2008 13:27:25 EDT -04:00
-
# t.hour # => 13
-
# t.dst? # => true
-
# t.utc_offset # => -14400
-
# t.zone # => "EDT"
-
# t.to_s(:rfc822) # => "Sun, 18 May 2008 13:27:25 -0400"
-
# t + 1.day # => Mon, 19 May 2008 13:27:25 EDT -04:00
-
# t.beginning_of_year # => Tue, 01 Jan 2008 00:00:00 EST -05:00
-
# t > Time.utc(1999) # => true
-
# t.is_a?(Time) # => true
-
# t.is_a?(ActiveSupport::TimeWithZone) # => true
-
1
class TimeWithZone
-
-
# Report class name as 'Time' to thwart type checking.
-
1
def self.name
-
'Time'
-
end
-
-
1
include Comparable
-
1
attr_reader :time_zone
-
-
1
def initialize(utc_time, time_zone, local_time = nil, period = nil)
-
@utc, @time_zone, @time = utc_time, time_zone, local_time
-
@period = @utc ? period : get_period_and_ensure_valid_local_time(period)
-
end
-
-
# Returns a Time or DateTime instance that represents the time in +time_zone+.
-
1
def time
-
@time ||= period.to_local(@utc)
-
end
-
-
# Returns a Time or DateTime instance that represents the time in UTC.
-
1
def utc
-
@utc ||= period.to_utc(@time)
-
end
-
1
alias_method :comparable_time, :utc
-
1
alias_method :getgm, :utc
-
1
alias_method :getutc, :utc
-
1
alias_method :gmtime, :utc
-
-
# Returns the underlying TZInfo::TimezonePeriod.
-
1
def period
-
@period ||= time_zone.period_for_utc(@utc)
-
end
-
-
# Returns the simultaneous time in <tt>Time.zone</tt>, or the specified zone.
-
1
def in_time_zone(new_zone = ::Time.zone)
-
return self if time_zone == new_zone
-
utc.in_time_zone(new_zone)
-
end
-
-
# Returns a <tt>Time.local()</tt> instance of the simultaneous time in your
-
# system's <tt>ENV['TZ']</tt> zone.
-
1
def localtime
-
utc.respond_to?(:getlocal) ? utc.getlocal : utc.to_time.getlocal
-
end
-
1
alias_method :getlocal, :localtime
-
-
# Returns true if the current time is within Daylight Savings Time for the
-
# specified time zone.
-
#
-
# Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)'
-
# Time.zone.parse("2012-5-30").dst? # => true
-
# Time.zone.parse("2012-11-30").dst? # => false
-
1
def dst?
-
period.dst?
-
end
-
1
alias_method :isdst, :dst?
-
-
# Returns true if the current time zone is set to UTC.
-
#
-
# Time.zone = 'UTC' # => 'UTC'
-
# Time.zone.now.utc? # => true
-
# Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)'
-
# Time.zone.now.utc? # => false
-
1
def utc?
-
time_zone.name == 'UTC'
-
end
-
1
alias_method :gmt?, :utc?
-
-
# Returns the offset from current time to UTC time in seconds.
-
1
def utc_offset
-
period.utc_total_offset
-
end
-
1
alias_method :gmt_offset, :utc_offset
-
1
alias_method :gmtoff, :utc_offset
-
-
# Returns a formatted string of the offset from UTC, or an alternative
-
# string if the time zone is already UTC.
-
#
-
# Time.zone = 'Eastern Time (US & Canada)' # => "Eastern Time (US & Canada)"
-
# Time.zone.now.formatted_offset(true) # => "-05:00"
-
# Time.zone.now.formatted_offset(false) # => "-0500"
-
# Time.zone = 'UTC' # => "UTC"
-
# Time.zone.now.formatted_offset(true, "0") # => "0"
-
1
def formatted_offset(colon = true, alternate_utc_string = nil)
-
utc? && alternate_utc_string || TimeZone.seconds_to_utc_offset(utc_offset, colon)
-
end
-
-
# Time uses +zone+ to display the time zone abbreviation, so we're
-
# duck-typing it.
-
1
def zone
-
period.zone_identifier.to_s
-
end
-
-
1
def inspect
-
"#{time.strftime('%a, %d %b %Y %H:%M:%S')} #{zone} #{formatted_offset}"
-
end
-
-
1
def xmlschema(fraction_digits = 0)
-
fraction = if fraction_digits.to_i > 0
-
(".%06i" % time.usec)[0, fraction_digits.to_i + 1]
-
end
-
-
"#{time.strftime("%Y-%m-%dT%H:%M:%S")}#{fraction}#{formatted_offset(true, 'Z')}"
-
end
-
1
alias_method :iso8601, :xmlschema
-
-
# Coerces time to a string for JSON encoding. The default format is ISO 8601.
-
# You can get %Y/%m/%d %H:%M:%S +offset style by setting
-
# <tt>ActiveSupport::JSON::Encoding.use_standard_json_time_format</tt>
-
# to +false+.
-
#
-
# # With ActiveSupport::JSON::Encoding.use_standard_json_time_format = true
-
# Time.utc(2005,2,1,15,15,10).in_time_zone("Hawaii").to_json
-
# # => "2005-02-01T05:15:10.000-10:00"
-
#
-
# # With ActiveSupport::JSON::Encoding.use_standard_json_time_format = false
-
# Time.utc(2005,2,1,15,15,10).in_time_zone("Hawaii").to_json
-
# # => "2005/02/01 05:15:10 -1000"
-
1
def as_json(options = nil)
-
if ActiveSupport::JSON::Encoding.use_standard_json_time_format
-
xmlschema(ActiveSupport::JSON::Encoding.time_precision)
-
else
-
%(#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)})
-
end
-
end
-
-
1
def encode_with(coder)
-
if coder.respond_to?(:represent_object)
-
coder.represent_object(nil, utc)
-
else
-
coder.represent_scalar(nil, utc.strftime("%Y-%m-%d %H:%M:%S.%9NZ"))
-
end
-
end
-
-
# Returns a string of the object's date and time in the format used by
-
# HTTP requests.
-
#
-
# Time.zone.now.httpdate # => "Tue, 01 Jan 2013 04:39:43 GMT"
-
1
def httpdate
-
utc.httpdate
-
end
-
-
# Returns a string of the object's date and time in the RFC 2822 standard
-
# format.
-
#
-
# Time.zone.now.rfc2822 # => "Tue, 01 Jan 2013 04:51:39 +0000"
-
1
def rfc2822
-
to_s(:rfc822)
-
end
-
1
alias_method :rfc822, :rfc2822
-
-
# <tt>:db</tt> format outputs time in UTC; all others output time in local.
-
# Uses TimeWithZone's +strftime+, so <tt>%Z</tt> and <tt>%z</tt> work correctly.
-
1
def to_s(format = :default)
-
if format == :db
-
utc.to_s(format)
-
elsif formatter = ::Time::DATE_FORMATS[format]
-
formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter)
-
else
-
"#{time.strftime("%Y-%m-%d %H:%M:%S")} #{formatted_offset(false, 'UTC')}" # mimicking Ruby 1.9 Time#to_s format
-
end
-
end
-
1
alias_method :to_formatted_s, :to_s
-
-
# Replaces <tt>%Z</tt> and <tt>%z</tt> directives with +zone+ and
-
# +formatted_offset+, respectively, before passing to Time#strftime, so
-
# that zone information is correct
-
1
def strftime(format)
-
format = format.gsub('%Z', zone)
-
.gsub('%z', formatted_offset(false))
-
.gsub('%:z', formatted_offset(true))
-
.gsub('%::z', formatted_offset(true) + ":00")
-
time.strftime(format)
-
end
-
-
# Use the time in UTC for comparisons.
-
1
def <=>(other)
-
utc <=> other
-
end
-
-
# Returns true if the current object's time is within the specified
-
# +min+ and +max+ time.
-
1
def between?(min, max)
-
utc.between?(min, max)
-
end
-
-
# Returns true if the current object's time is in the past.
-
1
def past?
-
utc.past?
-
end
-
-
# Returns true if the current object's time falls within
-
# the current day.
-
1
def today?
-
time.today?
-
end
-
-
# Returns true if the current object's time is in the future.
-
1
def future?
-
utc.future?
-
end
-
-
1
def eql?(other)
-
utc.eql?(other)
-
end
-
-
1
def hash
-
utc.hash
-
end
-
-
1
def +(other)
-
# If we're adding a Duration of variable length (i.e., years, months, days), move forward from #time,
-
# otherwise move forward from #utc, for accuracy when moving across DST boundaries
-
if duration_of_variable_length?(other)
-
method_missing(:+, other)
-
else
-
result = utc.acts_like?(:date) ? utc.since(other) : utc + other rescue utc.since(other)
-
result.in_time_zone(time_zone)
-
end
-
end
-
-
1
def -(other)
-
# If we're subtracting a Duration of variable length (i.e., years, months, days), move backwards from #time,
-
# otherwise move backwards #utc, for accuracy when moving across DST boundaries
-
if other.acts_like?(:time)
-
utc.to_f - other.to_f
-
elsif duration_of_variable_length?(other)
-
method_missing(:-, other)
-
else
-
result = utc.acts_like?(:date) ? utc.ago(other) : utc - other rescue utc.ago(other)
-
result.in_time_zone(time_zone)
-
end
-
end
-
-
1
def since(other)
-
# If we're adding a Duration of variable length (i.e., years, months, days), move forward from #time,
-
# otherwise move forward from #utc, for accuracy when moving across DST boundaries
-
if duration_of_variable_length?(other)
-
method_missing(:since, other)
-
else
-
utc.since(other).in_time_zone(time_zone)
-
end
-
end
-
-
1
def ago(other)
-
since(-other)
-
end
-
-
1
def advance(options)
-
# If we're advancing a value of variable length (i.e., years, weeks, months, days), advance from #time,
-
# otherwise advance from #utc, for accuracy when moving across DST boundaries
-
if options.values_at(:years, :weeks, :months, :days).any?
-
method_missing(:advance, options)
-
else
-
utc.advance(options).in_time_zone(time_zone)
-
end
-
end
-
-
1
%w(year mon month day mday wday yday hour min sec usec nsec to_date).each do |method_name|
-
13
class_eval <<-EOV, __FILE__, __LINE__ + 1
-
def #{method_name} # def month
-
time.#{method_name} # time.month
-
end # end
-
EOV
-
end
-
-
1
def to_a
-
[time.sec, time.min, time.hour, time.day, time.mon, time.year, time.wday, time.yday, dst?, zone]
-
end
-
-
1
def to_f
-
utc.to_f
-
end
-
-
1
def to_i
-
utc.to_i
-
end
-
1
alias_method :tv_sec, :to_i
-
-
1
def to_r
-
utc.to_r
-
end
-
-
# Return an instance of Time in the system timezone.
-
1
def to_time
-
utc.to_time
-
end
-
-
1
def to_datetime
-
utc.to_datetime.new_offset(Rational(utc_offset, 86_400))
-
end
-
-
# So that +self+ <tt>acts_like?(:time)</tt>.
-
1
def acts_like_time?
-
true
-
end
-
-
# Say we're a Time to thwart type checking.
-
1
def is_a?(klass)
-
klass == ::Time || super
-
end
-
1
alias_method :kind_of?, :is_a?
-
-
1
def freeze
-
period; utc; time # preload instance variables before freezing
-
super
-
end
-
-
1
def marshal_dump
-
[utc, time_zone.name, time]
-
end
-
-
1
def marshal_load(variables)
-
initialize(variables[0].utc, ::Time.find_zone(variables[1]), variables[2].utc)
-
end
-
-
# Ensure proxy class responds to all methods that underlying time instance
-
# responds to.
-
1
def respond_to_missing?(sym, include_priv)
-
# consistently respond false to acts_like?(:date), regardless of whether #time is a Time or DateTime
-
return false if sym.to_sym == :acts_like_date?
-
time.respond_to?(sym, include_priv)
-
end
-
-
# Send the missing method to +time+ instance, and wrap result in a new
-
# TimeWithZone with the existing +time_zone+.
-
1
def method_missing(sym, *args, &block)
-
wrap_with_time_zone time.__send__(sym, *args, &block)
-
rescue NoMethodError => e
-
raise e, e.message.sub(time.inspect, self.inspect), e.backtrace
-
end
-
-
1
private
-
1
def get_period_and_ensure_valid_local_time(period)
-
# we don't want a Time.local instance enforcing its own DST rules as well,
-
# so transfer time values to a utc constructor if necessary
-
@time = transfer_time_values_to_utc_constructor(@time) unless @time.utc?
-
begin
-
period || @time_zone.period_for_local(@time)
-
rescue ::TZInfo::PeriodNotFound
-
# time is in the "spring forward" hour gap, so we're moving the time forward one hour and trying again
-
@time += 1.hour
-
retry
-
end
-
end
-
-
1
def transfer_time_values_to_utc_constructor(time)
-
::Time.utc(time.year, time.month, time.day, time.hour, time.min, time.sec, Rational(time.nsec, 1000))
-
end
-
-
1
def duration_of_variable_length?(obj)
-
ActiveSupport::Duration === obj && obj.parts.any? {|p| [:years, :months, :days].include?(p[0]) }
-
end
-
-
1
def wrap_with_time_zone(time)
-
if time.acts_like?(:time)
-
periods = time_zone.periods_for_local(time)
-
self.class.new(nil, time_zone, time, periods.include?(period) ? period : nil)
-
elsif time.is_a?(Range)
-
wrap_with_time_zone(time.begin)..wrap_with_time_zone(time.end)
-
else
-
time
-
end
-
end
-
end
-
end
-
1
require 'tzinfo'
-
1
require 'thread_safe'
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'active_support/core_ext/object/try'
-
-
1
module ActiveSupport
-
# The TimeZone class serves as a wrapper around TZInfo::Timezone instances.
-
# It allows us to do the following:
-
#
-
# * Limit the set of zones provided by TZInfo to a meaningful subset of 146
-
# zones.
-
# * Retrieve and display zones with a friendlier name
-
# (e.g., "Eastern Time (US & Canada)" instead of "America/New_York").
-
# * Lazily load TZInfo::Timezone instances only when they're needed.
-
# * Create ActiveSupport::TimeWithZone instances via TimeZone's +local+,
-
# +parse+, +at+ and +now+ methods.
-
#
-
# If you set <tt>config.time_zone</tt> in the Rails Application, you can
-
# access this TimeZone object via <tt>Time.zone</tt>:
-
#
-
# # application.rb:
-
# class Application < Rails::Application
-
# config.time_zone = 'Eastern Time (US & Canada)'
-
# end
-
#
-
# Time.zone # => #<TimeZone:0x514834...>
-
# Time.zone.name # => "Eastern Time (US & Canada)"
-
# Time.zone.now # => Sun, 18 May 2008 14:30:44 EDT -04:00
-
#
-
# The version of TZInfo bundled with Active Support only includes the
-
# definitions necessary to support the zones defined by the TimeZone class.
-
# If you need to use zones that aren't defined by TimeZone, you'll need to
-
# install the TZInfo gem (if a recent version of the gem is installed locally,
-
# this will be used instead of the bundled version.)
-
1
class TimeZone
-
# Keys are Rails TimeZone names, values are TZInfo identifiers.
-
1
MAPPING = {
-
"International Date Line West" => "Pacific/Midway",
-
"Midway Island" => "Pacific/Midway",
-
"American Samoa" => "Pacific/Pago_Pago",
-
"Hawaii" => "Pacific/Honolulu",
-
"Alaska" => "America/Juneau",
-
"Pacific Time (US & Canada)" => "America/Los_Angeles",
-
"Tijuana" => "America/Tijuana",
-
"Mountain Time (US & Canada)" => "America/Denver",
-
"Arizona" => "America/Phoenix",
-
"Chihuahua" => "America/Chihuahua",
-
"Mazatlan" => "America/Mazatlan",
-
"Central Time (US & Canada)" => "America/Chicago",
-
"Saskatchewan" => "America/Regina",
-
"Guadalajara" => "America/Mexico_City",
-
"Mexico City" => "America/Mexico_City",
-
"Monterrey" => "America/Monterrey",
-
"Central America" => "America/Guatemala",
-
"Eastern Time (US & Canada)" => "America/New_York",
-
"Indiana (East)" => "America/Indiana/Indianapolis",
-
"Bogota" => "America/Bogota",
-
"Lima" => "America/Lima",
-
"Quito" => "America/Lima",
-
"Atlantic Time (Canada)" => "America/Halifax",
-
"Caracas" => "America/Caracas",
-
"La Paz" => "America/La_Paz",
-
"Santiago" => "America/Santiago",
-
"Newfoundland" => "America/St_Johns",
-
"Brasilia" => "America/Sao_Paulo",
-
"Buenos Aires" => "America/Argentina/Buenos_Aires",
-
"Montevideo" => "America/Montevideo",
-
"Georgetown" => "America/Guyana",
-
"Greenland" => "America/Godthab",
-
"Mid-Atlantic" => "Atlantic/South_Georgia",
-
"Azores" => "Atlantic/Azores",
-
"Cape Verde Is." => "Atlantic/Cape_Verde",
-
"Dublin" => "Europe/Dublin",
-
"Edinburgh" => "Europe/London",
-
"Lisbon" => "Europe/Lisbon",
-
"London" => "Europe/London",
-
"Casablanca" => "Africa/Casablanca",
-
"Monrovia" => "Africa/Monrovia",
-
"UTC" => "Etc/UTC",
-
"Belgrade" => "Europe/Belgrade",
-
"Bratislava" => "Europe/Bratislava",
-
"Budapest" => "Europe/Budapest",
-
"Ljubljana" => "Europe/Ljubljana",
-
"Prague" => "Europe/Prague",
-
"Sarajevo" => "Europe/Sarajevo",
-
"Skopje" => "Europe/Skopje",
-
"Warsaw" => "Europe/Warsaw",
-
"Zagreb" => "Europe/Zagreb",
-
"Brussels" => "Europe/Brussels",
-
"Copenhagen" => "Europe/Copenhagen",
-
"Madrid" => "Europe/Madrid",
-
"Paris" => "Europe/Paris",
-
"Amsterdam" => "Europe/Amsterdam",
-
"Berlin" => "Europe/Berlin",
-
"Bern" => "Europe/Berlin",
-
"Rome" => "Europe/Rome",
-
"Stockholm" => "Europe/Stockholm",
-
"Vienna" => "Europe/Vienna",
-
"West Central Africa" => "Africa/Algiers",
-
"Bucharest" => "Europe/Bucharest",
-
"Cairo" => "Africa/Cairo",
-
"Helsinki" => "Europe/Helsinki",
-
"Kyiv" => "Europe/Kiev",
-
"Riga" => "Europe/Riga",
-
"Sofia" => "Europe/Sofia",
-
"Tallinn" => "Europe/Tallinn",
-
"Vilnius" => "Europe/Vilnius",
-
"Athens" => "Europe/Athens",
-
"Istanbul" => "Europe/Istanbul",
-
"Minsk" => "Europe/Minsk",
-
"Jerusalem" => "Asia/Jerusalem",
-
"Harare" => "Africa/Harare",
-
"Pretoria" => "Africa/Johannesburg",
-
"Moscow" => "Europe/Moscow",
-
"St. Petersburg" => "Europe/Moscow",
-
"Volgograd" => "Europe/Moscow",
-
"Kuwait" => "Asia/Kuwait",
-
"Riyadh" => "Asia/Riyadh",
-
"Nairobi" => "Africa/Nairobi",
-
"Baghdad" => "Asia/Baghdad",
-
"Tehran" => "Asia/Tehran",
-
"Abu Dhabi" => "Asia/Muscat",
-
"Muscat" => "Asia/Muscat",
-
"Baku" => "Asia/Baku",
-
"Tbilisi" => "Asia/Tbilisi",
-
"Yerevan" => "Asia/Yerevan",
-
"Kabul" => "Asia/Kabul",
-
"Ekaterinburg" => "Asia/Yekaterinburg",
-
"Islamabad" => "Asia/Karachi",
-
"Karachi" => "Asia/Karachi",
-
"Tashkent" => "Asia/Tashkent",
-
"Chennai" => "Asia/Kolkata",
-
"Kolkata" => "Asia/Kolkata",
-
"Mumbai" => "Asia/Kolkata",
-
"New Delhi" => "Asia/Kolkata",
-
"Kathmandu" => "Asia/Kathmandu",
-
"Astana" => "Asia/Dhaka",
-
"Dhaka" => "Asia/Dhaka",
-
"Sri Jayawardenepura" => "Asia/Colombo",
-
"Almaty" => "Asia/Almaty",
-
"Novosibirsk" => "Asia/Novosibirsk",
-
"Rangoon" => "Asia/Rangoon",
-
"Bangkok" => "Asia/Bangkok",
-
"Hanoi" => "Asia/Bangkok",
-
"Jakarta" => "Asia/Jakarta",
-
"Krasnoyarsk" => "Asia/Krasnoyarsk",
-
"Beijing" => "Asia/Shanghai",
-
"Chongqing" => "Asia/Chongqing",
-
"Hong Kong" => "Asia/Hong_Kong",
-
"Urumqi" => "Asia/Urumqi",
-
"Kuala Lumpur" => "Asia/Kuala_Lumpur",
-
"Singapore" => "Asia/Singapore",
-
"Taipei" => "Asia/Taipei",
-
"Perth" => "Australia/Perth",
-
"Irkutsk" => "Asia/Irkutsk",
-
"Ulaanbaatar" => "Asia/Ulaanbaatar",
-
"Seoul" => "Asia/Seoul",
-
"Osaka" => "Asia/Tokyo",
-
"Sapporo" => "Asia/Tokyo",
-
"Tokyo" => "Asia/Tokyo",
-
"Yakutsk" => "Asia/Yakutsk",
-
"Darwin" => "Australia/Darwin",
-
"Adelaide" => "Australia/Adelaide",
-
"Canberra" => "Australia/Melbourne",
-
"Melbourne" => "Australia/Melbourne",
-
"Sydney" => "Australia/Sydney",
-
"Brisbane" => "Australia/Brisbane",
-
"Hobart" => "Australia/Hobart",
-
"Vladivostok" => "Asia/Vladivostok",
-
"Guam" => "Pacific/Guam",
-
"Port Moresby" => "Pacific/Port_Moresby",
-
"Magadan" => "Asia/Magadan",
-
"Solomon Is." => "Pacific/Guadalcanal",
-
"New Caledonia" => "Pacific/Noumea",
-
"Fiji" => "Pacific/Fiji",
-
"Kamchatka" => "Asia/Kamchatka",
-
"Marshall Is." => "Pacific/Majuro",
-
"Auckland" => "Pacific/Auckland",
-
"Wellington" => "Pacific/Auckland",
-
"Nuku'alofa" => "Pacific/Tongatapu",
-
"Tokelau Is." => "Pacific/Fakaofo",
-
"Chatham Is." => "Pacific/Chatham",
-
"Samoa" => "Pacific/Apia"
-
}
-
-
1
UTC_OFFSET_WITH_COLON = '%s%02d:%02d'
-
1
UTC_OFFSET_WITHOUT_COLON = UTC_OFFSET_WITH_COLON.sub(':', '')
-
-
1
@lazy_zones_map = ThreadSafe::Cache.new
-
-
# Assumes self represents an offset from UTC in seconds (as returned from
-
# Time#utc_offset) and turns this into an +HH:MM formatted string.
-
#
-
# TimeZone.seconds_to_utc_offset(-21_600) # => "-06:00"
-
1
def self.seconds_to_utc_offset(seconds, colon = true)
-
format = colon ? UTC_OFFSET_WITH_COLON : UTC_OFFSET_WITHOUT_COLON
-
sign = (seconds < 0 ? '-' : '+')
-
hours = seconds.abs / 3600
-
minutes = (seconds.abs % 3600) / 60
-
format % [sign, hours, minutes]
-
end
-
-
1
include Comparable
-
1
attr_reader :name
-
1
attr_reader :tzinfo
-
-
# Create a new TimeZone object with the given name and offset. The
-
# offset is the number of seconds that this time zone is offset from UTC
-
# (GMT). Seconds were chosen as the offset unit because that is the unit
-
# that Ruby uses to represent time zone offsets (see Time#utc_offset).
-
1
def initialize(name, utc_offset = nil, tzinfo = nil)
-
1
@name = name
-
1
@utc_offset = utc_offset
-
1
@tzinfo = tzinfo || TimeZone.find_tzinfo(name)
-
1
@current_period = nil
-
end
-
-
# Returns the offset of this time zone from UTC in seconds.
-
1
def utc_offset
-
1
if @utc_offset
-
@utc_offset
-
else
-
1
@current_period ||= tzinfo.try(:current_period)
-
1
@current_period.try(:utc_offset)
-
end
-
end
-
-
# Returns the offset of this time zone as a formatted string, of the
-
# format "+HH:MM".
-
1
def formatted_offset(colon=true, alternate_utc_string = nil)
-
utc_offset == 0 && alternate_utc_string || self.class.seconds_to_utc_offset(utc_offset, colon)
-
end
-
-
# Compare this time zone to the parameter. The two are compared first on
-
# their offsets, and then by name.
-
1
def <=>(zone)
-
return unless zone.respond_to? :utc_offset
-
result = (utc_offset <=> zone.utc_offset)
-
result = (name <=> zone.name) if result == 0
-
result
-
end
-
-
# Compare #name and TZInfo identifier to a supplied regexp, returning +true+
-
# if a match is found.
-
1
def =~(re)
-
re === name || re === MAPPING[name]
-
end
-
-
# Returns a textual representation of this time zone.
-
1
def to_s
-
"(GMT#{formatted_offset}) #{name}"
-
end
-
-
# Method for creating new ActiveSupport::TimeWithZone instance in time zone
-
# of +self+ from given values.
-
#
-
# Time.zone = 'Hawaii' # => "Hawaii"
-
# Time.zone.local(2007, 2, 1, 15, 30, 45) # => Thu, 01 Feb 2007 15:30:45 HST -10:00
-
1
def local(*args)
-
time = Time.utc(*args)
-
ActiveSupport::TimeWithZone.new(nil, self, time)
-
end
-
-
# Method for creating new ActiveSupport::TimeWithZone instance in time zone
-
# of +self+ from number of seconds since the Unix epoch.
-
#
-
# Time.zone = 'Hawaii' # => "Hawaii"
-
# Time.utc(2000).to_f # => 946684800.0
-
# Time.zone.at(946684800.0) # => Fri, 31 Dec 1999 14:00:00 HST -10:00
-
1
def at(secs)
-
Time.at(secs).utc.in_time_zone(self)
-
end
-
-
# Method for creating new ActiveSupport::TimeWithZone instance in time zone
-
# of +self+ from parsed string.
-
#
-
# Time.zone = 'Hawaii' # => "Hawaii"
-
# Time.zone.parse('1999-12-31 14:00:00') # => Fri, 31 Dec 1999 14:00:00 HST -10:00
-
#
-
# If upper components are missing from the string, they are supplied from
-
# TimeZone#now:
-
#
-
# Time.zone.now # => Fri, 31 Dec 1999 14:00:00 HST -10:00
-
# Time.zone.parse('22:30:00') # => Fri, 31 Dec 1999 22:30:00 HST -10:00
-
1
def parse(str, now=now)
-
parts = Date._parse(str, false)
-
return if parts.empty?
-
-
time = Time.new(
-
parts.fetch(:year, now.year),
-
parts.fetch(:mon, now.month),
-
parts.fetch(:mday, now.day),
-
parts.fetch(:hour, 0),
-
parts.fetch(:min, 0),
-
parts.fetch(:sec, 0) + parts.fetch(:sec_fraction, 0),
-
parts.fetch(:offset, 0)
-
)
-
-
if parts[:offset]
-
TimeWithZone.new(time.utc, self)
-
else
-
TimeWithZone.new(nil, self, time)
-
end
-
end
-
-
# Returns an ActiveSupport::TimeWithZone instance representing the current
-
# time in the time zone represented by +self+.
-
#
-
# Time.zone = 'Hawaii' # => "Hawaii"
-
# Time.zone.now # => Wed, 23 Jan 2008 20:24:27 HST -10:00
-
1
def now
-
time_now.utc.in_time_zone(self)
-
end
-
-
# Return the current date in this time zone.
-
1
def today
-
tzinfo.now.to_date
-
end
-
-
# Returns the next date in this time zone.
-
1
def tomorrow
-
today + 1
-
end
-
-
# Returns the previous date in this time zone.
-
1
def yesterday
-
today - 1
-
end
-
-
# Adjust the given time to the simultaneous time in the time zone
-
# represented by +self+. Returns a Time.utc() instance -- if you want an
-
# ActiveSupport::TimeWithZone instance, use Time#in_time_zone() instead.
-
1
def utc_to_local(time)
-
tzinfo.utc_to_local(time)
-
end
-
-
# Adjust the given time to the simultaneous time in UTC. Returns a
-
# Time.utc() instance.
-
1
def local_to_utc(time, dst=true)
-
tzinfo.local_to_utc(time, dst)
-
end
-
-
# Available so that TimeZone instances respond like TZInfo::Timezone
-
# instances.
-
1
def period_for_utc(time)
-
tzinfo.period_for_utc(time)
-
end
-
-
# Available so that TimeZone instances respond like TZInfo::Timezone
-
# instances.
-
1
def period_for_local(time, dst=true)
-
tzinfo.period_for_local(time, dst)
-
end
-
-
1
def periods_for_local(time) #:nodoc:
-
tzinfo.periods_for_local(time)
-
end
-
-
1
def self.find_tzinfo(name)
-
1
TZInfo::TimezoneProxy.new(MAPPING[name] || name)
-
end
-
-
1
class << self
-
1
alias_method :create, :new
-
-
# Returns a TimeZone instance with the given name, or +nil+ if no
-
# such TimeZone instance exists. (This exists to support the use of
-
# this class with the +composed_of+ macro.)
-
1
def new(name)
-
self[name]
-
end
-
-
# Returns an array of all TimeZone objects. There are multiple
-
# TimeZone objects per time zone, in many cases, to make it easier
-
# for users to find their own time zone.
-
1
def all
-
@zones ||= zones_map.values.sort
-
end
-
-
1
def zones_map
-
@zones_map ||= begin
-
MAPPING.each_key {|place| self[place]} # load all the zones
-
@lazy_zones_map
-
end
-
end
-
-
# Locate a specific time zone object. If the argument is a string, it
-
# is interpreted to mean the name of the timezone to locate. If it is a
-
# numeric value it is either the hour offset, or the second offset, of the
-
# timezone to find. (The first one with that offset will be returned.)
-
# Returns +nil+ if no such time zone is known to the system.
-
1
def [](arg)
-
1
case arg
-
when String
-
1
begin
-
2
@lazy_zones_map[arg] ||= create(arg).tap { |tz| tz.utc_offset }
-
rescue TZInfo::InvalidTimezoneIdentifier
-
nil
-
end
-
when Numeric, ActiveSupport::Duration
-
arg *= 3600 if arg.abs <= 13
-
all.find { |z| z.utc_offset == arg.to_i }
-
else
-
raise ArgumentError, "invalid argument to TimeZone[]: #{arg.inspect}"
-
end
-
end
-
-
# A convenience method for returning a collection of TimeZone objects
-
# for time zones in the USA.
-
1
def us_zones
-
@us_zones ||= all.find_all { |z| z.name =~ /US|Arizona|Indiana|Hawaii|Alaska/ }
-
end
-
end
-
-
1
private
-
-
1
def time_now
-
Time.now
-
end
-
end
-
end
-
1
require_relative 'gem_version'
-
-
1
module ActiveSupport
-
# Returns the version of the currently loaded ActiveSupport as a <tt>Gem::Version</tt>
-
1
def self.version
-
gem_version
-
end
-
end
-
1
require 'time'
-
1
require 'base64'
-
1
require 'bigdecimal'
-
1
require 'active_support/core_ext/module/delegation'
-
1
require 'active_support/core_ext/string/inflections'
-
1
require 'active_support/core_ext/date_time/calculations'
-
-
1
module ActiveSupport
-
# = XmlMini
-
#
-
# To use the much faster libxml parser:
-
# gem 'libxml-ruby', '=0.9.7'
-
# XmlMini.backend = 'LibXML'
-
1
module XmlMini
-
1
extend self
-
-
# This module decorates files deserialized using Hash.from_xml with
-
# the <tt>original_filename</tt> and <tt>content_type</tt> methods.
-
1
module FileLike #:nodoc:
-
1
attr_writer :original_filename, :content_type
-
-
1
def original_filename
-
@original_filename || 'untitled'
-
end
-
-
1
def content_type
-
@content_type || 'application/octet-stream'
-
end
-
end
-
-
DEFAULT_ENCODINGS = {
-
"binary" => "base64"
-
1
} unless defined?(DEFAULT_ENCODINGS)
-
-
TYPE_NAMES = {
-
"Symbol" => "symbol",
-
"Fixnum" => "integer",
-
"Bignum" => "integer",
-
"BigDecimal" => "decimal",
-
"Float" => "float",
-
"TrueClass" => "boolean",
-
"FalseClass" => "boolean",
-
"Date" => "date",
-
"DateTime" => "dateTime",
-
"Time" => "dateTime",
-
"Array" => "array",
-
"Hash" => "hash"
-
1
} unless defined?(TYPE_NAMES)
-
-
FORMATTING = {
-
"symbol" => Proc.new { |symbol| symbol.to_s },
-
"date" => Proc.new { |date| date.to_s(:db) },
-
"dateTime" => Proc.new { |time| time.xmlschema },
-
"binary" => Proc.new { |binary| ::Base64.encode64(binary) },
-
"yaml" => Proc.new { |yaml| yaml.to_yaml }
-
1
} unless defined?(FORMATTING)
-
-
# TODO use regexp instead of Date.parse
-
1
unless defined?(PARSING)
-
1
PARSING = {
-
"symbol" => Proc.new { |symbol| symbol.to_s.to_sym },
-
"date" => Proc.new { |date| ::Date.parse(date) },
-
"datetime" => Proc.new { |time| Time.xmlschema(time).utc rescue ::DateTime.parse(time).utc },
-
"integer" => Proc.new { |integer| integer.to_i },
-
"float" => Proc.new { |float| float.to_f },
-
"decimal" => Proc.new { |number| BigDecimal(number) },
-
"boolean" => Proc.new { |boolean| %w(1 true).include?(boolean.to_s.strip) },
-
"string" => Proc.new { |string| string.to_s },
-
"yaml" => Proc.new { |yaml| YAML::load(yaml) rescue yaml },
-
"base64Binary" => Proc.new { |bin| ::Base64.decode64(bin) },
-
"binary" => Proc.new { |bin, entity| _parse_binary(bin, entity) },
-
"file" => Proc.new { |file, entity| _parse_file(file, entity) }
-
}
-
-
1
PARSING.update(
-
"double" => PARSING["float"],
-
"dateTime" => PARSING["datetime"]
-
)
-
end
-
-
1
delegate :parse, :to => :backend
-
-
1
def backend
-
current_thread_backend || @backend
-
end
-
-
1
def backend=(name)
-
1
backend = name && cast_backend_name_to_module(name)
-
1
self.current_thread_backend = backend if current_thread_backend
-
1
@backend = backend
-
end
-
-
1
def with_backend(name)
-
old_backend = current_thread_backend
-
self.current_thread_backend = name && cast_backend_name_to_module(name)
-
yield
-
ensure
-
self.current_thread_backend = old_backend
-
end
-
-
1
def to_tag(key, value, options)
-
type_name = options.delete(:type)
-
merged_options = options.merge(:root => key, :skip_instruct => true)
-
-
if value.is_a?(::Method) || value.is_a?(::Proc)
-
if value.arity == 1
-
value.call(merged_options)
-
else
-
value.call(merged_options, key.to_s.singularize)
-
end
-
elsif value.respond_to?(:to_xml)
-
value.to_xml(merged_options)
-
else
-
type_name ||= TYPE_NAMES[value.class.name]
-
type_name ||= value.class.name if value && !value.respond_to?(:to_str)
-
type_name = type_name.to_s if type_name
-
type_name = "dateTime" if type_name == "datetime"
-
-
key = rename_key(key.to_s, options)
-
-
attributes = options[:skip_types] || type_name.nil? ? { } : { :type => type_name }
-
attributes[:nil] = true if value.nil?
-
-
encoding = options[:encoding] || DEFAULT_ENCODINGS[type_name]
-
attributes[:encoding] = encoding if encoding
-
-
formatted_value = FORMATTING[type_name] && !value.nil? ?
-
FORMATTING[type_name].call(value) : value
-
-
options[:builder].tag!(key, formatted_value, attributes)
-
end
-
end
-
-
1
def rename_key(key, options = {})
-
camelize = options[:camelize]
-
dasherize = !options.has_key?(:dasherize) || options[:dasherize]
-
if camelize
-
key = true == camelize ? key.camelize : key.camelize(camelize)
-
end
-
key = _dasherize(key) if dasherize
-
key
-
end
-
-
1
protected
-
-
1
def _dasherize(key)
-
# $2 must be a non-greedy regex for this to work
-
left, middle, right = /\A(_*)(.*?)(_*)\Z/.match(key.strip)[1,3]
-
"#{left}#{middle.tr('_ ', '--')}#{right}"
-
end
-
-
# TODO: Add support for other encodings
-
1
def _parse_binary(bin, entity) #:nodoc:
-
case entity['encoding']
-
when 'base64'
-
::Base64.decode64(bin)
-
else
-
bin
-
end
-
end
-
-
1
def _parse_file(file, entity)
-
f = StringIO.new(::Base64.decode64(file))
-
f.extend(FileLike)
-
f.original_filename = entity['name']
-
f.content_type = entity['content_type']
-
f
-
end
-
-
1
private
-
-
1
def current_thread_backend
-
1
Thread.current[:xml_mini_backend]
-
end
-
-
1
def current_thread_backend=(name)
-
Thread.current[:xml_mini_backend] = name && cast_backend_name_to_module(name)
-
end
-
-
1
def cast_backend_name_to_module(name)
-
1
if name.is_a?(Module)
-
name
-
else
-
1
require "active_support/xml_mini/#{name.downcase}"
-
1
ActiveSupport.const_get("XmlMini_#{name}")
-
end
-
end
-
end
-
-
1
XmlMini.backend = 'REXML'
-
end
-
1
require 'active_support/core_ext/kernel/reporting'
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'stringio'
-
-
1
module ActiveSupport
-
1
module XmlMini_REXML #:nodoc:
-
1
extend self
-
-
1
CONTENT_KEY = '__content__'.freeze
-
-
# Parse an XML Document string or IO into a simple hash.
-
#
-
# Same as XmlSimple::xml_in but doesn't shoot itself in the foot,
-
# and uses the defaults from Active Support.
-
#
-
# data::
-
# XML Document string or IO to parse
-
1
def parse(data)
-
if !data.respond_to?(:read)
-
data = StringIO.new(data || '')
-
end
-
-
char = data.getc
-
if char.nil?
-
{}
-
else
-
data.ungetc(char)
-
silence_warnings { require 'rexml/document' } unless defined?(REXML::Document)
-
doc = REXML::Document.new(data)
-
-
if doc.root
-
merge_element!({}, doc.root)
-
else
-
raise REXML::ParseException,
-
"The document #{doc.to_s.inspect} does not have a valid root"
-
end
-
end
-
end
-
-
1
private
-
# Convert an XML element and merge into the hash
-
#
-
# hash::
-
# Hash to merge the converted element into.
-
# element::
-
# XML element to merge into hash
-
1
def merge_element!(hash, element)
-
merge!(hash, element.name, collapse(element))
-
end
-
-
# Actually converts an XML document element into a data structure.
-
#
-
# element::
-
# The document element to be collapsed.
-
1
def collapse(element)
-
hash = get_attributes(element)
-
-
if element.has_elements?
-
element.each_element {|child| merge_element!(hash, child) }
-
merge_texts!(hash, element) unless empty_content?(element)
-
hash
-
else
-
merge_texts!(hash, element)
-
end
-
end
-
-
# Merge all the texts of an element into the hash
-
#
-
# hash::
-
# Hash to add the converted element to.
-
# element::
-
# XML element whose texts are to me merged into the hash
-
1
def merge_texts!(hash, element)
-
unless element.has_text?
-
hash
-
else
-
# must use value to prevent double-escaping
-
texts = ''
-
element.texts.each { |t| texts << t.value }
-
merge!(hash, CONTENT_KEY, texts)
-
end
-
end
-
-
# Adds a new key/value pair to an existing Hash. If the key to be added
-
# already exists and the existing value associated with key is not
-
# an Array, it will be wrapped in an Array. Then the new value is
-
# appended to that Array.
-
#
-
# hash::
-
# Hash to add key/value pair to.
-
# key::
-
# Key to be added.
-
# value::
-
# Value to be associated with key.
-
1
def merge!(hash, key, value)
-
if hash.has_key?(key)
-
if hash[key].instance_of?(Array)
-
hash[key] << value
-
else
-
hash[key] = [hash[key], value]
-
end
-
elsif value.instance_of?(Array)
-
hash[key] = [value]
-
else
-
hash[key] = value
-
end
-
hash
-
end
-
-
# Converts the attributes array of an XML element into a hash.
-
# Returns an empty Hash if node has no attributes.
-
#
-
# element::
-
# XML element to extract attributes from.
-
1
def get_attributes(element)
-
attributes = {}
-
element.attributes.each { |n,v| attributes[n] = v }
-
attributes
-
end
-
-
# Determines if a document element has text content
-
#
-
# element::
-
# XML element to be checked.
-
1
def empty_content?(element)
-
element.texts.join.blank?
-
end
-
end
-
end
-
1
require 'arel/crud'
-
1
require 'arel/factory_methods'
-
-
1
require 'arel/expressions'
-
1
require 'arel/predications'
-
1
require 'arel/window_predications'
-
1
require 'arel/math'
-
1
require 'arel/alias_predication'
-
1
require 'arel/order_predications'
-
1
require 'arel/table'
-
1
require 'arel/attributes'
-
1
require 'arel/compatibility/wheres'
-
-
#### these are deprecated
-
1
require 'arel/expression'
-
####
-
-
1
require 'arel/visitors'
-
-
1
require 'arel/tree_manager'
-
1
require 'arel/insert_manager'
-
1
require 'arel/select_manager'
-
1
require 'arel/update_manager'
-
1
require 'arel/delete_manager'
-
1
require 'arel/nodes'
-
-
-
#### these are deprecated
-
1
require 'arel/deprecated'
-
1
require 'arel/sql/engine'
-
1
require 'arel/sql_literal'
-
####
-
-
1
module Arel
-
1
VERSION = '5.0.1'
-
-
1
def self.sql raw_sql
-
Arel::Nodes::SqlLiteral.new raw_sql
-
end
-
-
1
def self.star
-
sql '*'
-
end
-
## Convenience Alias
-
1
Node = Arel::Nodes::Node
-
end
-
1
module Arel
-
1
module AliasPredication
-
1
def as other
-
Nodes::As.new self, Nodes::SqlLiteral.new(other)
-
end
-
end
-
end
-
1
require 'arel/attributes/attribute'
-
-
1
module Arel
-
1
module Attributes
-
###
-
# Factory method to wrap a raw database +column+ to an Arel Attribute.
-
1
def self.for column
-
case column.type
-
when :string, :text, :binary then String
-
when :integer then Integer
-
when :float then Float
-
when :decimal then Decimal
-
when :date, :datetime, :timestamp, :time then Time
-
when :boolean then Boolean
-
else
-
Undefined
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Attributes
-
1
class Attribute < Struct.new :relation, :name
-
1
include Arel::Expressions
-
1
include Arel::Predications
-
1
include Arel::AliasPredication
-
1
include Arel::OrderPredications
-
1
include Arel::Math
-
-
###
-
# Create a node for lowering this attribute
-
1
def lower
-
relation.lower self
-
end
-
end
-
-
1
class String < Attribute; end
-
1
class Time < Attribute; end
-
1
class Boolean < Attribute; end
-
1
class Decimal < Attribute; end
-
1
class Float < Attribute; end
-
1
class Integer < Attribute; end
-
1
class Undefined < Attribute; end
-
end
-
-
1
Attribute = Attributes::Attribute
-
end
-
1
module Arel
-
1
module Compatibility # :nodoc:
-
1
class Wheres # :nodoc:
-
1
include Enumerable
-
-
1
module Value # :nodoc:
-
1
attr_accessor :visitor
-
1
def value
-
visitor.accept self
-
end
-
-
1
def name
-
super.to_sym
-
end
-
end
-
-
1
def initialize engine, collection
-
@engine = engine
-
@collection = collection
-
end
-
-
1
def each
-
to_sql = Visitors::ToSql.new @engine
-
-
@collection.each { |c|
-
c.extend(Value)
-
c.visitor = to_sql
-
yield c
-
}
-
end
-
end
-
end
-
end
-
1
module Arel
-
###
-
# FIXME hopefully we can remove this
-
1
module Crud
-
1
def compile_update values, pk
-
um = UpdateManager.new @engine
-
-
if Nodes::SqlLiteral === values
-
relation = @ctx.from
-
else
-
relation = values.first.first.relation
-
end
-
um.key = pk
-
um.table relation
-
um.set values
-
um.take @ast.limit.expr if @ast.limit
-
um.order(*@ast.orders)
-
um.wheres = @ctx.wheres
-
um
-
end
-
-
1
def compile_insert values
-
im = create_insert
-
im.insert values
-
im
-
end
-
-
1
def create_insert
-
InsertManager.new @engine
-
end
-
-
1
def compile_delete
-
dm = DeleteManager.new @engine
-
dm.wheres = @ctx.wheres
-
dm.from @ctx.froms
-
dm
-
end
-
-
end
-
end
-
1
module Arel
-
1
class DeleteManager < Arel::TreeManager
-
1
def initialize engine
-
super
-
@ast = Nodes::DeleteStatement.new
-
@ctx = @ast
-
end
-
-
1
def from relation
-
@ast.relation = relation
-
self
-
end
-
-
1
def wheres= list
-
@ast.wheres = list
-
end
-
end
-
end
-
1
module Arel
-
1
InnerJoin = Nodes::InnerJoin
-
1
OuterJoin = Nodes::OuterJoin
-
end
-
1
module Arel
-
1
module Expression
-
1
include Arel::OrderPredications
-
end
-
end
-
1
module Arel
-
1
module Expressions
-
1
def count distinct = false
-
Nodes::Count.new [self], distinct
-
end
-
-
1
def sum
-
Nodes::Sum.new [self], Nodes::SqlLiteral.new('sum_id')
-
end
-
-
1
def maximum
-
Nodes::Max.new [self], Nodes::SqlLiteral.new('max_id')
-
end
-
-
1
def minimum
-
Nodes::Min.new [self], Nodes::SqlLiteral.new('min_id')
-
end
-
-
1
def average
-
Nodes::Avg.new [self], Nodes::SqlLiteral.new('avg_id')
-
end
-
-
1
def extract field
-
Nodes::Extract.new [self], field
-
end
-
end
-
end
-
1
module Arel
-
###
-
# Methods for creating various nodes
-
1
module FactoryMethods
-
1
def create_true
-
Arel::Nodes::True.new
-
end
-
-
1
def create_false
-
Arel::Nodes::False.new
-
end
-
-
1
def create_table_alias relation, name
-
Nodes::TableAlias.new(relation, name)
-
end
-
-
1
def create_join to, constraint = nil, klass = Nodes::InnerJoin
-
klass.new(to, constraint)
-
end
-
-
1
def create_string_join to
-
create_join to, nil, Nodes::StringJoin
-
end
-
-
1
def create_and clauses
-
Nodes::And.new clauses
-
end
-
-
1
def create_on expr
-
Nodes::On.new expr
-
end
-
-
1
def grouping expr
-
Nodes::Grouping.new expr
-
end
-
-
###
-
# Create a LOWER() function
-
1
def lower column
-
Nodes::NamedFunction.new 'LOWER', [column]
-
end
-
end
-
end
-
1
module Arel
-
1
class InsertManager < Arel::TreeManager
-
1
def initialize engine
-
super
-
@ast = Nodes::InsertStatement.new
-
end
-
-
1
def into table
-
@ast.relation = table
-
self
-
end
-
-
1
def columns; @ast.columns end
-
1
def values= val; @ast.values = val; end
-
-
1
def insert fields
-
return if fields.empty?
-
-
if String === fields
-
@ast.values = SqlLiteral.new(fields)
-
else
-
@ast.relation ||= fields.first.first.relation
-
-
values = []
-
-
fields.each do |column, value|
-
@ast.columns << column
-
values << value
-
end
-
@ast.values = create_values values, @ast.columns
-
end
-
end
-
-
1
def create_values values, columns
-
Nodes::Values.new values, columns
-
end
-
end
-
end
-
1
module Arel
-
1
module Math
-
1
def *(other)
-
Arel::Nodes::Multiplication.new(self, other)
-
end
-
-
1
def +(other)
-
Arel::Nodes::Grouping.new(Arel::Nodes::Addition.new(self, other))
-
end
-
-
1
def -(other)
-
Arel::Nodes::Grouping.new(Arel::Nodes::Subtraction.new(self, other))
-
end
-
-
1
def /(other)
-
Arel::Nodes::Division.new(self, other)
-
end
-
end
-
end
-
# node
-
1
require 'arel/nodes/node'
-
1
require 'arel/nodes/select_statement'
-
1
require 'arel/nodes/select_core'
-
1
require 'arel/nodes/insert_statement'
-
1
require 'arel/nodes/update_statement'
-
-
# terminal
-
-
1
require 'arel/nodes/terminal'
-
1
require 'arel/nodes/true'
-
1
require 'arel/nodes/false'
-
-
# unary
-
1
require 'arel/nodes/unary'
-
1
require 'arel/nodes/grouping'
-
1
require 'arel/nodes/ascending'
-
1
require 'arel/nodes/descending'
-
1
require 'arel/nodes/unqualified_column'
-
1
require 'arel/nodes/with'
-
-
# binary
-
1
require 'arel/nodes/binary'
-
1
require 'arel/nodes/equality'
-
1
require 'arel/nodes/in' # Why is this subclassed from equality?
-
1
require 'arel/nodes/join_source'
-
1
require 'arel/nodes/delete_statement'
-
1
require 'arel/nodes/table_alias'
-
1
require 'arel/nodes/infix_operation'
-
1
require 'arel/nodes/over'
-
-
# nary
-
1
require 'arel/nodes/and'
-
-
# function
-
# FIXME: Function + Alias can be rewritten as a Function and Alias node.
-
# We should make Function a Unary node and deprecate the use of "aliaz"
-
1
require 'arel/nodes/function'
-
1
require 'arel/nodes/count'
-
1
require 'arel/nodes/extract'
-
1
require 'arel/nodes/values'
-
1
require 'arel/nodes/named_function'
-
-
# windows
-
1
require 'arel/nodes/window'
-
-
# joins
-
1
require 'arel/nodes/inner_join'
-
1
require 'arel/nodes/outer_join'
-
1
require 'arel/nodes/string_join'
-
-
1
require 'arel/nodes/sql_literal'
-
1
module Arel
-
1
module Nodes
-
1
class And < Arel::Nodes::Node
-
1
attr_reader :children
-
-
1
def initialize children, right = nil
-
super()
-
unless Array === children
-
warn "(#{caller.first}) AND nodes should be created with a list"
-
children = [children, right]
-
end
-
@children = children
-
end
-
-
1
def left
-
children.first
-
end
-
-
1
def right
-
children[1]
-
end
-
-
1
def hash
-
children.hash
-
end
-
-
1
def eql? other
-
self.class == other.class &&
-
self.children == other.children
-
end
-
1
alias :== :eql?
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Ascending < Ordering
-
-
1
def reverse
-
Descending.new(expr)
-
end
-
-
1
def direction
-
:asc
-
end
-
-
1
def ascending?
-
true
-
end
-
-
1
def descending?
-
false
-
end
-
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Binary < Arel::Nodes::Node
-
1
attr_accessor :left, :right
-
-
1
def initialize left, right
-
super()
-
@left = left
-
@right = right
-
end
-
-
1
def initialize_copy other
-
super
-
@left = @left.clone if @left
-
@right = @right.clone if @right
-
end
-
-
1
def hash
-
[@left, @right].hash
-
end
-
-
1
def eql? other
-
self.class == other.class &&
-
self.left == other.left &&
-
self.right == other.right
-
end
-
1
alias :== :eql?
-
end
-
-
%w{
-
As
-
Assignment
-
Between
-
DoesNotMatch
-
GreaterThan
-
GreaterThanOrEqual
-
Join
-
LessThan
-
LessThanOrEqual
-
Matches
-
NotEqual
-
NotIn
-
Or
-
Union
-
UnionAll
-
Intersect
-
Except
-
1
}.each do |name|
-
17
const_set name, Class.new(Binary)
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Count < Arel::Nodes::Function
-
1
def initialize expr, distinct = false, aliaz = nil
-
super(expr, aliaz)
-
@distinct = distinct
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class DeleteStatement < Arel::Nodes::Binary
-
1
alias :relation :left
-
1
alias :relation= :left=
-
1
alias :wheres :right
-
1
alias :wheres= :right=
-
-
1
def initialize relation = nil, wheres = []
-
super
-
end
-
-
1
def initialize_copy other
-
super
-
@right = @right.clone
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Descending < Ordering
-
-
1
def reverse
-
Ascending.new(expr)
-
end
-
-
1
def direction
-
:desc
-
end
-
-
1
def ascending?
-
false
-
end
-
-
1
def descending?
-
true
-
end
-
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Equality < Arel::Nodes::Binary
-
1
def operator; :== end
-
1
alias :operand1 :left
-
1
alias :operand2 :right
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
-
1
class Extract < Arel::Nodes::Unary
-
1
include Arel::Expression
-
1
include Arel::Predications
-
-
1
attr_accessor :field
-
1
attr_accessor :alias
-
-
1
def initialize expr, field, aliaz = nil
-
super(expr)
-
@field = field
-
@alias = aliaz && SqlLiteral.new(aliaz)
-
end
-
-
1
def as aliaz
-
self.alias = SqlLiteral.new(aliaz)
-
self
-
end
-
-
1
def hash
-
super ^ [@field, @alias].hash
-
end
-
-
1
def eql? other
-
super &&
-
self.field == other.field &&
-
self.alias == other.alias
-
end
-
1
alias :== :eql?
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class False < Arel::Nodes::Node
-
1
def hash
-
self.class.hash
-
end
-
-
1
def eql? other
-
self.class == other.class
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Function < Arel::Nodes::Node
-
1
include Arel::Expression
-
1
include Arel::Predications
-
1
include Arel::WindowPredications
-
1
attr_accessor :expressions, :alias, :distinct
-
-
1
def initialize expr, aliaz = nil
-
super()
-
@expressions = expr
-
@alias = aliaz && SqlLiteral.new(aliaz)
-
@distinct = false
-
end
-
-
1
def as aliaz
-
self.alias = SqlLiteral.new(aliaz)
-
self
-
end
-
-
1
def hash
-
[@expressions, @alias, @distinct].hash
-
end
-
-
1
def eql? other
-
self.class == other.class &&
-
self.expressions == other.expressions &&
-
self.alias == other.alias &&
-
self.distinct == other.distinct
-
end
-
end
-
-
%w{
-
Sum
-
Exists
-
Max
-
Min
-
Avg
-
1
}.each do |name|
-
5
const_set(name, Class.new(Function))
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Grouping < Unary
-
1
include Arel::Predications
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class In < Equality
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
-
1
class InfixOperation < Binary
-
1
include Arel::Expressions
-
1
include Arel::Predications
-
1
include Arel::OrderPredications
-
1
include Arel::AliasPredication
-
1
include Arel::Math
-
-
1
attr_reader :operator
-
-
1
def initialize operator, left, right
-
super(left, right)
-
@operator = operator
-
end
-
end
-
-
1
class Multiplication < InfixOperation
-
1
def initialize left, right
-
super(:*, left, right)
-
end
-
end
-
-
1
class Division < InfixOperation
-
1
def initialize left, right
-
super(:/, left, right)
-
end
-
end
-
-
1
class Addition < InfixOperation
-
1
def initialize left, right
-
super(:+, left, right)
-
end
-
end
-
-
1
class Subtraction < InfixOperation
-
1
def initialize left, right
-
super(:-, left, right)
-
end
-
end
-
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class InnerJoin < Arel::Nodes::Join
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class InsertStatement < Arel::Nodes::Node
-
1
attr_accessor :relation, :columns, :values
-
-
1
def initialize
-
super()
-
@relation = nil
-
@columns = []
-
@values = nil
-
end
-
-
1
def initialize_copy other
-
super
-
@columns = @columns.clone
-
@values = @values.clone if @values
-
end
-
-
1
def hash
-
[@relation, @columns, @values].hash
-
end
-
-
1
def eql? other
-
self.class == other.class &&
-
self.relation == other.relation &&
-
self.columns == other.columns &&
-
self.values == other.values
-
end
-
1
alias :== :eql?
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
###
-
# Class that represents a join source
-
#
-
# http://www.sqlite.org/syntaxdiagrams.html#join-source
-
-
1
class JoinSource < Arel::Nodes::Binary
-
1
def initialize single_source, joinop = []
-
super
-
end
-
-
1
def empty?
-
!left && right.empty?
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class NamedFunction < Arel::Nodes::Function
-
1
attr_accessor :name
-
-
1
def initialize name, expr, aliaz = nil
-
super(expr, aliaz)
-
@name = name
-
end
-
-
1
def hash
-
super ^ @name.hash
-
end
-
-
1
def eql? other
-
super && self.name == other.name
-
end
-
1
alias :== :eql?
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
###
-
# Abstract base class for all AST nodes
-
1
class Node
-
1
include Arel::FactoryMethods
-
1
include Enumerable
-
-
1
if $DEBUG
-
def _caller
-
@caller
-
end
-
-
def initialize
-
@caller = caller.dup
-
end
-
end
-
-
###
-
# Factory method to create a Nodes::Not node that has the recipient of
-
# the caller as a child.
-
1
def not
-
Nodes::Not.new self
-
end
-
-
###
-
# Factory method to create a Nodes::Grouping node that has an Nodes::Or
-
# node as a child.
-
1
def or right
-
Nodes::Grouping.new Nodes::Or.new(self, right)
-
end
-
-
###
-
# Factory method to create an Nodes::And node.
-
1
def and right
-
Nodes::And.new [self, right]
-
end
-
-
# FIXME: this method should go away. I don't like people calling
-
# to_sql on non-head nodes. This forces us to walk the AST until we
-
# can find a node that has a "relation" member.
-
#
-
# Maybe we should just use `Table.engine`? :'(
-
1
def to_sql engine = Table.engine
-
engine.connection.visitor.accept self
-
end
-
-
# Iterate through AST, nodes will be yielded depth-first
-
1
def each &block
-
return enum_for(:each) unless block_given?
-
-
::Arel::Visitors::DepthFirst.new(block).accept self
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class OuterJoin < Arel::Nodes::Join
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
-
1
class Over < Binary
-
1
include Arel::AliasPredication
-
-
1
def initialize(left, right = nil)
-
super(left, right)
-
end
-
-
1
def operator; 'OVER' end
-
end
-
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class SelectCore < Arel::Nodes::Node
-
1
attr_accessor :top, :projections, :wheres, :groups, :windows
-
1
attr_accessor :having, :source, :set_quantifier
-
-
1
def initialize
-
super()
-
@source = JoinSource.new nil
-
@top = nil
-
-
# http://savage.net.au/SQL/sql-92.bnf.html#set%20quantifier
-
@set_quantifier = nil
-
@projections = []
-
@wheres = []
-
@groups = []
-
@having = nil
-
@windows = []
-
end
-
-
1
def from
-
@source.left
-
end
-
-
1
def from= value
-
@source.left = value
-
end
-
-
1
alias :froms= :from=
-
1
alias :froms :from
-
-
1
def initialize_copy other
-
super
-
@source = @source.clone if @source
-
@projections = @projections.clone
-
@wheres = @wheres.clone
-
@groups = @groups.clone
-
@having = @having.clone if @having
-
@windows = @windows.clone
-
end
-
-
1
def hash
-
[
-
@source, @top, @set_quantifier, @projections,
-
@wheres, @groups, @having, @windows
-
].hash
-
end
-
-
1
def eql? other
-
self.class == other.class &&
-
self.source == other.source &&
-
self.top == other.top &&
-
self.set_quantifier == other.set_quantifier &&
-
self.projections == other.projections &&
-
self.wheres == other.wheres &&
-
self.groups == other.groups &&
-
self.having == other.having &&
-
self.windows == other.windows
-
end
-
1
alias :== :eql?
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class SelectStatement < Arel::Nodes::Node
-
1
attr_reader :cores
-
1
attr_accessor :limit, :orders, :lock, :offset, :with
-
-
1
def initialize cores = [SelectCore.new]
-
super()
-
@cores = cores
-
@orders = []
-
@limit = nil
-
@lock = nil
-
@offset = nil
-
@with = nil
-
end
-
-
1
def initialize_copy other
-
super
-
@cores = @cores.map { |x| x.clone }
-
@orders = @orders.map { |x| x.clone }
-
end
-
-
1
def hash
-
[@cores, @orders, @limit, @lock, @offset, @with].hash
-
end
-
-
1
def eql? other
-
self.class == other.class &&
-
self.cores == other.cores &&
-
self.orders == other.orders &&
-
self.limit == other.limit &&
-
self.lock == other.lock &&
-
self.offset == other.offset &&
-
self.with == other.with
-
end
-
1
alias :== :eql?
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class SqlLiteral < String
-
1
include Arel::Expressions
-
1
include Arel::Predications
-
1
include Arel::AliasPredication
-
1
include Arel::OrderPredications
-
-
1
def encode_with(coder)
-
coder.scalar = self.to_s
-
end
-
end
-
-
1
class BindParam < SqlLiteral
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class StringJoin < Arel::Nodes::Join
-
1
def initialize left, right = nil
-
super
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class TableAlias < Arel::Nodes::Binary
-
1
alias :name :right
-
1
alias :relation :left
-
1
alias :table_alias :name
-
-
1
def [] name
-
Attribute.new(self, name)
-
end
-
-
1
def table_name
-
relation.respond_to?(:name) ? relation.name : name
-
end
-
-
1
def engine
-
relation.engine
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Distinct < Arel::Nodes::Node
-
1
def hash
-
self.class.hash
-
end
-
-
1
def eql? other
-
self.class == other.class
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class True < Arel::Nodes::Node
-
1
def hash
-
self.class.hash
-
end
-
-
1
def eql? other
-
self.class == other.class
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Unary < Arel::Nodes::Node
-
1
attr_accessor :expr
-
1
alias :value :expr
-
-
1
def initialize expr
-
super()
-
@expr = expr
-
end
-
-
1
def hash
-
@expr.hash
-
end
-
-
1
def eql? other
-
self.class == other.class &&
-
self.expr == other.expr
-
end
-
1
alias :== :eql?
-
end
-
-
%w{
-
Bin
-
Group
-
Having
-
Limit
-
Not
-
Offset
-
On
-
Ordering
-
Top
-
Lock
-
DistinctOn
-
1
}.each do |name|
-
11
const_set(name, Class.new(Unary))
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class UnqualifiedColumn < Arel::Nodes::Unary
-
1
alias :attribute :expr
-
1
alias :attribute= :expr=
-
-
1
def relation
-
@expr.relation
-
end
-
-
1
def column
-
@expr.column
-
end
-
-
1
def name
-
@expr.name
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class UpdateStatement < Arel::Nodes::Node
-
1
attr_accessor :relation, :wheres, :values, :orders, :limit
-
1
attr_accessor :key
-
-
1
def initialize
-
@relation = nil
-
@wheres = []
-
@values = []
-
@orders = []
-
@limit = nil
-
@key = nil
-
end
-
-
1
def initialize_copy other
-
super
-
@wheres = @wheres.clone
-
@values = @values.clone
-
end
-
-
1
def hash
-
[@relation, @wheres, @values, @orders, @limit, @key].hash
-
end
-
-
1
def eql? other
-
self.class == other.class &&
-
self.relation == other.relation &&
-
self.wheres == other.wheres &&
-
self.values == other.values &&
-
self.orders == other.orders &&
-
self.limit == other.limit &&
-
self.key == other.key
-
end
-
1
alias :== :eql?
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Values < Arel::Nodes::Binary
-
1
alias :expressions :left
-
1
alias :expressions= :left=
-
1
alias :columns :right
-
1
alias :columns= :right=
-
-
1
def initialize exprs, columns = []
-
super
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class With < Arel::Nodes::Unary
-
1
alias children expr
-
end
-
-
1
class WithRecursive < With; end
-
end
-
end
-
-
1
module Arel
-
1
module OrderPredications
-
-
1
def asc
-
Nodes::Ascending.new self
-
end
-
-
1
def desc
-
Nodes::Descending.new self
-
end
-
-
end
-
end
-
1
module Arel
-
1
module Predications
-
1
def not_eq other
-
Nodes::NotEqual.new self, other
-
end
-
-
1
def not_eq_any others
-
grouping_any :not_eq, others
-
end
-
-
1
def not_eq_all others
-
grouping_all :not_eq, others
-
end
-
-
1
def eq other
-
Nodes::Equality.new self, other
-
end
-
-
1
def eq_any others
-
grouping_any :eq, others
-
end
-
-
1
def eq_all others
-
grouping_all :eq, others
-
end
-
-
1
def in other
-
case other
-
when Arel::SelectManager
-
Arel::Nodes::In.new(self, other.ast)
-
when Range
-
if other.begin == -Float::INFINITY && other.end == Float::INFINITY
-
Nodes::NotIn.new self, []
-
elsif other.end == Float::INFINITY
-
Nodes::GreaterThanOrEqual.new(self, other.begin)
-
elsif other.begin == -Float::INFINITY && other.exclude_end?
-
Nodes::LessThan.new(self, other.end)
-
elsif other.begin == -Float::INFINITY
-
Nodes::LessThanOrEqual.new(self, other.end)
-
elsif other.exclude_end?
-
left = Nodes::GreaterThanOrEqual.new(self, other.begin)
-
right = Nodes::LessThan.new(self, other.end)
-
Nodes::And.new [left, right]
-
else
-
Nodes::Between.new(self, Nodes::And.new([other.begin, other.end]))
-
end
-
else
-
Nodes::In.new self, other
-
end
-
end
-
-
1
def in_any others
-
grouping_any :in, others
-
end
-
-
1
def in_all others
-
grouping_all :in, others
-
end
-
-
1
def not_in other
-
case other
-
when Arel::SelectManager
-
Arel::Nodes::NotIn.new(self, other.ast)
-
when Range
-
if other.begin == -Float::INFINITY && other.end == Float::INFINITY
-
Nodes::In.new self, []
-
elsif other.end == Float::INFINITY
-
Nodes::LessThan.new(self, other.begin)
-
elsif other.begin == -Float::INFINITY && other.exclude_end?
-
Nodes::GreaterThanOrEqual.new(self, other.end)
-
elsif other.begin == -Float::INFINITY
-
Nodes::GreaterThan.new(self, other.end)
-
elsif other.exclude_end?
-
left = Nodes::LessThan.new(self, other.begin)
-
right = Nodes::GreaterThanOrEqual.new(self, other.end)
-
Nodes::Or.new left, right
-
else
-
left = Nodes::LessThan.new(self, other.begin)
-
right = Nodes::GreaterThan.new(self, other.end)
-
Nodes::Or.new left, right
-
end
-
else
-
Nodes::NotIn.new self, other
-
end
-
end
-
-
1
def not_in_any others
-
grouping_any :not_in, others
-
end
-
-
1
def not_in_all others
-
grouping_all :not_in, others
-
end
-
-
1
def matches other
-
Nodes::Matches.new self, other
-
end
-
-
1
def matches_any others
-
grouping_any :matches, others
-
end
-
-
1
def matches_all others
-
grouping_all :matches, others
-
end
-
-
1
def does_not_match other
-
Nodes::DoesNotMatch.new self, other
-
end
-
-
1
def does_not_match_any others
-
grouping_any :does_not_match, others
-
end
-
-
1
def does_not_match_all others
-
grouping_all :does_not_match, others
-
end
-
-
1
def gteq right
-
Nodes::GreaterThanOrEqual.new self, right
-
end
-
-
1
def gteq_any others
-
grouping_any :gteq, others
-
end
-
-
1
def gteq_all others
-
grouping_all :gteq, others
-
end
-
-
1
def gt right
-
Nodes::GreaterThan.new self, right
-
end
-
-
1
def gt_any others
-
grouping_any :gt, others
-
end
-
-
1
def gt_all others
-
grouping_all :gt, others
-
end
-
-
1
def lt right
-
Nodes::LessThan.new self, right
-
end
-
-
1
def lt_any others
-
grouping_any :lt, others
-
end
-
-
1
def lt_all others
-
grouping_all :lt, others
-
end
-
-
1
def lteq right
-
Nodes::LessThanOrEqual.new self, right
-
end
-
-
1
def lteq_any others
-
grouping_any :lteq, others
-
end
-
-
1
def lteq_all others
-
grouping_all :lteq, others
-
end
-
-
1
private
-
-
1
def grouping_any method_id, others
-
nodes = others.map {|expr| send(method_id, expr)}
-
Nodes::Grouping.new nodes.inject { |memo,node|
-
Nodes::Or.new(memo, node)
-
}
-
end
-
-
1
def grouping_all method_id, others
-
Nodes::Grouping.new Nodes::And.new(others.map {|expr| send(method_id, expr)})
-
end
-
end
-
end
-
1
module Arel
-
1
class SelectManager < Arel::TreeManager
-
1
include Arel::Crud
-
-
1
STRING_OR_SYMBOL_CLASS = [Symbol, String]
-
-
1
def initialize engine, table = nil
-
super(engine)
-
@ast = Nodes::SelectStatement.new
-
@ctx = @ast.cores.last
-
from table
-
end
-
-
1
def initialize_copy other
-
super
-
@ctx = @ast.cores.last
-
end
-
-
1
def limit
-
@ast.limit && @ast.limit.expr
-
end
-
1
alias :taken :limit
-
-
1
def constraints
-
@ctx.wheres
-
end
-
-
1
def offset
-
@ast.offset && @ast.offset.expr
-
end
-
-
1
def skip amount
-
if amount
-
@ast.offset = Nodes::Offset.new(amount)
-
else
-
@ast.offset = nil
-
end
-
self
-
end
-
1
alias :offset= :skip
-
-
###
-
# Produces an Arel::Nodes::Exists node
-
1
def exists
-
Arel::Nodes::Exists.new @ast
-
end
-
-
1
def as other
-
create_table_alias grouping(@ast), Nodes::SqlLiteral.new(other)
-
end
-
-
1
def lock locking = Arel.sql('FOR UPDATE')
-
case locking
-
when true
-
locking = Arel.sql('FOR UPDATE')
-
when Arel::Nodes::SqlLiteral
-
when String
-
locking = Arel.sql locking
-
end
-
-
@ast.lock = Nodes::Lock.new(locking)
-
self
-
end
-
-
1
def locked
-
@ast.lock
-
end
-
-
1
def on *exprs
-
@ctx.source.right.last.right = Nodes::On.new(collapse(exprs))
-
self
-
end
-
-
1
def group *columns
-
columns.each do |column|
-
# FIXME: backwards compat
-
column = Nodes::SqlLiteral.new(column) if String === column
-
column = Nodes::SqlLiteral.new(column.to_s) if Symbol === column
-
-
@ctx.groups.push Nodes::Group.new column
-
end
-
self
-
end
-
-
1
def from table
-
table = Nodes::SqlLiteral.new(table) if String === table
-
# FIXME: this is a hack to support
-
# test_with_two_tables_in_from_without_getting_double_quoted
-
# from the AR tests.
-
-
case table
-
when Nodes::Join
-
@ctx.source.right << table
-
else
-
@ctx.source.left = table
-
end
-
-
self
-
end
-
-
1
def froms
-
@ast.cores.map { |x| x.from }.compact
-
end
-
-
1
def join relation, klass = Nodes::InnerJoin
-
return self unless relation
-
-
case relation
-
when String, Nodes::SqlLiteral
-
raise if relation.blank?
-
klass = Nodes::StringJoin
-
end
-
-
@ctx.source.right << create_join(relation, nil, klass)
-
self
-
end
-
-
1
def having *exprs
-
@ctx.having = Nodes::Having.new(collapse(exprs, @ctx.having))
-
self
-
end
-
-
1
def window name
-
window = Nodes::NamedWindow.new(name)
-
@ctx.windows.push window
-
window
-
end
-
-
1
def project *projections
-
# FIXME: converting these to SQLLiterals is probably not good, but
-
# rails tests require it.
-
@ctx.projections.concat projections.map { |x|
-
STRING_OR_SYMBOL_CLASS.include?(x.class) ? SqlLiteral.new(x.to_s) : x
-
}
-
self
-
end
-
-
1
def projections
-
@ctx.projections
-
end
-
-
1
def projections= projections
-
@ctx.projections = projections
-
end
-
-
1
def distinct(value = true)
-
if value
-
@ctx.set_quantifier = Arel::Nodes::Distinct.new
-
else
-
@ctx.set_quantifier = nil
-
end
-
end
-
-
1
def order *expr
-
# FIXME: We SHOULD NOT be converting these to SqlLiteral automatically
-
@ast.orders.concat expr.map { |x|
-
STRING_OR_SYMBOL_CLASS.include?(x.class) ? Nodes::SqlLiteral.new(x.to_s) : x
-
}
-
self
-
end
-
-
1
def orders
-
@ast.orders
-
end
-
-
1
def where_sql
-
return if @ctx.wheres.empty?
-
-
viz = Visitors::WhereSql.new @engine.connection
-
Nodes::SqlLiteral.new viz.accept @ctx
-
end
-
-
1
def union operation, other = nil
-
if other
-
node_class = Nodes.const_get("Union#{operation.to_s.capitalize}")
-
else
-
other = operation
-
node_class = Nodes::Union
-
end
-
-
node_class.new self.ast, other.ast
-
end
-
-
1
def intersect other
-
Nodes::Intersect.new ast, other.ast
-
end
-
-
1
def except other
-
Nodes::Except.new ast, other.ast
-
end
-
1
alias :minus :except
-
-
1
def with *subqueries
-
if subqueries.first.is_a? Symbol
-
node_class = Nodes.const_get("With#{subqueries.shift.to_s.capitalize}")
-
else
-
node_class = Nodes::With
-
end
-
@ast.with = node_class.new(subqueries.flatten)
-
-
self
-
end
-
-
1
def take limit
-
if limit
-
@ast.limit = Nodes::Limit.new(limit)
-
@ctx.top = Nodes::Top.new(limit)
-
else
-
@ast.limit = nil
-
@ctx.top = nil
-
end
-
self
-
end
-
1
alias limit= take
-
-
1
def join_sql
-
return nil if @ctx.source.right.empty?
-
-
sql = visitor.dup.extend(Visitors::JoinSql).accept @ctx
-
Nodes::SqlLiteral.new sql
-
end
-
-
1
def order_clauses
-
visitor = Visitors::OrderClauses.new(@engine.connection)
-
visitor.accept(@ast).map { |x|
-
Nodes::SqlLiteral.new x
-
}
-
end
-
-
1
def join_sources
-
@ctx.source.right
-
end
-
-
1
def source
-
@ctx.source
-
end
-
-
1
def joins manager
-
if $VERBOSE
-
warn "joins is deprecated and will be removed in 4.0.0"
-
warn "please remove your call to joins from #{caller.first}"
-
end
-
manager.join_sql
-
end
-
-
1
class Row < Struct.new(:data) # :nodoc:
-
1
def id
-
data['id']
-
end
-
-
1
def method_missing(name, *args)
-
name = name.to_s
-
return data[name] if data.key?(name)
-
super
-
end
-
end
-
-
1
def to_a # :nodoc:
-
warn "to_a is deprecated. Please remove it from #{caller[0]}"
-
# FIXME: I think `select` should be made public...
-
@engine.connection.send(:select, to_sql, 'AREL').map { |x| Row.new(x) }
-
end
-
-
1
private
-
1
def collapse exprs, existing = nil
-
exprs = exprs.unshift(existing.expr) if existing
-
exprs = exprs.compact.map { |expr|
-
if String === expr
-
# FIXME: Don't do this automatically
-
Arel.sql(expr)
-
else
-
expr
-
end
-
}
-
-
if exprs.length == 1
-
exprs.first
-
else
-
create_and exprs
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Sql
-
1
class Engine
-
1
def self.new thing
-
#warn "#{caller.first} -- Engine will be removed"
-
thing
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
class SqlLiteral < Nodes::SqlLiteral
-
end
-
end
-
1
module Arel
-
1
class Table
-
1
include Arel::Crud
-
1
include Arel::FactoryMethods
-
-
1
@engine = nil
-
2
class << self; attr_accessor :engine; end
-
-
1
attr_accessor :name, :engine, :aliases, :table_alias
-
-
# TableAlias and Table both have a #table_name which is the name of the underlying table
-
1
alias :table_name :name
-
-
1
def initialize name, engine = Table.engine
-
@name = name.to_s
-
@engine = engine
-
@columns = nil
-
@aliases = []
-
@table_alias = nil
-
@primary_key = nil
-
-
if Hash === engine
-
@engine = engine[:engine] || Table.engine
-
-
# Sometime AR sends an :as parameter to table, to let the table know
-
# that it is an Alias. We may want to override new, and return a
-
# TableAlias node?
-
@table_alias = engine[:as] unless engine[:as].to_s == @name
-
end
-
end
-
-
1
def primary_key
-
if $VERBOSE
-
warn <<-eowarn
-
primary_key (#{caller.first}) is deprecated and will be removed in Arel 4.0.0
-
eowarn
-
end
-
@primary_key ||= begin
-
primary_key_name = @engine.connection.primary_key(name)
-
# some tables might be without primary key
-
primary_key_name && self[primary_key_name]
-
end
-
end
-
-
1
def alias name = "#{self.name}_2"
-
Nodes::TableAlias.new(self, name).tap do |node|
-
@aliases << node
-
end
-
end
-
-
1
def from table
-
SelectManager.new(@engine, table)
-
end
-
-
1
def joins manager
-
if $VERBOSE
-
warn "joins is deprecated and will be removed in 4.0.0"
-
warn "please remove your call to joins from #{caller.first}"
-
end
-
nil
-
end
-
-
1
def join relation, klass = Nodes::InnerJoin
-
return from(self) unless relation
-
-
case relation
-
when String, Nodes::SqlLiteral
-
raise if relation.blank?
-
klass = Nodes::StringJoin
-
end
-
-
from(self).join(relation, klass)
-
end
-
-
1
def group *columns
-
from(self).group(*columns)
-
end
-
-
1
def order *expr
-
from(self).order(*expr)
-
end
-
-
1
def where condition
-
from(self).where condition
-
end
-
-
1
def project *things
-
from(self).project(*things)
-
end
-
-
1
def take amount
-
from(self).take amount
-
end
-
-
1
def skip amount
-
from(self).skip amount
-
end
-
-
1
def having expr
-
from(self).having expr
-
end
-
-
1
def [] name
-
::Arel::Attribute.new self, name
-
end
-
-
1
def select_manager
-
SelectManager.new(@engine)
-
end
-
-
1
def insert_manager
-
InsertManager.new(@engine)
-
end
-
-
1
def hash
-
# Perf note: aliases, table alias and engine is excluded from the hash
-
# aliases can have a loop back to this table breaking hashes in parent
-
# relations, for the vast majority of cases @name is unique to a query
-
@name.hash
-
end
-
-
1
def eql? other
-
self.class == other.class &&
-
self.name == other.name &&
-
self.engine == other.engine &&
-
self.aliases == other.aliases &&
-
self.table_alias == other.table_alias
-
end
-
1
alias :== :eql?
-
-
1
private
-
-
1
def attributes_for columns
-
return nil unless columns
-
-
columns.map do |column|
-
Attributes.for(column).new self, column.name.to_sym
-
end
-
end
-
-
end
-
end
-
1
module Arel
-
1
class TreeManager
-
1
include Arel::FactoryMethods
-
-
1
attr_reader :ast, :engine
-
-
1
attr_accessor :bind_values
-
-
1
def initialize engine
-
@engine = engine
-
@ctx = nil
-
@bind_values = []
-
end
-
-
1
def to_dot
-
Visitors::Dot.new.accept @ast
-
end
-
-
1
def visitor
-
engine.connection.visitor
-
end
-
-
1
def to_sql
-
visitor.accept @ast
-
end
-
-
1
def initialize_copy other
-
super
-
@ast = @ast.clone
-
end
-
-
1
def where expr
-
if Arel::TreeManager === expr
-
expr = expr.ast
-
end
-
@ctx.wheres << expr
-
self
-
end
-
end
-
end
-
1
module Arel
-
1
class UpdateManager < Arel::TreeManager
-
1
def initialize engine
-
super
-
@ast = Nodes::UpdateStatement.new
-
@ctx = @ast
-
end
-
-
1
def take limit
-
@ast.limit = Nodes::Limit.new(limit) if limit
-
self
-
end
-
-
1
def key= key
-
@ast.key = key
-
end
-
-
1
def key
-
@ast.key
-
end
-
-
1
def order *expr
-
@ast.orders = expr
-
self
-
end
-
-
###
-
# UPDATE +table+
-
1
def table table
-
@ast.relation = table
-
self
-
end
-
-
1
def wheres= exprs
-
@ast.wheres = exprs
-
end
-
-
1
def where expr
-
@ast.wheres << expr
-
self
-
end
-
-
1
def set values
-
if String === values
-
@ast.values = [values]
-
else
-
@ast.values = values.map { |column,value|
-
Nodes::Assignment.new(
-
Nodes::UnqualifiedColumn.new(column),
-
value
-
)
-
}
-
end
-
self
-
end
-
end
-
end
-
1
require 'arel/visitors/visitor'
-
1
require 'arel/visitors/depth_first'
-
1
require 'arel/visitors/to_sql'
-
1
require 'arel/visitors/sqlite'
-
1
require 'arel/visitors/postgresql'
-
1
require 'arel/visitors/mysql'
-
1
require 'arel/visitors/mssql'
-
1
require 'arel/visitors/oracle'
-
1
require 'arel/visitors/join_sql'
-
1
require 'arel/visitors/where_sql'
-
1
require 'arel/visitors/order_clauses'
-
1
require 'arel/visitors/dot'
-
1
require 'arel/visitors/ibm_db'
-
1
require 'arel/visitors/informix'
-
-
1
module Arel
-
1
module Visitors
-
1
VISITORS = {
-
'postgresql' => Arel::Visitors::PostgreSQL,
-
'mysql' => Arel::Visitors::MySQL,
-
'mysql2' => Arel::Visitors::MySQL,
-
'mssql' => Arel::Visitors::MSSQL,
-
'sqlserver' => Arel::Visitors::MSSQL,
-
'oracle_enhanced' => Arel::Visitors::Oracle,
-
'sqlite' => Arel::Visitors::SQLite,
-
'sqlite3' => Arel::Visitors::SQLite,
-
'ibm_db' => Arel::Visitors::IBM_DB,
-
'informix' => Arel::Visitors::Informix,
-
}
-
-
1
ENGINE_VISITORS = Hash.new do |hash, engine|
-
pool = engine.connection_pool
-
adapter = pool.spec.config[:adapter]
-
hash[engine] = (VISITORS[adapter] || Visitors::ToSql).new(engine)
-
end
-
-
1
def self.visitor_for engine
-
ENGINE_VISITORS[engine]
-
end
-
2
class << self; alias :for :visitor_for; end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
module BindVisitor
-
1
def initialize target
-
@block = nil
-
super
-
end
-
-
1
def accept node, &block
-
@block = block if block_given?
-
super
-
end
-
-
1
private
-
-
1
def visit_Arel_Nodes_Assignment o, a
-
if o.right.is_a? Arel::Nodes::BindParam
-
"#{visit o.left, a} = #{visit o.right, a}"
-
else
-
super
-
end
-
end
-
-
1
def visit_Arel_Nodes_BindParam o, a
-
if @block
-
@block.call
-
else
-
super
-
end
-
end
-
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class DepthFirst < Arel::Visitors::Visitor
-
1
def initialize block = nil
-
@block = block || Proc.new
-
end
-
-
1
private
-
-
1
def visit o, a = nil
-
super
-
@block.call o
-
end
-
-
1
def unary o, a
-
visit o.expr, a
-
end
-
1
alias :visit_Arel_Nodes_Group :unary
-
1
alias :visit_Arel_Nodes_Grouping :unary
-
1
alias :visit_Arel_Nodes_Having :unary
-
1
alias :visit_Arel_Nodes_Limit :unary
-
1
alias :visit_Arel_Nodes_Not :unary
-
1
alias :visit_Arel_Nodes_Offset :unary
-
1
alias :visit_Arel_Nodes_On :unary
-
1
alias :visit_Arel_Nodes_Ordering :unary
-
1
alias :visit_Arel_Nodes_Ascending :unary
-
1
alias :visit_Arel_Nodes_Descending :unary
-
1
alias :visit_Arel_Nodes_Top :unary
-
1
alias :visit_Arel_Nodes_UnqualifiedColumn :unary
-
-
1
def function o, a
-
visit o.expressions, a
-
visit o.alias, a
-
visit o.distinct, a
-
end
-
1
alias :visit_Arel_Nodes_Avg :function
-
1
alias :visit_Arel_Nodes_Exists :function
-
1
alias :visit_Arel_Nodes_Max :function
-
1
alias :visit_Arel_Nodes_Min :function
-
1
alias :visit_Arel_Nodes_Sum :function
-
-
1
def visit_Arel_Nodes_NamedFunction o, a
-
visit o.name, a
-
visit o.expressions, a
-
visit o.distinct, a
-
visit o.alias, a
-
end
-
-
1
def visit_Arel_Nodes_Count o, a
-
visit o.expressions, a
-
visit o.alias, a
-
visit o.distinct, a
-
end
-
-
1
def nary o, a
-
o.children.each { |child| visit child, a }
-
end
-
1
alias :visit_Arel_Nodes_And :nary
-
-
1
def binary o, a
-
visit o.left, a
-
visit o.right, a
-
end
-
1
alias :visit_Arel_Nodes_As :binary
-
1
alias :visit_Arel_Nodes_Assignment :binary
-
1
alias :visit_Arel_Nodes_Between :binary
-
1
alias :visit_Arel_Nodes_DeleteStatement :binary
-
1
alias :visit_Arel_Nodes_DoesNotMatch :binary
-
1
alias :visit_Arel_Nodes_Equality :binary
-
1
alias :visit_Arel_Nodes_GreaterThan :binary
-
1
alias :visit_Arel_Nodes_GreaterThanOrEqual :binary
-
1
alias :visit_Arel_Nodes_In :binary
-
1
alias :visit_Arel_Nodes_InfixOperation :binary
-
1
alias :visit_Arel_Nodes_JoinSource :binary
-
1
alias :visit_Arel_Nodes_InnerJoin :binary
-
1
alias :visit_Arel_Nodes_LessThan :binary
-
1
alias :visit_Arel_Nodes_LessThanOrEqual :binary
-
1
alias :visit_Arel_Nodes_Matches :binary
-
1
alias :visit_Arel_Nodes_NotEqual :binary
-
1
alias :visit_Arel_Nodes_NotIn :binary
-
1
alias :visit_Arel_Nodes_Or :binary
-
1
alias :visit_Arel_Nodes_OuterJoin :binary
-
1
alias :visit_Arel_Nodes_TableAlias :binary
-
1
alias :visit_Arel_Nodes_Values :binary
-
-
1
def visit_Arel_Nodes_StringJoin o, a
-
visit o.left, a
-
end
-
-
1
def visit_Arel_Attribute o, a
-
visit o.relation, a
-
visit o.name, a
-
end
-
1
alias :visit_Arel_Attributes_Integer :visit_Arel_Attribute
-
1
alias :visit_Arel_Attributes_Float :visit_Arel_Attribute
-
1
alias :visit_Arel_Attributes_String :visit_Arel_Attribute
-
1
alias :visit_Arel_Attributes_Time :visit_Arel_Attribute
-
1
alias :visit_Arel_Attributes_Boolean :visit_Arel_Attribute
-
1
alias :visit_Arel_Attributes_Attribute :visit_Arel_Attribute
-
1
alias :visit_Arel_Attributes_Decimal :visit_Arel_Attribute
-
-
1
def visit_Arel_Table o, a
-
visit o.name, a
-
end
-
-
1
def terminal o, a
-
end
-
1
alias :visit_ActiveSupport_Multibyte_Chars :terminal
-
1
alias :visit_ActiveSupport_StringInquirer :terminal
-
1
alias :visit_Arel_Nodes_Lock :terminal
-
1
alias :visit_Arel_Nodes_Node :terminal
-
1
alias :visit_Arel_Nodes_SqlLiteral :terminal
-
1
alias :visit_Arel_Nodes_BindParam :terminal
-
1
alias :visit_Arel_Nodes_Window :terminal
-
1
alias :visit_Arel_SqlLiteral :terminal
-
1
alias :visit_BigDecimal :terminal
-
1
alias :visit_Bignum :terminal
-
1
alias :visit_Class :terminal
-
1
alias :visit_Date :terminal
-
1
alias :visit_DateTime :terminal
-
1
alias :visit_FalseClass :terminal
-
1
alias :visit_Fixnum :terminal
-
1
alias :visit_Float :terminal
-
1
alias :visit_NilClass :terminal
-
1
alias :visit_String :terminal
-
1
alias :visit_Symbol :terminal
-
1
alias :visit_Time :terminal
-
1
alias :visit_TrueClass :terminal
-
-
1
def visit_Arel_Nodes_InsertStatement o, a
-
visit o.relation, a
-
visit o.columns, a
-
visit o.values, a
-
end
-
-
1
def visit_Arel_Nodes_SelectCore o, a
-
visit o.projections, a
-
visit o.source, a
-
visit o.wheres, a
-
visit o.groups, a
-
visit o.windows, a
-
visit o.having, a
-
end
-
-
1
def visit_Arel_Nodes_SelectStatement o, a
-
visit o.cores, a
-
visit o.orders, a
-
visit o.limit, a
-
visit o.lock, a
-
visit o.offset, a
-
end
-
-
1
def visit_Arel_Nodes_UpdateStatement o, a
-
visit o.relation, a
-
visit o.values, a
-
visit o.wheres, a
-
visit o.orders, a
-
visit o.limit, a
-
end
-
-
1
def visit_Array o, a
-
o.each { |i| visit i, a }
-
end
-
-
1
def visit_Hash o, a
-
o.each { |k,v| visit(k, a); visit(v, a) }
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class Dot < Arel::Visitors::Visitor
-
1
class Node # :nodoc:
-
1
attr_accessor :name, :id, :fields
-
-
1
def initialize name, id, fields = []
-
@name = name
-
@id = id
-
@fields = fields
-
end
-
end
-
-
1
class Edge < Struct.new :name, :from, :to # :nodoc:
-
end
-
-
1
def initialize
-
@nodes = []
-
@edges = []
-
@node_stack = []
-
@edge_stack = []
-
@seen = {}
-
end
-
-
1
def accept object
-
super
-
to_dot
-
end
-
-
1
private
-
1
def visit_Arel_Nodes_Ordering o, a
-
visit_edge o, a, "expr"
-
end
-
-
1
def visit_Arel_Nodes_TableAlias o, a
-
visit_edge o, a, "name"
-
visit_edge o, a, "relation"
-
end
-
-
1
def visit_Arel_Nodes_Count o, a
-
visit_edge o, a, "expressions"
-
visit_edge o, a, "distinct"
-
end
-
-
1
def visit_Arel_Nodes_Values o, a
-
visit_edge o, a, "expressions"
-
end
-
-
1
def visit_Arel_Nodes_StringJoin o, a
-
visit_edge o, a, "left"
-
end
-
-
1
def visit_Arel_Nodes_InnerJoin o, a
-
visit_edge o, a, "left"
-
visit_edge o, a, "right"
-
end
-
1
alias :visit_Arel_Nodes_OuterJoin :visit_Arel_Nodes_InnerJoin
-
-
1
def visit_Arel_Nodes_DeleteStatement o, a
-
visit_edge o, a, "relation"
-
visit_edge o, a, "wheres"
-
end
-
-
1
def unary o, a
-
visit_edge o, a, "expr"
-
end
-
1
alias :visit_Arel_Nodes_Group :unary
-
1
alias :visit_Arel_Nodes_Grouping :unary
-
1
alias :visit_Arel_Nodes_Having :unary
-
1
alias :visit_Arel_Nodes_Limit :unary
-
1
alias :visit_Arel_Nodes_Not :unary
-
1
alias :visit_Arel_Nodes_Offset :unary
-
1
alias :visit_Arel_Nodes_On :unary
-
1
alias :visit_Arel_Nodes_Top :unary
-
1
alias :visit_Arel_Nodes_UnqualifiedColumn :unary
-
1
alias :visit_Arel_Nodes_Preceding :unary
-
1
alias :visit_Arel_Nodes_Following :unary
-
1
alias :visit_Arel_Nodes_Rows :unary
-
1
alias :visit_Arel_Nodes_Range :unary
-
-
1
def window o, a
-
visit_edge o, a, "orders"
-
visit_edge o, a, "framing"
-
end
-
1
alias :visit_Arel_Nodes_Window :window
-
-
1
def named_window o, a
-
visit_edge o, a, "orders"
-
visit_edge o, a, "framing"
-
visit_edge o, a, "name"
-
end
-
1
alias :visit_Arel_Nodes_NamedWindow :named_window
-
-
1
def function o, a
-
visit_edge o, a, "expressions"
-
visit_edge o, a, "distinct"
-
visit_edge o, a, "alias"
-
end
-
1
alias :visit_Arel_Nodes_Exists :function
-
1
alias :visit_Arel_Nodes_Min :function
-
1
alias :visit_Arel_Nodes_Max :function
-
1
alias :visit_Arel_Nodes_Avg :function
-
1
alias :visit_Arel_Nodes_Sum :function
-
-
1
def extract o, a
-
visit_edge o, a, "expressions"
-
visit_edge o, a, "alias"
-
end
-
1
alias :visit_Arel_Nodes_Extract :extract
-
-
1
def visit_Arel_Nodes_NamedFunction o, a
-
visit_edge o, a, "name"
-
visit_edge o, a, "expressions"
-
visit_edge o, a, "distinct"
-
visit_edge o, a, "alias"
-
end
-
-
1
def visit_Arel_Nodes_InsertStatement o, a
-
visit_edge o, a, "relation"
-
visit_edge o, a, "columns"
-
visit_edge o, a, "values"
-
end
-
-
1
def visit_Arel_Nodes_SelectCore o, a
-
visit_edge o, a, "source"
-
visit_edge o, a, "projections"
-
visit_edge o, a, "wheres"
-
visit_edge o, a, "windows"
-
end
-
-
1
def visit_Arel_Nodes_SelectStatement o, a
-
visit_edge o, a, "cores"
-
visit_edge o, a, "limit"
-
visit_edge o, a, "orders"
-
visit_edge o, a, "offset"
-
end
-
-
1
def visit_Arel_Nodes_UpdateStatement o, a
-
visit_edge o, a, "relation"
-
visit_edge o, a, "wheres"
-
visit_edge o, a, "values"
-
end
-
-
1
def visit_Arel_Table o, a
-
visit_edge o, a, "name"
-
end
-
-
1
def visit_Arel_Attribute o, a
-
visit_edge o, a, "relation"
-
visit_edge o, a, "name"
-
end
-
1
alias :visit_Arel_Attributes_Integer :visit_Arel_Attribute
-
1
alias :visit_Arel_Attributes_Float :visit_Arel_Attribute
-
1
alias :visit_Arel_Attributes_String :visit_Arel_Attribute
-
1
alias :visit_Arel_Attributes_Time :visit_Arel_Attribute
-
1
alias :visit_Arel_Attributes_Boolean :visit_Arel_Attribute
-
1
alias :visit_Arel_Attributes_Attribute :visit_Arel_Attribute
-
-
1
def nary o, a
-
o.children.each_with_index do |x,i|
-
edge(i) { visit x, a }
-
end
-
end
-
1
alias :visit_Arel_Nodes_And :nary
-
-
1
def binary o, a
-
visit_edge o, a, "left"
-
visit_edge o, a, "right"
-
end
-
1
alias :visit_Arel_Nodes_As :binary
-
1
alias :visit_Arel_Nodes_Assignment :binary
-
1
alias :visit_Arel_Nodes_Between :binary
-
1
alias :visit_Arel_Nodes_DoesNotMatch :binary
-
1
alias :visit_Arel_Nodes_Equality :binary
-
1
alias :visit_Arel_Nodes_GreaterThan :binary
-
1
alias :visit_Arel_Nodes_GreaterThanOrEqual :binary
-
1
alias :visit_Arel_Nodes_In :binary
-
1
alias :visit_Arel_Nodes_JoinSource :binary
-
1
alias :visit_Arel_Nodes_LessThan :binary
-
1
alias :visit_Arel_Nodes_LessThanOrEqual :binary
-
1
alias :visit_Arel_Nodes_Matches :binary
-
1
alias :visit_Arel_Nodes_NotEqual :binary
-
1
alias :visit_Arel_Nodes_NotIn :binary
-
1
alias :visit_Arel_Nodes_Or :binary
-
1
alias :visit_Arel_Nodes_Over :binary
-
-
1
def visit_String o, a
-
@node_stack.last.fields << o
-
end
-
1
alias :visit_Time :visit_String
-
1
alias :visit_Date :visit_String
-
1
alias :visit_DateTime :visit_String
-
1
alias :visit_NilClass :visit_String
-
1
alias :visit_TrueClass :visit_String
-
1
alias :visit_FalseClass :visit_String
-
1
alias :visit_Arel_SqlLiteral :visit_String
-
1
alias :visit_Arel_Nodes_BindParam :visit_String
-
1
alias :visit_Fixnum :visit_String
-
1
alias :visit_BigDecimal :visit_String
-
1
alias :visit_Float :visit_String
-
1
alias :visit_Symbol :visit_String
-
1
alias :visit_Arel_Nodes_SqlLiteral :visit_String
-
-
1
def visit_Hash o, a
-
o.each_with_index do |pair, i|
-
edge("pair_#{i}") { visit pair, a }
-
end
-
end
-
-
1
def visit_Array o, a
-
o.each_with_index do |x,i|
-
edge(i) { visit x, a }
-
end
-
end
-
-
1
def visit_edge o, a, method
-
edge(method) { visit o.send(method), a }
-
end
-
-
1
def visit o, a = nil
-
if node = @seen[o.object_id]
-
@edge_stack.last.to = node
-
return
-
end
-
-
node = Node.new(o.class.name, o.object_id)
-
@seen[node.id] = node
-
@nodes << node
-
with_node node do
-
super
-
end
-
end
-
-
1
def edge name
-
edge = Edge.new(name, @node_stack.last)
-
@edge_stack.push edge
-
@edges << edge
-
yield
-
@edge_stack.pop
-
end
-
-
1
def with_node node
-
if edge = @edge_stack.last
-
edge.to = node
-
end
-
-
@node_stack.push node
-
yield
-
@node_stack.pop
-
end
-
-
1
def quote string
-
string.to_s.gsub('"', '\"')
-
end
-
-
1
def to_dot
-
"digraph \"Arel\" {\nnode [width=0.375,height=0.25,shape=record];\n" +
-
@nodes.map { |node|
-
label = "<f0>#{node.name}"
-
-
node.fields.each_with_index do |field, i|
-
label << "|<f#{i + 1}>#{quote field}"
-
end
-
-
"#{node.id} [label=\"#{label}\"];"
-
}.join("\n") + "\n" + @edges.map { |edge|
-
"#{edge.from.id} -> #{edge.to.id} [label=\"#{edge.name}\"];"
-
}.join("\n") + "\n}"
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class IBM_DB < Arel::Visitors::ToSql
-
1
private
-
-
1
def visit_Arel_Nodes_Limit o, a
-
"FETCH FIRST #{visit o.expr, a} ROWS ONLY"
-
end
-
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class Informix < Arel::Visitors::ToSql
-
1
private
-
1
def visit_Arel_Nodes_SelectStatement o, a
-
[
-
"SELECT",
-
(visit(o.offset, a) if o.offset),
-
(visit(o.limit, a) if o.limit),
-
o.cores.map { |x| visit_Arel_Nodes_SelectCore x, a }.join,
-
("ORDER BY #{o.orders.map { |x| visit x, a }.join(', ')}" unless o.orders.empty?),
-
(visit(o.lock, a) if o.lock),
-
].compact.join ' '
-
end
-
1
def visit_Arel_Nodes_SelectCore o, a
-
[
-
"#{o.projections.map { |x| visit x, a }.join ', '}",
-
("FROM #{visit(o.source, a)}" if o.source && !o.source.empty?),
-
("WHERE #{o.wheres.map { |x| visit x, a }.join ' AND ' }" unless o.wheres.empty?),
-
("GROUP BY #{o.groups.map { |x| visit x, a }.join ', ' }" unless o.groups.empty?),
-
(visit(o.having, a) if o.having),
-
].compact.join ' '
-
end
-
1
def visit_Arel_Nodes_Offset o, a
-
"SKIP #{visit o.expr, a}"
-
end
-
1
def visit_Arel_Nodes_Limit o, a
-
"LIMIT #{visit o.expr, a}"
-
end
-
end
-
end
-
end
-
-
1
module Arel
-
1
module Visitors
-
###
-
# This class produces SQL for JOIN clauses but omits the "single-source"
-
# part of the Join grammar:
-
#
-
# http://www.sqlite.org/syntaxdiagrams.html#join-source
-
#
-
# This visitor is used in SelectManager#join_sql and is for backwards
-
# compatibility with Arel V1.0
-
1
module JoinSql
-
1
private
-
-
1
def visit_Arel_Nodes_SelectCore o, a
-
o.source.right.map { |j| visit j, a }.join ' '
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class MSSQL < Arel::Visitors::ToSql
-
1
private
-
-
# `top` wouldn't really work here. I.e. User.select("distinct first_name").limit(10) would generate
-
# "select top 10 distinct first_name from users", which is invalid query! it should be
-
# "select distinct top 10 first_name from users"
-
1
def visit_Arel_Nodes_Top o, a
-
""
-
end
-
-
1
def visit_Arel_Nodes_SelectStatement o, a
-
if !o.limit && !o.offset
-
return super o, a
-
end
-
-
select_order_by = "ORDER BY #{o.orders.map { |x| visit x, a }.join(', ')}" unless o.orders.empty?
-
-
is_select_count = false
-
sql = o.cores.map { |x|
-
core_order_by = select_order_by || determine_order_by(x, a)
-
if select_count? x
-
x.projections = [row_num_literal(core_order_by)]
-
is_select_count = true
-
else
-
x.projections << row_num_literal(core_order_by)
-
end
-
-
visit_Arel_Nodes_SelectCore x, a
-
}.join
-
-
sql = "SELECT _t.* FROM (#{sql}) as _t WHERE #{get_offset_limit_clause(o)}"
-
# fixme count distinct wouldn't work with limit or offset
-
sql = "SELECT COUNT(1) as count_id FROM (#{sql}) AS subquery" if is_select_count
-
sql
-
end
-
-
1
def get_offset_limit_clause o
-
first_row = o.offset ? o.offset.expr.to_i + 1 : 1
-
last_row = o.limit ? o.limit.expr.to_i - 1 + first_row : nil
-
if last_row
-
" _row_num BETWEEN #{first_row} AND #{last_row}"
-
else
-
" _row_num >= #{first_row}"
-
end
-
end
-
-
1
def determine_order_by x, a
-
unless x.groups.empty?
-
"ORDER BY #{x.groups.map { |g| visit g, a }.join ', ' }"
-
else
-
"ORDER BY #{find_left_table_pk(x.froms, a)}"
-
end
-
end
-
-
1
def row_num_literal order_by
-
Nodes::SqlLiteral.new("ROW_NUMBER() OVER (#{order_by}) as _row_num")
-
end
-
-
1
def select_count? x
-
x.projections.length == 1 && Arel::Nodes::Count === x.projections.first
-
end
-
-
# FIXME raise exception of there is no pk?
-
# FIXME!! Table.primary_key will be deprecated. What is the replacement??
-
1
def find_left_table_pk o, a
-
return visit o.primary_key, a if o.instance_of? Arel::Table
-
find_left_table_pk o.left, a if o.kind_of? Arel::Nodes::Join
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class MySQL < Arel::Visitors::ToSql
-
1
private
-
1
def visit_Arel_Nodes_Union o, a, suppress_parens = false
-
left_result = case o.left
-
when Arel::Nodes::Union
-
visit_Arel_Nodes_Union o.left, a, true
-
else
-
visit o.left, a
-
end
-
-
right_result = case o.right
-
when Arel::Nodes::Union
-
visit_Arel_Nodes_Union o.right, a, true
-
else
-
visit o.right, a
-
end
-
-
if suppress_parens
-
"#{left_result} UNION #{right_result}"
-
else
-
"( #{left_result} UNION #{right_result} )"
-
end
-
end
-
-
1
def visit_Arel_Nodes_Bin o, a
-
"BINARY #{visit o.expr, a}"
-
end
-
-
###
-
# :'(
-
# http://dev.mysql.com/doc/refman/5.0/en/select.html#id3482214
-
1
def visit_Arel_Nodes_SelectStatement o, a
-
o.limit = Arel::Nodes::Limit.new(18446744073709551615) if o.offset && !o.limit
-
super
-
end
-
-
1
def visit_Arel_Nodes_SelectCore o, a
-
o.froms ||= Arel.sql('DUAL')
-
super
-
end
-
-
1
def visit_Arel_Nodes_UpdateStatement o, a
-
[
-
"UPDATE #{visit o.relation, a}",
-
("SET #{o.values.map { |value| visit value, a }.join ', '}" unless o.values.empty?),
-
("WHERE #{o.wheres.map { |x| visit x, a }.join ' AND '}" unless o.wheres.empty?),
-
("ORDER BY #{o.orders.map { |x| visit x, a }.join(', ')}" unless o.orders.empty?),
-
(visit(o.limit, a) if o.limit),
-
].compact.join ' '
-
end
-
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class Oracle < Arel::Visitors::ToSql
-
1
private
-
-
1
def visit_Arel_Nodes_SelectStatement o, a
-
o = order_hacks(o, a)
-
-
# if need to select first records without ORDER BY and GROUP BY and without DISTINCT
-
# then can use simple ROWNUM in WHERE clause
-
if o.limit && o.orders.empty? && !o.offset && o.cores.first.set_quantifier.class.to_s !~ /Distinct/
-
o.cores.last.wheres.push Nodes::LessThanOrEqual.new(
-
Nodes::SqlLiteral.new('ROWNUM'), o.limit.expr
-
)
-
return super
-
end
-
-
if o.limit && o.offset
-
o = o.dup
-
limit = o.limit.expr.to_i
-
offset = o.offset
-
o.offset = nil
-
sql = super(o, a)
-
return <<-eosql
-
SELECT * FROM (
-
SELECT raw_sql_.*, rownum raw_rnum_
-
FROM (#{sql}) raw_sql_
-
WHERE rownum <= #{offset.expr.to_i + limit}
-
)
-
WHERE #{visit offset, a}
-
eosql
-
end
-
-
if o.limit
-
o = o.dup
-
limit = o.limit.expr
-
return "SELECT * FROM (#{super(o, a)}) WHERE ROWNUM <= #{visit limit, a}"
-
end
-
-
if o.offset
-
o = o.dup
-
offset = o.offset
-
o.offset = nil
-
sql = super(o, a)
-
return <<-eosql
-
SELECT * FROM (
-
SELECT raw_sql_.*, rownum raw_rnum_
-
FROM (#{sql}) raw_sql_
-
)
-
WHERE #{visit offset, a}
-
eosql
-
end
-
-
super
-
end
-
-
1
def visit_Arel_Nodes_Limit o, a
-
end
-
-
1
def visit_Arel_Nodes_Offset o, a
-
"raw_rnum_ > #{visit o.expr, a}"
-
end
-
-
1
def visit_Arel_Nodes_Except o, a
-
"( #{visit o.left, a} MINUS #{visit o.right, a} )"
-
end
-
-
1
def visit_Arel_Nodes_UpdateStatement o, a
-
# Oracle does not allow ORDER BY/LIMIT in UPDATEs.
-
if o.orders.any? && o.limit.nil?
-
# However, there is no harm in silently eating the ORDER BY clause if no LIMIT has been provided,
-
# otherwise let the user deal with the error
-
o = o.dup
-
o.orders = []
-
end
-
-
super
-
end
-
-
###
-
# Hacks for the order clauses specific to Oracle
-
1
def order_hacks o, a
-
return o if o.orders.empty?
-
return o unless o.cores.any? do |core|
-
core.projections.any? do |projection|
-
/FIRST_VALUE/ === projection
-
end
-
end
-
# Previous version with join and split broke ORDER BY clause
-
# if it contained functions with several arguments (separated by ',').
-
#
-
# orders = o.orders.map { |x| visit x, a }.join(', ').split(',')
-
orders = o.orders.map do |x|
-
string = visit x, a
-
if string.include?(',')
-
split_order_string(string)
-
else
-
string
-
end
-
end.flatten
-
o.orders = []
-
orders.each_with_index do |order, i|
-
o.orders <<
-
Nodes::SqlLiteral.new("alias_#{i}__#{' DESC' if /\bdesc$/i === order}")
-
end
-
o
-
end
-
-
# Split string by commas but count opening and closing brackets
-
# and ignore commas inside brackets.
-
1
def split_order_string(string)
-
array = []
-
i = 0
-
string.split(',').each do |part|
-
if array[i]
-
array[i] << ',' << part
-
else
-
# to ensure that array[i] will be String and not Arel::Nodes::SqlLiteral
-
array[i] = '' << part
-
end
-
i += 1 if array[i].count('(') == array[i].count(')')
-
end
-
array
-
end
-
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class OrderClauses < Arel::Visitors::ToSql
-
1
private
-
-
1
def visit_Arel_Nodes_SelectStatement o, a
-
o.orders.map { |x| visit x, a }
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class PostgreSQL < Arel::Visitors::ToSql
-
1
private
-
-
1
def visit_Arel_Nodes_Matches o, a
-
a = o.left if Arel::Attributes::Attribute === o.left
-
"#{visit o.left, a} ILIKE #{visit o.right, a}"
-
end
-
-
1
def visit_Arel_Nodes_DoesNotMatch o, a
-
a = o.left if Arel::Attributes::Attribute === o.left
-
"#{visit o.left, a} NOT ILIKE #{visit o.right, a}"
-
end
-
-
1
def visit_Arel_Nodes_DistinctOn o, a
-
"DISTINCT ON ( #{visit o.expr, a} )"
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class SQLite < Arel::Visitors::ToSql
-
1
private
-
-
# Locks are not supported in SQLite
-
1
def visit_Arel_Nodes_Lock o, a
-
end
-
-
1
def visit_Arel_Nodes_SelectStatement o, a
-
o.limit = Arel::Nodes::Limit.new(-1) if o.offset && !o.limit
-
super
-
end
-
end
-
end
-
end
-
1
require 'bigdecimal'
-
1
require 'date'
-
-
1
module Arel
-
1
module Visitors
-
1
class ToSql < Arel::Visitors::Visitor
-
##
-
# This is some roflscale crazy stuff. I'm roflscaling this because
-
# building SQL queries is a hotspot. I will explain the roflscale so that
-
# others will not rm this code.
-
#
-
# In YARV, string literals in a method body will get duped when the byte
-
# code is executed. Let's take a look:
-
#
-
# > puts RubyVM::InstructionSequence.new('def foo; "bar"; end').disasm
-
#
-
# == disasm: <RubyVM::InstructionSequence:foo@<compiled>>=====
-
# 0000 trace 8
-
# 0002 trace 1
-
# 0004 putstring "bar"
-
# 0006 trace 16
-
# 0008 leave
-
#
-
# The `putstring` bytecode will dup the string and push it on the stack.
-
# In many cases in our SQL visitor, that string is never mutated, so there
-
# is no need to dup the literal.
-
#
-
# If we change to a constant lookup, the string will not be duped, and we
-
# can reduce the objects in our system:
-
#
-
# > puts RubyVM::InstructionSequence.new('BAR = "bar"; def foo; BAR; end').disasm
-
#
-
# == disasm: <RubyVM::InstructionSequence:foo@<compiled>>========
-
# 0000 trace 8
-
# 0002 trace 1
-
# 0004 getinlinecache 11, <ic:0>
-
# 0007 getconstant :BAR
-
# 0009 setinlinecache <ic:0>
-
# 0011 trace 16
-
# 0013 leave
-
#
-
# `getconstant` should be a hash lookup, and no object is duped when the
-
# value of the constant is pushed on the stack. Hence the crazy
-
# constants below.
-
#
-
# `matches` and `doesNotMatch` operate case-insensitively via Visitor subclasses
-
# specialized for specific databases when necessary.
-
#
-
-
1
WHERE = ' WHERE ' # :nodoc:
-
1
SPACE = ' ' # :nodoc:
-
1
COMMA = ', ' # :nodoc:
-
1
GROUP_BY = ' GROUP BY ' # :nodoc:
-
1
ORDER_BY = ' ORDER BY ' # :nodoc:
-
1
WINDOW = ' WINDOW ' # :nodoc:
-
1
AND = ' AND ' # :nodoc:
-
-
1
DISTINCT = 'DISTINCT' # :nodoc:
-
-
1
def initialize connection
-
1
@connection = connection
-
1
@schema_cache = connection.schema_cache
-
1
@quoted_tables = {}
-
1
@quoted_columns = {}
-
end
-
-
1
private
-
-
1
def visit_Arel_Nodes_DeleteStatement o, a
-
[
-
"DELETE FROM #{visit o.relation}",
-
("WHERE #{o.wheres.map { |x| visit x }.join AND}" unless o.wheres.empty?)
-
].compact.join ' '
-
end
-
-
# FIXME: we should probably have a 2-pass visitor for this
-
1
def build_subselect key, o
-
stmt = Nodes::SelectStatement.new
-
core = stmt.cores.first
-
core.froms = o.relation
-
core.wheres = o.wheres
-
core.projections = [key]
-
stmt.limit = o.limit
-
stmt.orders = o.orders
-
stmt
-
end
-
-
1
def visit_Arel_Nodes_UpdateStatement o, a
-
if o.orders.empty? && o.limit.nil?
-
wheres = o.wheres
-
else
-
wheres = [Nodes::In.new(o.key, [build_subselect(o.key, o)])]
-
end
-
-
[
-
"UPDATE #{visit o.relation, a}",
-
("SET #{o.values.map { |value| visit value, a }.join ', '}" unless o.values.empty?),
-
("WHERE #{wheres.map { |x| visit x, a }.join ' AND '}" unless wheres.empty?),
-
].compact.join ' '
-
end
-
-
1
def visit_Arel_Nodes_InsertStatement o, a
-
[
-
"INSERT INTO #{visit o.relation, a}",
-
-
("(#{o.columns.map { |x|
-
quote_column_name x.name
-
}.join ', '})" unless o.columns.empty?),
-
-
(visit o.values, a if o.values),
-
].compact.join ' '
-
end
-
-
1
def visit_Arel_Nodes_Exists o, a
-
"EXISTS (#{visit o.expressions, a})#{
-
o.alias ? " AS #{visit o.alias, a}" : ''}"
-
end
-
-
1
def visit_Arel_Nodes_True o, a
-
"TRUE"
-
end
-
-
1
def visit_Arel_Nodes_False o, a
-
"FALSE"
-
end
-
-
1
def table_exists? name
-
@schema_cache.table_exists? name
-
end
-
-
1
def column_for attr
-
return unless attr
-
name = attr.name.to_s
-
table = attr.relation.table_name
-
-
return nil unless table_exists? table
-
-
column_cache(table)[name]
-
end
-
-
1
def column_cache(table)
-
@schema_cache.columns_hash(table)
-
end
-
-
1
def visit_Arel_Nodes_Values o, a
-
"VALUES (#{o.expressions.zip(o.columns).map { |value, attr|
-
if Nodes::SqlLiteral === value
-
visit value, a
-
else
-
quote(value, attr && column_for(attr))
-
end
-
}.join ', '})"
-
end
-
-
1
def visit_Arel_Nodes_SelectStatement o, a
-
str = ''
-
-
if o.with
-
str << visit(o.with, a)
-
str << SPACE
-
end
-
-
o.cores.each { |x| str << visit_Arel_Nodes_SelectCore(x, a) }
-
-
unless o.orders.empty?
-
str << SPACE
-
str << ORDER_BY
-
len = o.orders.length - 1
-
o.orders.each_with_index { |x, i|
-
str << visit(x, a)
-
str << COMMA unless len == i
-
}
-
end
-
-
str << " #{visit(o.limit, a)}" if o.limit
-
str << " #{visit(o.offset, a)}" if o.offset
-
str << " #{visit(o.lock, a)}" if o.lock
-
-
str.strip!
-
str
-
end
-
-
1
def visit_Arel_Nodes_SelectCore o, a
-
str = "SELECT"
-
-
str << " #{visit(o.top, a)}" if o.top
-
str << " #{visit(o.set_quantifier, a)}" if o.set_quantifier
-
-
unless o.projections.empty?
-
str << SPACE
-
len = o.projections.length - 1
-
o.projections.each_with_index do |x, i|
-
str << visit(x, a)
-
str << COMMA unless len == i
-
end
-
end
-
-
str << " FROM #{visit(o.source, a)}" if o.source && !o.source.empty?
-
-
unless o.wheres.empty?
-
str << WHERE
-
len = o.wheres.length - 1
-
o.wheres.each_with_index do |x, i|
-
str << visit(x, a)
-
str << AND unless len == i
-
end
-
end
-
-
unless o.groups.empty?
-
str << GROUP_BY
-
len = o.groups.length - 1
-
o.groups.each_with_index do |x, i|
-
str << visit(x, a)
-
str << COMMA unless len == i
-
end
-
end
-
-
str << " #{visit(o.having, a)}" if o.having
-
-
unless o.windows.empty?
-
str << WINDOW
-
len = o.windows.length - 1
-
o.windows.each_with_index do |x, i|
-
str << visit(x, a)
-
str << COMMA unless len == i
-
end
-
end
-
-
str
-
end
-
-
1
def visit_Arel_Nodes_Bin o, a
-
visit o.expr, a
-
end
-
-
1
def visit_Arel_Nodes_Distinct o, a
-
DISTINCT
-
end
-
-
1
def visit_Arel_Nodes_DistinctOn o, a
-
raise NotImplementedError, 'DISTINCT ON not implemented for this db'
-
end
-
-
1
def visit_Arel_Nodes_With o, a
-
"WITH #{o.children.map { |x| visit x, a }.join(', ')}"
-
end
-
-
1
def visit_Arel_Nodes_WithRecursive o, a
-
"WITH RECURSIVE #{o.children.map { |x| visit x, a }.join(', ')}"
-
end
-
-
1
def visit_Arel_Nodes_Union o, a
-
"( #{visit o.left, a} UNION #{visit o.right, a} )"
-
end
-
-
1
def visit_Arel_Nodes_UnionAll o, a
-
"( #{visit o.left, a} UNION ALL #{visit o.right, a} )"
-
end
-
-
1
def visit_Arel_Nodes_Intersect o, a
-
"( #{visit o.left, a} INTERSECT #{visit o.right, a} )"
-
end
-
-
1
def visit_Arel_Nodes_Except o, a
-
"( #{visit o.left, a} EXCEPT #{visit o.right, a} )"
-
end
-
-
1
def visit_Arel_Nodes_NamedWindow o, a
-
"#{quote_column_name o.name} AS #{visit_Arel_Nodes_Window o, a}"
-
end
-
-
1
def visit_Arel_Nodes_Window o, a
-
s = [
-
("ORDER BY #{o.orders.map { |x| visit(x, a) }.join(', ')}" unless o.orders.empty?),
-
(visit o.framing, a if o.framing)
-
].compact.join ' '
-
"(#{s})"
-
end
-
-
1
def visit_Arel_Nodes_Rows o, a
-
if o.expr
-
"ROWS #{visit o.expr, a}"
-
else
-
"ROWS"
-
end
-
end
-
-
1
def visit_Arel_Nodes_Range o, a
-
if o.expr
-
"RANGE #{visit o.expr, a}"
-
else
-
"RANGE"
-
end
-
end
-
-
1
def visit_Arel_Nodes_Preceding o, a
-
"#{o.expr ? visit(o.expr, a) : 'UNBOUNDED'} PRECEDING"
-
end
-
-
1
def visit_Arel_Nodes_Following o, a
-
"#{o.expr ? visit(o.expr, a) : 'UNBOUNDED'} FOLLOWING"
-
end
-
-
1
def visit_Arel_Nodes_CurrentRow o, a
-
"CURRENT ROW"
-
end
-
-
1
def visit_Arel_Nodes_Over o, a
-
case o.right
-
when nil
-
"#{visit o.left, a} OVER ()"
-
when Arel::Nodes::SqlLiteral
-
"#{visit o.left, a} OVER #{visit o.right, a}"
-
when String, Symbol
-
"#{visit o.left, a} OVER #{quote_column_name o.right.to_s}"
-
else
-
"#{visit o.left, a} OVER #{visit o.right, a}"
-
end
-
end
-
-
1
def visit_Arel_Nodes_Having o, a
-
"HAVING #{visit o.expr, a}"
-
end
-
-
1
def visit_Arel_Nodes_Offset o, a
-
"OFFSET #{visit o.expr, a}"
-
end
-
-
1
def visit_Arel_Nodes_Limit o, a
-
"LIMIT #{visit o.expr, a}"
-
end
-
-
# FIXME: this does nothing on most databases, but does on MSSQL
-
1
def visit_Arel_Nodes_Top o, a
-
""
-
end
-
-
1
def visit_Arel_Nodes_Lock o, a
-
visit o.expr, a
-
end
-
-
1
def visit_Arel_Nodes_Grouping o, a
-
"(#{visit o.expr, a})"
-
end
-
-
1
def visit_Arel_SelectManager o, a
-
"(#{o.to_sql.rstrip})"
-
end
-
-
1
def visit_Arel_Nodes_Ascending o, a
-
"#{visit o.expr, a} ASC"
-
end
-
-
1
def visit_Arel_Nodes_Descending o, a
-
"#{visit o.expr, a} DESC"
-
end
-
-
1
def visit_Arel_Nodes_Group o, a
-
visit o.expr, a
-
end
-
-
1
def visit_Arel_Nodes_NamedFunction o, a
-
"#{o.name}(#{o.distinct ? 'DISTINCT ' : ''}#{o.expressions.map { |x|
-
visit x, a
-
}.join(', ')})#{o.alias ? " AS #{visit o.alias, a}" : ''}"
-
end
-
-
1
def visit_Arel_Nodes_Extract o, a
-
"EXTRACT(#{o.field.to_s.upcase} FROM #{visit o.expr, a})#{o.alias ? " AS #{visit o.alias, a}" : ''}"
-
end
-
-
1
def visit_Arel_Nodes_Count o, a
-
"COUNT(#{o.distinct ? 'DISTINCT ' : ''}#{o.expressions.map { |x|
-
visit x, a
-
}.join(', ')})#{o.alias ? " AS #{visit o.alias, a}" : ''}"
-
end
-
-
1
def visit_Arel_Nodes_Sum o, a
-
"SUM(#{o.distinct ? 'DISTINCT ' : ''}#{o.expressions.map { |x|
-
visit x, a }.join(', ')})#{o.alias ? " AS #{visit o.alias, a}" : ''}"
-
end
-
-
1
def visit_Arel_Nodes_Max o, a
-
"MAX(#{o.distinct ? 'DISTINCT ' : ''}#{o.expressions.map { |x|
-
visit x, a }.join(', ')})#{o.alias ? " AS #{visit o.alias, a}" : ''}"
-
end
-
-
1
def visit_Arel_Nodes_Min o, a
-
"MIN(#{o.distinct ? 'DISTINCT ' : ''}#{o.expressions.map { |x|
-
visit x, a }.join(', ')})#{o.alias ? " AS #{visit o.alias, a}" : ''}"
-
end
-
-
1
def visit_Arel_Nodes_Avg o, a
-
"AVG(#{o.distinct ? 'DISTINCT ' : ''}#{o.expressions.map { |x|
-
visit x, a }.join(', ')})#{o.alias ? " AS #{visit o.alias, a}" : ''}"
-
end
-
-
1
def visit_Arel_Nodes_TableAlias o, a
-
"#{visit o.relation, a} #{quote_table_name o.name}"
-
end
-
-
1
def visit_Arel_Nodes_Between o, a
-
a = o.left if Arel::Attributes::Attribute === o.left
-
"#{visit o.left, a} BETWEEN #{visit o.right, a}"
-
end
-
-
1
def visit_Arel_Nodes_GreaterThanOrEqual o, a
-
a = o.left if Arel::Attributes::Attribute === o.left
-
"#{visit o.left, a} >= #{visit o.right, a}"
-
end
-
-
1
def visit_Arel_Nodes_GreaterThan o, a
-
a = o.left if Arel::Attributes::Attribute === o.left
-
"#{visit o.left, a} > #{visit o.right, a}"
-
end
-
-
1
def visit_Arel_Nodes_LessThanOrEqual o, a
-
a = o.left if Arel::Attributes::Attribute === o.left
-
"#{visit o.left, a} <= #{visit o.right, a}"
-
end
-
-
1
def visit_Arel_Nodes_LessThan o, a
-
a = o.left if Arel::Attributes::Attribute === o.left
-
"#{visit o.left, a} < #{visit o.right, a}"
-
end
-
-
1
def visit_Arel_Nodes_Matches o, a
-
a = o.left if Arel::Attributes::Attribute === o.left
-
"#{visit o.left, a} LIKE #{visit o.right, a}"
-
end
-
-
1
def visit_Arel_Nodes_DoesNotMatch o, a
-
a = o.left if Arel::Attributes::Attribute === o.left
-
"#{visit o.left, a} NOT LIKE #{visit o.right, a}"
-
end
-
-
1
def visit_Arel_Nodes_JoinSource o, a
-
[
-
(visit(o.left, a) if o.left),
-
o.right.map { |j| visit j, a }.join(' ')
-
].compact.join ' '
-
end
-
-
1
def visit_Arel_Nodes_StringJoin o, a
-
visit o.left, a
-
end
-
-
1
def visit_Arel_Nodes_OuterJoin o, a
-
"LEFT OUTER JOIN #{visit o.left, a} #{visit o.right, a}"
-
end
-
-
1
def visit_Arel_Nodes_InnerJoin o, a
-
s = "INNER JOIN #{visit o.left, a}"
-
if o.right
-
s << SPACE
-
s << visit(o.right, a)
-
end
-
s
-
end
-
-
1
def visit_Arel_Nodes_On o, a
-
"ON #{visit o.expr, a}"
-
end
-
-
1
def visit_Arel_Nodes_Not o, a
-
"NOT (#{visit o.expr, a})"
-
end
-
-
1
def visit_Arel_Table o, a
-
if o.table_alias
-
"#{quote_table_name o.name} #{quote_table_name o.table_alias}"
-
else
-
quote_table_name o.name
-
end
-
end
-
-
1
def visit_Arel_Nodes_In o, a
-
if Array === o.right && o.right.empty?
-
'1=0'
-
else
-
a = o.left if Arel::Attributes::Attribute === o.left
-
"#{visit o.left, a} IN (#{visit o.right, a})"
-
end
-
end
-
-
1
def visit_Arel_Nodes_NotIn o, a
-
if Array === o.right && o.right.empty?
-
'1=1'
-
else
-
a = o.left if Arel::Attributes::Attribute === o.left
-
"#{visit o.left, a} NOT IN (#{visit o.right, a})"
-
end
-
end
-
-
1
def visit_Arel_Nodes_And o, a
-
o.children.map { |x| visit x, a }.join ' AND '
-
end
-
-
1
def visit_Arel_Nodes_Or o, a
-
"#{visit o.left, a} OR #{visit o.right, a}"
-
end
-
-
1
def visit_Arel_Nodes_Assignment o, a
-
right = quote(o.right, column_for(o.left))
-
"#{visit o.left, a} = #{right}"
-
end
-
-
1
def visit_Arel_Nodes_Equality o, a
-
right = o.right
-
-
a = o.left if Arel::Attributes::Attribute === o.left
-
if right.nil?
-
"#{visit o.left, a} IS NULL"
-
else
-
"#{visit o.left, a} = #{visit right, a}"
-
end
-
end
-
-
1
def visit_Arel_Nodes_NotEqual o, a
-
right = o.right
-
-
a = o.left if Arel::Attributes::Attribute === o.left
-
if right.nil?
-
"#{visit o.left, a} IS NOT NULL"
-
else
-
"#{visit o.left, a} != #{visit right, a}"
-
end
-
end
-
-
1
def visit_Arel_Nodes_As o, a
-
"#{visit o.left, a} AS #{visit o.right, a}"
-
end
-
-
1
def visit_Arel_Nodes_UnqualifiedColumn o, a
-
"#{quote_column_name o.name}"
-
end
-
-
1
def visit_Arel_Attributes_Attribute o, a
-
join_name = o.relation.table_alias || o.relation.name
-
"#{quote_table_name join_name}.#{quote_column_name o.name}"
-
end
-
1
alias :visit_Arel_Attributes_Integer :visit_Arel_Attributes_Attribute
-
1
alias :visit_Arel_Attributes_Float :visit_Arel_Attributes_Attribute
-
1
alias :visit_Arel_Attributes_Decimal :visit_Arel_Attributes_Attribute
-
1
alias :visit_Arel_Attributes_String :visit_Arel_Attributes_Attribute
-
1
alias :visit_Arel_Attributes_Time :visit_Arel_Attributes_Attribute
-
1
alias :visit_Arel_Attributes_Boolean :visit_Arel_Attributes_Attribute
-
-
1
def literal o, a; o end
-
-
1
alias :visit_Arel_Nodes_BindParam :literal
-
1
alias :visit_Arel_Nodes_SqlLiteral :literal
-
1
alias :visit_Arel_SqlLiteral :literal # This is deprecated
-
1
alias :visit_Bignum :literal
-
1
alias :visit_Fixnum :literal
-
-
1
def quoted o, a
-
quote(o, column_for(a))
-
end
-
-
1
alias :visit_ActiveSupport_Multibyte_Chars :quoted
-
1
alias :visit_ActiveSupport_StringInquirer :quoted
-
1
alias :visit_BigDecimal :quoted
-
1
alias :visit_Class :quoted
-
1
alias :visit_Date :quoted
-
1
alias :visit_DateTime :quoted
-
1
alias :visit_FalseClass :quoted
-
1
alias :visit_Float :quoted
-
1
alias :visit_Hash :quoted
-
1
alias :visit_NilClass :quoted
-
1
alias :visit_String :quoted
-
1
alias :visit_Symbol :quoted
-
1
alias :visit_Time :quoted
-
1
alias :visit_TrueClass :quoted
-
-
1
def visit_Arel_Nodes_InfixOperation o, a
-
"#{visit o.left, a} #{o.operator} #{visit o.right, a}"
-
end
-
-
1
alias :visit_Arel_Nodes_Addition :visit_Arel_Nodes_InfixOperation
-
1
alias :visit_Arel_Nodes_Subtraction :visit_Arel_Nodes_InfixOperation
-
1
alias :visit_Arel_Nodes_Multiplication :visit_Arel_Nodes_InfixOperation
-
1
alias :visit_Arel_Nodes_Division :visit_Arel_Nodes_InfixOperation
-
-
1
def visit_Array o, a
-
o.map { |x| visit x, a }.join(', ')
-
end
-
-
1
def quote value, column = nil
-
return value if Arel::Nodes::SqlLiteral === value
-
@connection.quote value, column
-
end
-
-
1
def quote_table_name name
-
return name if Arel::Nodes::SqlLiteral === name
-
@quoted_tables[name] ||= @connection.quote_table_name(name)
-
end
-
-
1
def quote_column_name name
-
@quoted_columns[name] ||= Arel::Nodes::SqlLiteral === name ? name : @connection.quote_column_name(name)
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class Visitor
-
1
def accept object
-
visit object
-
end
-
-
1
private
-
-
1
DISPATCH = Hash.new do |hash, visitor_class|
-
hash[visitor_class] =
-
Hash.new do |method_hash, node_class|
-
method_hash[node_class] = "visit_#{(node_class.name || '').gsub('::', '_')}"
-
end
-
end
-
-
1
def dispatch
-
DISPATCH[self.class]
-
end
-
-
1
def visit object, attribute = nil
-
send dispatch[object.class], object, attribute
-
rescue NoMethodError => e
-
raise e if respond_to?(dispatch[object.class], true)
-
superklass = object.class.ancestors.find { |klass|
-
respond_to?(dispatch[klass], true)
-
}
-
raise(TypeError, "Cannot visit #{object.class}") unless superklass
-
dispatch[object.class] = dispatch[superklass]
-
retry
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class WhereSql < Arel::Visitors::ToSql
-
1
def visit_Arel_Nodes_SelectCore o, a
-
"WHERE #{o.wheres.map { |x| visit x, a }.join ' AND ' }"
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module WindowPredications
-
-
1
def over(expr = nil)
-
Nodes::Over.new(self, expr)
-
end
-
-
end
-
end
-
# A Ruby library implementing OpenBSD's bcrypt()/crypt_blowfish algorithm for
-
# hashing passwords.
-
1
module BCrypt
-
end
-
-
1
if RUBY_PLATFORM == "java"
-
require 'java'
-
else
-
1
require "openssl"
-
end
-
-
1
begin
-
1
RUBY_VERSION =~ /(\d+.\d+)/
-
1
require "#{$1}/bcrypt_ext"
-
rescue LoadError
-
1
require "bcrypt_ext"
-
end
-
-
1
require 'bcrypt/error'
-
1
require 'bcrypt/engine'
-
1
require 'bcrypt/password'
-
1
module BCrypt
-
# A Ruby wrapper for the bcrypt() C extension calls and the Java calls.
-
1
class Engine
-
# The default computational expense parameter.
-
1
DEFAULT_COST = 10
-
# The minimum cost supported by the algorithm.
-
1
MIN_COST = 4
-
# Maximum possible size of bcrypt() salts.
-
1
MAX_SALT_LENGTH = 16
-
-
1
if RUBY_PLATFORM != "java"
-
# C-level routines which, if they don't get the right input, will crash the
-
# hell out of the Ruby process.
-
1
private_class_method :__bc_salt
-
1
private_class_method :__bc_crypt
-
end
-
-
1
@cost = nil
-
-
# Returns the cost factor that will be used if one is not specified when
-
# creating a password hash. Defaults to DEFAULT_COST if not set.
-
1
def self.cost
-
@cost || DEFAULT_COST
-
end
-
-
# Set a default cost factor that will be used if one is not specified when
-
# creating a password hash.
-
#
-
# Example:
-
#
-
# BCrypt::Engine::DEFAULT_COST #=> 10
-
# BCrypt::Password.create('secret').cost #=> 10
-
#
-
# BCrypt::Engine.cost = 8
-
# BCrypt::Password.create('secret').cost #=> 8
-
#
-
# # cost can still be overridden as needed
-
# BCrypt::Password.create('secret', :cost => 6).cost #=> 6
-
1
def self.cost=(cost)
-
@cost = cost
-
end
-
-
# Given a secret and a valid salt (see BCrypt::Engine.generate_salt) calculates
-
# a bcrypt() password hash.
-
1
def self.hash_secret(secret, salt, _ = nil)
-
if valid_secret?(secret)
-
if valid_salt?(salt)
-
if RUBY_PLATFORM == "java"
-
Java.bcrypt_jruby.BCrypt.hashpw(secret.to_s, salt.to_s)
-
else
-
__bc_crypt(secret.to_s, salt)
-
end
-
else
-
raise Errors::InvalidSalt.new("invalid salt")
-
end
-
else
-
raise Errors::InvalidSecret.new("invalid secret")
-
end
-
end
-
-
# Generates a random salt with a given computational cost.
-
1
def self.generate_salt(cost = self.cost)
-
cost = cost.to_i
-
if cost > 0
-
if cost < MIN_COST
-
cost = MIN_COST
-
end
-
if RUBY_PLATFORM == "java"
-
Java.bcrypt_jruby.BCrypt.gensalt(cost)
-
else
-
prefix = "$2a$05$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW"
-
__bc_salt(prefix, cost, OpenSSL::Random.random_bytes(MAX_SALT_LENGTH))
-
end
-
else
-
raise Errors::InvalidCost.new("cost must be numeric and > 0")
-
end
-
end
-
-
# Returns true if +salt+ is a valid bcrypt() salt, false if not.
-
1
def self.valid_salt?(salt)
-
!!(salt =~ /^\$[0-9a-z]{2,}\$[0-9]{2,}\$[A-Za-z0-9\.\/]{22,}$/)
-
end
-
-
# Returns true if +secret+ is a valid bcrypt() secret, false if not.
-
1
def self.valid_secret?(secret)
-
secret.respond_to?(:to_s)
-
end
-
-
# Returns the cost factor which will result in computation times less than +upper_time_limit_in_ms+.
-
#
-
# Example:
-
#
-
# BCrypt::Engine.calibrate(200) #=> 10
-
# BCrypt::Engine.calibrate(1000) #=> 12
-
#
-
# # should take less than 200ms
-
# BCrypt::Password.create("woo", :cost => 10)
-
#
-
# # should take less than 1000ms
-
# BCrypt::Password.create("woo", :cost => 12)
-
1
def self.calibrate(upper_time_limit_in_ms)
-
40.times do |i|
-
start_time = Time.now
-
Password.create("testing testing", :cost => i+1)
-
end_time = Time.now - start_time
-
return i if end_time * 1_000 > upper_time_limit_in_ms
-
end
-
end
-
-
# Autodetects the cost from the salt string.
-
1
def self.autodetect_cost(salt)
-
salt[4..5].to_i
-
end
-
end
-
-
end
-
1
module BCrypt
-
-
1
class Error < StandardError # :nodoc:
-
end
-
-
1
module Errors # :nodoc:
-
-
# The salt parameter provided to bcrypt() is invalid.
-
1
class InvalidSalt < BCrypt::Error; end
-
-
# The hash parameter provided to bcrypt() is invalid.
-
1
class InvalidHash < BCrypt::Error; end
-
-
# The cost parameter provided to bcrypt() is invalid.
-
1
class InvalidCost < BCrypt::Error; end
-
-
# The secret parameter provided to bcrypt() is invalid.
-
1
class InvalidSecret < BCrypt::Error; end
-
-
end
-
-
end
-
1
module BCrypt
-
# A password management class which allows you to safely store users' passwords and compare them.
-
#
-
# Example usage:
-
#
-
# include BCrypt
-
#
-
# # hash a user's password
-
# @password = Password.create("my grand secret")
-
# @password #=> "$2a$10$GtKs1Kbsig8ULHZzO1h2TetZfhO4Fmlxphp8bVKnUlZCBYYClPohG"
-
#
-
# # store it safely
-
# @user.update_attribute(:password, @password)
-
#
-
# # read it back
-
# @user.reload!
-
# @db_password = Password.new(@user.password)
-
#
-
# # compare it after retrieval
-
# @db_password == "my grand secret" #=> true
-
# @db_password == "a paltry guess" #=> false
-
#
-
1
class Password < String
-
# The hash portion of the stored password hash.
-
1
attr_reader :checksum
-
# The salt of the store password hash (including version and cost).
-
1
attr_reader :salt
-
# The version of the bcrypt() algorithm used to create the hash.
-
1
attr_reader :version
-
# The cost factor used to create the hash.
-
1
attr_reader :cost
-
-
1
class << self
-
# Hashes a secret, returning a BCrypt::Password instance. Takes an optional <tt>:cost</tt> option, which is a
-
# logarithmic variable which determines how computational expensive the hash is to calculate (a <tt>:cost</tt> of
-
# 4 is twice as much work as a <tt>:cost</tt> of 3). The higher the <tt>:cost</tt> the harder it becomes for
-
# attackers to try to guess passwords (even if a copy of your database is stolen), but the slower it is to check
-
# users' passwords.
-
#
-
# Example:
-
#
-
# @password = BCrypt::Password.create("my secret", :cost => 13)
-
1
def create(secret, options = {})
-
cost = options[:cost] || BCrypt::Engine.cost
-
raise ArgumentError if cost > 31
-
Password.new(BCrypt::Engine.hash_secret(secret, BCrypt::Engine.generate_salt(cost)))
-
end
-
-
1
def valid_hash?(h)
-
h =~ /^\$[0-9a-z]{2}\$[0-9]{2}\$[A-Za-z0-9\.\/]{53}$/
-
end
-
end
-
-
# Initializes a BCrypt::Password instance with the data from a stored hash.
-
1
def initialize(raw_hash)
-
if valid_hash?(raw_hash)
-
self.replace(raw_hash)
-
@version, @cost, @salt, @checksum = split_hash(self)
-
else
-
raise Errors::InvalidHash.new("invalid hash")
-
end
-
end
-
-
# Compares a potential secret against the hash. Returns true if the secret is the original secret, false otherwise.
-
1
def ==(secret)
-
super(BCrypt::Engine.hash_secret(secret, @salt))
-
end
-
1
alias_method :is_password?, :==
-
-
1
private
-
-
# Returns true if +h+ is a valid hash.
-
1
def valid_hash?(h)
-
self.class.valid_hash?(h)
-
end
-
-
# call-seq:
-
# split_hash(raw_hash) -> version, cost, salt, hash
-
#
-
# Splits +h+ into version, cost, salt, and hash and returns them in that order.
-
1
def split_hash(h)
-
_, v, c, mash = h.split('$')
-
return v, c.to_i, h[0, 29].to_str, mash[-31, 31].to_str
-
end
-
end
-
-
end
-
1
require "bootstrap-on-rails/version"
-
1
require "less-rails"
-
-
1
module BootstrapOnRails
-
1
require "bootstrap-on-rails/engine"
-
1
require "bootstrap-on-rails/version"
-
end
-
1
module BootstrapOnRails
-
1
class Engine < Rails::Engine
-
end
-
end
-
1
module BootstrapOnRails
-
1
VERSION = "3.2.0"
-
end
-
1
require 'bootstrap3-datetimepicker-rails/version'
-
-
1
module Bootstrap3Datetimepicker
-
1
module Rails
-
1
class Engine < ::Rails::Engine
-
end
-
end
-
end
-
1
module Bootstrap3Datetimepicker
-
1
module Rails
-
1
VERSION = '3.1.3'
-
end
-
end
-
1
require 'cancan/ability'
-
1
require 'cancan/rule'
-
1
require 'cancan/controller_resource'
-
1
require 'cancan/controller_additions'
-
1
require 'cancan/model_additions'
-
1
require 'cancan/exceptions'
-
1
require 'cancan/inherited_resource'
-
-
1
require 'cancan/model_adapters/abstract_adapter'
-
1
require 'cancan/model_adapters/default_adapter'
-
1
require 'cancan/model_adapters/active_record_adapter' if defined? ActiveRecord
-
1
require 'cancan/model_adapters/data_mapper_adapter' if defined? DataMapper
-
1
require 'cancan/model_adapters/mongoid_adapter' if defined?(Mongoid) && defined?(Mongoid::Document)
-
1
module CanCan
-
-
# This module is designed to be included into an Ability class. This will
-
# provide the "can" methods for defining and checking abilities.
-
#
-
# class Ability
-
# include CanCan::Ability
-
#
-
# def initialize(user)
-
# if user.admin?
-
# can :manage, :all
-
# else
-
# can :read, :all
-
# end
-
# end
-
# end
-
#
-
1
module Ability
-
# Check if the user has permission to perform a given action on an object.
-
#
-
# can? :destroy, @project
-
#
-
# You can also pass the class instead of an instance (if you don't have one handy).
-
#
-
# can? :create, Project
-
#
-
# Nested resources can be passed through a hash, this way conditions which are
-
# dependent upon the association will work when using a class.
-
#
-
# can? :create, @category => Project
-
#
-
# Any additional arguments will be passed into the "can" block definition. This
-
# can be used to pass more information about the user's request for example.
-
#
-
# can? :create, Project, request.remote_ip
-
#
-
# can :create Project do |project, remote_ip|
-
# # ...
-
# end
-
#
-
# Not only can you use the can? method in the controller and view (see ControllerAdditions),
-
# but you can also call it directly on an ability instance.
-
#
-
# ability.can? :destroy, @project
-
#
-
# This makes testing a user's abilities very easy.
-
#
-
# def test "user can only destroy projects which he owns"
-
# user = User.new
-
# ability = Ability.new(user)
-
# assert ability.can?(:destroy, Project.new(:user => user))
-
# assert ability.cannot?(:destroy, Project.new)
-
# end
-
#
-
# Also see the RSpec Matchers to aid in testing.
-
1
def can?(action, subject, *extra_args)
-
match = relevant_rules_for_match(action, subject).detect do |rule|
-
rule.matches_conditions?(action, subject, extra_args)
-
end
-
match ? match.base_behavior : false
-
end
-
-
# Convenience method which works the same as "can?" but returns the opposite value.
-
#
-
# cannot? :destroy, @project
-
#
-
1
def cannot?(*args)
-
!can?(*args)
-
end
-
-
# Defines which abilities are allowed using two arguments. The first one is the action
-
# you're setting the permission for, the second one is the class of object you're setting it on.
-
#
-
# can :update, Article
-
#
-
# You can pass an array for either of these parameters to match any one.
-
# Here the user has the ability to update or destroy both articles and comments.
-
#
-
# can [:update, :destroy], [Article, Comment]
-
#
-
# You can pass :all to match any object and :manage to match any action. Here are some examples.
-
#
-
# can :manage, :all
-
# can :update, :all
-
# can :manage, Project
-
#
-
# You can pass a hash of conditions as the third argument. Here the user can only see active projects which he owns.
-
#
-
# can :read, Project, :active => true, :user_id => user.id
-
#
-
# See ActiveRecordAdditions#accessible_by for how to use this in database queries. These conditions
-
# are also used for initial attributes when building a record in ControllerAdditions#load_resource.
-
#
-
# If the conditions hash does not give you enough control over defining abilities, you can use a block
-
# along with any Ruby code you want.
-
#
-
# can :update, Project do |project|
-
# project.groups.include?(user.group)
-
# end
-
#
-
# If the block returns true then the user has that :update ability for that project, otherwise he
-
# will be denied access. The downside to using a block is that it cannot be used to generate
-
# conditions for database queries.
-
#
-
# You can pass custom objects into this "can" method, this is usually done with a symbol
-
# and is useful if a class isn't available to define permissions on.
-
#
-
# can :read, :stats
-
# can? :read, :stats # => true
-
#
-
# IMPORTANT: Neither a hash of conditions or a block will be used when checking permission on a class.
-
#
-
# can :update, Project, :priority => 3
-
# can? :update, Project # => true
-
#
-
# If you pass no arguments to +can+, the action, class, and object will be passed to the block and the
-
# block will always be executed. This allows you to override the full behavior if the permissions are
-
# defined in an external source such as the database.
-
#
-
# can do |action, object_class, object|
-
# # check the database and return true/false
-
# end
-
#
-
1
def can(action = nil, subject = nil, conditions = nil, &block)
-
rules << Rule.new(true, action, subject, conditions, block)
-
end
-
-
# Defines an ability which cannot be done. Accepts the same arguments as "can".
-
#
-
# can :read, :all
-
# cannot :read, Comment
-
#
-
# A block can be passed just like "can", however if the logic is complex it is recommended
-
# to use the "can" method.
-
#
-
# cannot :read, Product do |product|
-
# product.invisible?
-
# end
-
#
-
1
def cannot(action = nil, subject = nil, conditions = nil, &block)
-
rules << Rule.new(false, action, subject, conditions, block)
-
end
-
-
# Alias one or more actions into another one.
-
#
-
# alias_action :update, :destroy, :to => :modify
-
# can :modify, Comment
-
#
-
# Then :modify permission will apply to both :update and :destroy requests.
-
#
-
# can? :update, Comment # => true
-
# can? :destroy, Comment # => true
-
#
-
# This only works in one direction. Passing the aliased action into the "can?" call
-
# will not work because aliases are meant to generate more generic actions.
-
#
-
# alias_action :update, :destroy, :to => :modify
-
# can :update, Comment
-
# can? :modify, Comment # => false
-
#
-
# Unless that exact alias is used.
-
#
-
# can :modify, Comment
-
# can? :modify, Comment # => true
-
#
-
# The following aliases are added by default for conveniently mapping common controller actions.
-
#
-
# alias_action :index, :show, :to => :read
-
# alias_action :new, :to => :create
-
# alias_action :edit, :to => :update
-
#
-
# This way one can use params[:action] in the controller to determine the permission.
-
1
def alias_action(*args)
-
target = args.pop[:to]
-
validate_target(target)
-
aliased_actions[target] ||= []
-
aliased_actions[target] += args
-
end
-
-
# User shouldn't specify targets with names of real actions or it will cause Seg fault
-
1
def validate_target(target)
-
raise Error, "You can't specify target (#{target}) as alias because it is real action name" if aliased_actions.values.flatten.include? target
-
end
-
-
# Returns a hash of aliased actions. The key is the target and the value is an array of actions aliasing the key.
-
1
def aliased_actions
-
@aliased_actions ||= default_alias_actions
-
end
-
-
# Removes previously aliased actions including the defaults.
-
1
def clear_aliased_actions
-
@aliased_actions = {}
-
end
-
-
1
def model_adapter(model_class, action)
-
adapter_class = ModelAdapters::AbstractAdapter.adapter_class(model_class)
-
adapter_class.new(model_class, relevant_rules_for_query(action, model_class))
-
end
-
-
# See ControllerAdditions#authorize! for documentation.
-
1
def authorize!(action, subject, *args)
-
message = nil
-
if args.last.kind_of?(Hash) && args.last.has_key?(:message)
-
message = args.pop[:message]
-
end
-
if cannot?(action, subject, *args)
-
message ||= unauthorized_message(action, subject)
-
raise AccessDenied.new(message, action, subject)
-
end
-
subject
-
end
-
-
1
def unauthorized_message(action, subject)
-
keys = unauthorized_message_keys(action, subject)
-
variables = {:action => action.to_s}
-
variables[:subject] = (subject.class == Class ? subject : subject.class).to_s.underscore.humanize.downcase
-
message = I18n.translate(nil, variables.merge(:scope => :unauthorized, :default => keys + [""]))
-
message.blank? ? nil : message
-
end
-
-
1
def attributes_for(action, subject)
-
attributes = {}
-
relevant_rules(action, subject).map do |rule|
-
attributes.merge!(rule.attributes_from_conditions) if rule.base_behavior
-
end
-
attributes
-
end
-
-
1
def has_block?(action, subject)
-
relevant_rules(action, subject).any?(&:only_block?)
-
end
-
-
1
def has_raw_sql?(action, subject)
-
relevant_rules(action, subject).any?(&:only_raw_sql?)
-
end
-
-
1
def merge(ability)
-
ability.send(:rules).each do |rule|
-
rules << rule.dup
-
end
-
self
-
end
-
-
1
private
-
-
1
def unauthorized_message_keys(action, subject)
-
subject = (subject.class == Class ? subject : subject.class).name.underscore unless subject.kind_of? Symbol
-
[subject, :all].map do |try_subject|
-
[aliases_for_action(action), :manage].flatten.map do |try_action|
-
:"#{try_action}.#{try_subject}"
-
end
-
end.flatten
-
end
-
-
# Accepts an array of actions and returns an array of actions which match.
-
# This should be called before "matches?" and other checking methods since they
-
# rely on the actions to be expanded.
-
1
def expand_actions(actions)
-
actions.map do |action|
-
aliased_actions[action] ? [action, *expand_actions(aliased_actions[action])] : action
-
end.flatten
-
end
-
-
# Given an action, it will try to find all of the actions which are aliased to it.
-
# This does the opposite kind of lookup as expand_actions.
-
1
def aliases_for_action(action)
-
results = [action]
-
aliased_actions.each do |aliased_action, actions|
-
results += aliases_for_action(aliased_action) if actions.include? action
-
end
-
results
-
end
-
-
1
def rules
-
@rules ||= []
-
end
-
-
# Returns an array of Rule instances which match the action and subject
-
# This does not take into consideration any hash conditions or block statements
-
1
def relevant_rules(action, subject)
-
rules.reverse.select do |rule|
-
rule.expanded_actions = expand_actions(rule.actions)
-
rule.relevant? action, subject
-
end
-
end
-
-
1
def relevant_rules_for_match(action, subject)
-
relevant_rules(action, subject).each do |rule|
-
if rule.only_raw_sql?
-
raise Error, "The can? and cannot? call cannot be used with a raw sql 'can' definition. The checking code cannot be determined for #{action.inspect} #{subject.inspect}"
-
end
-
end
-
end
-
-
1
def relevant_rules_for_query(action, subject)
-
relevant_rules(action, subject).each do |rule|
-
if rule.only_block?
-
raise Error, "The accessible_by call cannot be used with a block 'can' definition. The SQL cannot be determined for #{action.inspect} #{subject.inspect}"
-
end
-
end
-
end
-
-
1
def default_alias_actions
-
{
-
:read => [:index, :show],
-
:create => [:new],
-
:update => [:edit],
-
}
-
end
-
end
-
end
-
1
module CanCan
-
-
# This module is automatically included into all controllers.
-
# It also makes the "can?" and "cannot?" methods available to all views.
-
1
module ControllerAdditions
-
1
module ClassMethods
-
# Sets up a before filter which loads and authorizes the current resource. This performs both
-
# load_resource and authorize_resource and accepts the same arguments. See those methods for details.
-
#
-
# class BooksController < ApplicationController
-
# load_and_authorize_resource
-
# end
-
#
-
1
def load_and_authorize_resource(*args)
-
cancan_resource_class.add_before_filter(self, :load_and_authorize_resource, *args)
-
end
-
-
# Sets up a before filter which loads the model resource into an instance variable.
-
# For example, given an ArticlesController it will load the current article into the @article
-
# instance variable. It does this by either calling Article.find(params[:id]) or
-
# Article.new(params[:article]) depending upon the action. The index action will
-
# automatically set @articles to Article.accessible_by(current_ability).
-
#
-
# If a conditions hash is used in the Ability, the +new+ and +create+ actions will set
-
# the initial attributes based on these conditions. This way these actions will satisfy
-
# the ability restrictions.
-
#
-
# Call this method directly on the controller class.
-
#
-
# class BooksController < ApplicationController
-
# load_resource
-
# end
-
#
-
# A resource is not loaded if the instance variable is already set. This makes it easy to override
-
# the behavior through a before_filter on certain actions.
-
#
-
# class BooksController < ApplicationController
-
# before_filter :find_book_by_permalink, :only => :show
-
# load_resource
-
#
-
# private
-
#
-
# def find_book_by_permalink
-
# @book = Book.find_by_permalink!(params[:id)
-
# end
-
# end
-
#
-
# If a name is provided which does not match the controller it assumes it is a parent resource. Child
-
# resources can then be loaded through it.
-
#
-
# class BooksController < ApplicationController
-
# load_resource :author
-
# load_resource :book, :through => :author
-
# end
-
#
-
# Here the author resource will be loaded before each action using params[:author_id]. The book resource
-
# will then be loaded through the @author instance variable.
-
#
-
# That first argument is optional and will default to the singular name of the controller.
-
# A hash of options (see below) can also be passed to this method to further customize it.
-
#
-
# See load_and_authorize_resource to automatically authorize the resource too.
-
#
-
# Options:
-
# [:+only+]
-
# Only applies before filter to given actions.
-
#
-
# [:+except+]
-
# Does not apply before filter to given actions.
-
#
-
# [:+through+]
-
# Load this resource through another one. This should match the name of the parent instance variable or method.
-
#
-
# [:+through_association+]
-
# The name of the association to fetch the child records through the parent resource. This is normally not needed
-
# because it defaults to the pluralized resource name.
-
#
-
# [:+shallow+]
-
# Pass +true+ to allow this resource to be loaded directly when parent is +nil+. Defaults to +false+.
-
#
-
# [:+singleton+]
-
# Pass +true+ if this is a singleton resource through a +has_one+ association.
-
#
-
# [:+parent+]
-
# True or false depending on if the resource is considered a parent resource. This defaults to +true+ if a resource
-
# name is given which does not match the controller.
-
#
-
# [:+class+]
-
# The class to use for the model (string or constant).
-
#
-
# [:+instance_name+]
-
# The name of the instance variable to load the resource into.
-
#
-
# [:+find_by+]
-
# Find using a different attribute other than id. For example.
-
#
-
# load_resource :find_by => :permalink # will use find_by_permalink!(params[:id])
-
#
-
# [:+id_param+]
-
# Find using a param key other than :id. For example:
-
#
-
# load_resource :id_key => :url # will use find(params[:url])
-
#
-
# [:+collection+]
-
# Specify which actions are resource collection actions in addition to :+index+. This
-
# is usually not necessary because it will try to guess depending on if the id param is present.
-
#
-
# load_resource :collection => [:sort, :list]
-
#
-
# [:+new+]
-
# Specify which actions are new resource actions in addition to :+new+ and :+create+.
-
# Pass an action name into here if you would like to build a new resource instead of
-
# fetch one.
-
#
-
# load_resource :new => :build
-
#
-
# [:+prepend+]
-
# Passing +true+ will use prepend_before_filter instead of a normal before_filter.
-
#
-
1
def load_resource(*args)
-
cancan_resource_class.add_before_filter(self, :load_resource, *args)
-
end
-
-
# Sets up a before filter which authorizes the resource using the instance variable.
-
# For example, if you have an ArticlesController it will check the @article instance variable
-
# and ensure the user can perform the current action on it. Under the hood it is doing
-
# something like the following.
-
#
-
# authorize!(params[:action].to_sym, @article || Article)
-
#
-
# Call this method directly on the controller class.
-
#
-
# class BooksController < ApplicationController
-
# authorize_resource
-
# end
-
#
-
# If you pass in the name of a resource which does not match the controller it will assume
-
# it is a parent resource.
-
#
-
# class BooksController < ApplicationController
-
# authorize_resource :author
-
# authorize_resource :book
-
# end
-
#
-
# Here it will authorize :+show+, @+author+ on every action before authorizing the book.
-
#
-
# That first argument is optional and will default to the singular name of the controller.
-
# A hash of options (see below) can also be passed to this method to further customize it.
-
#
-
# See load_and_authorize_resource to automatically load the resource too.
-
#
-
# Options:
-
# [:+only+]
-
# Only applies before filter to given actions.
-
#
-
# [:+except+]
-
# Does not apply before filter to given actions.
-
#
-
# [:+singleton+]
-
# Pass +true+ if this is a singleton resource through a +has_one+ association.
-
#
-
# [:+parent+]
-
# True or false depending on if the resource is considered a parent resource. This defaults to +true+ if a resource
-
# name is given which does not match the controller.
-
#
-
# [:+class+]
-
# The class to use for the model (string or constant). This passed in when the instance variable is not set.
-
# Pass +false+ if there is no associated class for this resource and it will use a symbol of the resource name.
-
#
-
# [:+instance_name+]
-
# The name of the instance variable for this resource.
-
#
-
# [:+through+]
-
# Authorize conditions on this parent resource when instance isn't available.
-
#
-
# [:+prepend+]
-
# Passing +true+ will use prepend_before_filter instead of a normal before_filter.
-
#
-
1
def authorize_resource(*args)
-
cancan_resource_class.add_before_filter(self, :authorize_resource, *args)
-
end
-
-
# Skip both the loading and authorization behavior of CanCan for this given controller. This is primarily
-
# useful to skip the behavior of a superclass. You can pass :only and :except options to specify which actions
-
# to skip the effects on. It will apply to all actions by default.
-
#
-
# class ProjectsController < SomeOtherController
-
# skip_load_and_authorize_resource :only => :index
-
# end
-
#
-
# You can also pass the resource name as the first argument to skip that resource.
-
1
def skip_load_and_authorize_resource(*args)
-
skip_load_resource(*args)
-
skip_authorize_resource(*args)
-
end
-
-
# Skip the loading behavior of CanCan. This is useful when using +load_and_authorize_resource+ but want to
-
# only do authorization on certain actions. You can pass :only and :except options to specify which actions to
-
# skip the effects on. It will apply to all actions by default.
-
#
-
# class ProjectsController < ApplicationController
-
# load_and_authorize_resource
-
# skip_load_resource :only => :index
-
# end
-
#
-
# You can also pass the resource name as the first argument to skip that resource.
-
1
def skip_load_resource(*args)
-
options = args.extract_options!
-
name = args.first
-
cancan_skipper[:load][name] = options
-
end
-
-
# Skip the authorization behavior of CanCan. This is useful when using +load_and_authorize_resource+ but want to
-
# only do loading on certain actions. You can pass :only and :except options to specify which actions to
-
# skip the effects on. It will apply to all actions by default.
-
#
-
# class ProjectsController < ApplicationController
-
# load_and_authorize_resource
-
# skip_authorize_resource :only => :index
-
# end
-
#
-
# You can also pass the resource name as the first argument to skip that resource.
-
1
def skip_authorize_resource(*args)
-
options = args.extract_options!
-
name = args.first
-
cancan_skipper[:authorize][name] = options
-
end
-
-
# Add this to a controller to ensure it performs authorization through +authorized+! or +authorize_resource+ call.
-
# If neither of these authorization methods are called, a CanCan::AuthorizationNotPerformed exception will be raised.
-
# This is normally added to the ApplicationController to ensure all controller actions do authorization.
-
#
-
# class ApplicationController < ActionController::Base
-
# check_authorization
-
# end
-
#
-
# See skip_authorization_check to bypass this check on specific controller actions.
-
#
-
# Options:
-
# [:+only+]
-
# Only applies to given actions.
-
#
-
# [:+except+]
-
# Does not apply to given actions.
-
#
-
# [:+if+]
-
# Supply the name of a controller method to be called. The authorization check only takes place if this returns true.
-
#
-
# check_authorization :if => :admin_controller?
-
#
-
# [:+unless+]
-
# Supply the name of a controller method to be called. The authorization check only takes place if this returns false.
-
#
-
# check_authorization :unless => :devise_controller?
-
#
-
1
def check_authorization(options = {})
-
self.after_filter(options.slice(:only, :except)) do |controller|
-
next if controller.instance_variable_defined?(:@_authorized)
-
next if options[:if] && !controller.send(options[:if])
-
next if options[:unless] && controller.send(options[:unless])
-
raise AuthorizationNotPerformed, "This action failed the check_authorization because it does not authorize_resource. Add skip_authorization_check to bypass this check."
-
end
-
end
-
-
# Call this in the class of a controller to skip the check_authorization behavior on the actions.
-
#
-
# class HomeController < ApplicationController
-
# skip_authorization_check :only => :index
-
# end
-
#
-
# Any arguments are passed to the +before_filter+ it triggers.
-
1
def skip_authorization_check(*args)
-
self.before_filter(*args) do |controller|
-
controller.instance_variable_set(:@_authorized, true)
-
end
-
end
-
-
1
def skip_authorization(*args)
-
raise ImplementationRemoved, "The CanCan skip_authorization method has been renamed to skip_authorization_check. Please update your code."
-
end
-
-
1
def cancan_resource_class
-
if ancestors.map(&:to_s).include? "InheritedResources::Actions"
-
InheritedResource
-
else
-
ControllerResource
-
end
-
end
-
-
1
def cancan_skipper
-
@_cancan_skipper ||= {:authorize => {}, :load => {}}
-
end
-
end
-
-
1
def self.included(base)
-
1
base.extend ClassMethods
-
1
base.helper_method :can?, :cannot?, :current_ability
-
end
-
-
# Raises a CanCan::AccessDenied exception if the current_ability cannot
-
# perform the given action. This is usually called in a controller action or
-
# before filter to perform the authorization.
-
#
-
# def show
-
# @article = Article.find(params[:id])
-
# authorize! :read, @article
-
# end
-
#
-
# A :message option can be passed to specify a different message.
-
#
-
# authorize! :read, @article, :message => "Not authorized to read #{@article.name}"
-
#
-
# You can also use I18n to customize the message. Action aliases defined in Ability work here.
-
#
-
# en:
-
# unauthorized:
-
# manage:
-
# all: "Not authorized to %{action} %{subject}."
-
# user: "Not allowed to manage other user accounts."
-
# update:
-
# project: "Not allowed to update this project."
-
#
-
# You can rescue from the exception in the controller to customize how unauthorized
-
# access is displayed to the user.
-
#
-
# class ApplicationController < ActionController::Base
-
# rescue_from CanCan::AccessDenied do |exception|
-
# redirect_to root_url, :alert => exception.message
-
# end
-
# end
-
#
-
# See the CanCan::AccessDenied exception for more details on working with the exception.
-
#
-
# See the load_and_authorize_resource method to automatically add the authorize! behavior
-
# to the default RESTful actions.
-
1
def authorize!(*args)
-
@_authorized = true
-
current_ability.authorize!(*args)
-
end
-
-
1
def unauthorized!(message = nil)
-
raise ImplementationRemoved, "The unauthorized! method has been removed from CanCan, use authorize! instead."
-
end
-
-
# Creates and returns the current user's ability and caches it. If you
-
# want to override how the Ability is defined then this is the place.
-
# Just define the method in the controller to change behavior.
-
#
-
# def current_ability
-
# # instead of Ability.new(current_user)
-
# @current_ability ||= UserAbility.new(current_account)
-
# end
-
#
-
# Notice it is important to cache the ability object so it is not
-
# recreated every time.
-
1
def current_ability
-
@current_ability ||= ::Ability.new(current_user)
-
end
-
-
# Use in the controller or view to check the user's permission for a given action
-
# and object.
-
#
-
# can? :destroy, @project
-
#
-
# You can also pass the class instead of an instance (if you don't have one handy).
-
#
-
# <% if can? :create, Project %>
-
# <%= link_to "New Project", new_project_path %>
-
# <% end %>
-
#
-
# If it's a nested resource, you can pass the parent instance in a hash. This way it will
-
# check conditions which reach through that association.
-
#
-
# <% if can? :create, @category => Project %>
-
# <%= link_to "New Project", new_project_path %>
-
# <% end %>
-
#
-
# This simply calls "can?" on the current_ability. See Ability#can?.
-
1
def can?(*args)
-
current_ability.can?(*args)
-
end
-
-
# Convenience method which works the same as "can?" but returns the opposite value.
-
#
-
# cannot? :destroy, @project
-
#
-
1
def cannot?(*args)
-
current_ability.cannot?(*args)
-
end
-
end
-
end
-
-
1
if defined? ActionController::Base
-
1
ActionController::Base.class_eval do
-
1
include CanCan::ControllerAdditions
-
end
-
end
-
1
module CanCan
-
# Handle the load and authorization controller logic so we don't clutter up all controllers with non-interface methods.
-
# This class is used internally, so you do not need to call methods directly on it.
-
1
class ControllerResource # :nodoc:
-
1
def self.add_before_filter(controller_class, method, *args)
-
options = args.extract_options!
-
resource_name = args.first
-
before_filter_method = options.delete(:prepend) ? :prepend_before_filter : :before_filter
-
controller_class.send(before_filter_method, options.slice(:only, :except, :if, :unless)) do |controller|
-
controller.class.cancan_resource_class.new(controller, resource_name, options.except(:only, :except, :if, :unless)).send(method)
-
end
-
end
-
-
1
def initialize(controller, *args)
-
@controller = controller
-
@params = controller.params
-
@options = args.extract_options!
-
@name = args.first
-
raise CanCan::ImplementationRemoved, "The :nested option is no longer supported, instead use :through with separate load/authorize call." if @options[:nested]
-
raise CanCan::ImplementationRemoved, "The :name option is no longer supported, instead pass the name as the first argument." if @options[:name]
-
raise CanCan::ImplementationRemoved, "The :resource option has been renamed back to :class, use false if no class." if @options[:resource]
-
end
-
-
1
def load_and_authorize_resource
-
load_resource
-
authorize_resource
-
end
-
-
1
def load_resource
-
unless skip?(:load)
-
if load_instance?
-
self.resource_instance ||= load_resource_instance
-
elsif load_collection?
-
self.collection_instance ||= load_collection
-
end
-
end
-
end
-
-
1
def authorize_resource
-
unless skip?(:authorize)
-
@controller.authorize!(authorization_action, resource_instance || resource_class_with_parent)
-
end
-
end
-
-
1
def parent?
-
@options.has_key?(:parent) ? @options[:parent] : @name && @name != name_from_controller.to_sym
-
end
-
-
1
def skip?(behavior) # This could probably use some refactoring
-
options = @controller.class.cancan_skipper[behavior][@name]
-
if options.nil?
-
false
-
elsif options == {}
-
true
-
elsif options[:except] && ![options[:except]].flatten.include?(@params[:action].to_sym)
-
true
-
elsif [options[:only]].flatten.include?(@params[:action].to_sym)
-
true
-
end
-
end
-
-
1
protected
-
-
1
def load_resource_instance
-
if !parent? && new_actions.include?(@params[:action].to_sym)
-
build_resource
-
elsif id_param || @options[:singleton]
-
find_resource
-
end
-
end
-
-
1
def load_instance?
-
parent? || member_action?
-
end
-
-
1
def load_collection?
-
resource_base.respond_to?(:accessible_by) && !current_ability.has_block?(authorization_action, resource_class)
-
end
-
-
1
def load_collection
-
resource_base.accessible_by(current_ability, authorization_action)
-
end
-
-
1
def build_resource
-
resource = resource_base.new(resource_params || {})
-
assign_attributes(resource)
-
end
-
-
1
def assign_attributes(resource)
-
resource.send("#{parent_name}=", parent_resource) if @options[:singleton] && parent_resource
-
initial_attributes.each do |attr_name, value|
-
resource.send("#{attr_name}=", value)
-
end
-
resource
-
end
-
-
1
def initial_attributes
-
current_ability.attributes_for(@params[:action].to_sym, resource_class).delete_if do |key, value|
-
resource_params && resource_params.include?(key)
-
end
-
end
-
-
1
def find_resource
-
if @options[:singleton] && parent_resource.respond_to?(name)
-
parent_resource.send(name)
-
else
-
if @options[:find_by]
-
if resource_base.respond_to? "find_by_#{@options[:find_by]}!"
-
resource_base.send("find_by_#{@options[:find_by]}!", id_param)
-
elsif resource_base.respond_to? "find_by"
-
resource_base.send("find_by", { @options[:find_by].to_sym => id_param })
-
else
-
resource_base.send(@options[:find_by], id_param)
-
end
-
else
-
adapter.find(resource_base, id_param)
-
end
-
end
-
end
-
-
1
def adapter
-
ModelAdapters::AbstractAdapter.adapter_class(resource_class)
-
end
-
-
1
def authorization_action
-
parent? ? :show : @params[:action].to_sym
-
end
-
-
1
def id_param
-
if @options[:id_param]
-
@params[@options[:id_param]]
-
else
-
@params[parent? ? :"#{name}_id" : :id]
-
end.to_s
-
end
-
-
1
def member_action?
-
new_actions.include?(@params[:action].to_sym) || @options[:singleton] || ( (@params[:id] || @params[@options[:id_param]]) && !collection_actions.include?(@params[:action].to_sym))
-
end
-
-
# Returns the class used for this resource. This can be overriden by the :class option.
-
# If +false+ is passed in it will use the resource name as a symbol in which case it should
-
# only be used for authorization, not loading since there's no class to load through.
-
1
def resource_class
-
case @options[:class]
-
when false then name.to_sym
-
when nil then namespaced_name.to_s.camelize.constantize
-
when String then @options[:class].constantize
-
else @options[:class]
-
end
-
end
-
-
1
def resource_class_with_parent
-
parent_resource ? {parent_resource => resource_class} : resource_class
-
end
-
-
1
def resource_instance=(instance)
-
@controller.instance_variable_set("@#{instance_name}", instance)
-
end
-
-
1
def resource_instance
-
@controller.instance_variable_get("@#{instance_name}") if load_instance?
-
end
-
-
1
def collection_instance=(instance)
-
@controller.instance_variable_set("@#{instance_name.to_s.pluralize}", instance)
-
end
-
-
1
def collection_instance
-
@controller.instance_variable_get("@#{instance_name.to_s.pluralize}")
-
end
-
-
# The object that methods (such as "find", "new" or "build") are called on.
-
# If the :through option is passed it will go through an association on that instance.
-
# If the :shallow option is passed it will use the resource_class if there's no parent
-
# If the :singleton option is passed it won't use the association because it needs to be handled later.
-
1
def resource_base
-
if @options[:through]
-
if parent_resource
-
@options[:singleton] ? resource_class : parent_resource.send(@options[:through_association] || name.to_s.pluralize)
-
elsif @options[:shallow]
-
resource_class
-
else
-
raise AccessDenied.new(nil, authorization_action, resource_class) # maybe this should be a record not found error instead?
-
end
-
else
-
resource_class
-
end
-
end
-
-
1
def parent_name
-
@options[:through] && [@options[:through]].flatten.detect { |i| fetch_parent(i) }
-
end
-
-
# The object to load this resource through.
-
1
def parent_resource
-
parent_name && fetch_parent(parent_name)
-
end
-
-
1
def fetch_parent(name)
-
if @controller.instance_variable_defined? "@#{name}"
-
@controller.instance_variable_get("@#{name}")
-
elsif @controller.respond_to?(name, true)
-
@controller.send(name)
-
end
-
end
-
-
1
def current_ability
-
@controller.send(:current_ability)
-
end
-
-
1
def name
-
@name || name_from_controller
-
end
-
-
1
def resource_params
-
if @options[:class]
-
params_key = extract_key(@options[:class])
-
return @params[params_key] if @params[params_key]
-
end
-
-
resource_params_by_namespaced_name
-
end
-
-
1
def resource_params_by_namespaced_name
-
@params[extract_key(namespaced_name)]
-
end
-
-
1
def namespace
-
@params[:controller].split(/::|\//)[0..-2]
-
end
-
-
1
def namespaced_name
-
[namespace, name.camelize].join('::').singularize.camelize.constantize
-
rescue NameError
-
name
-
end
-
-
1
def name_from_controller
-
@params[:controller].sub("Controller", "").underscore.split('/').last.singularize
-
end
-
-
1
def instance_name
-
@options[:instance_name] || name
-
end
-
-
1
def collection_actions
-
[:index] + [@options[:collection]].flatten
-
end
-
-
1
def new_actions
-
[:new, :create] + [@options[:new]].flatten
-
end
-
-
1
private
-
-
1
def extract_key(value)
-
value.to_s.underscore.gsub('/', '_')
-
end
-
end
-
end
-
1
module CanCan
-
# A general CanCan exception
-
1
class Error < StandardError; end
-
-
# Raised when behavior is not implemented, usually used in an abstract class.
-
1
class NotImplemented < Error; end
-
-
# Raised when removed code is called, an alternative solution is provided in message.
-
1
class ImplementationRemoved < Error; end
-
-
# Raised when using check_authorization without calling authorized!
-
1
class AuthorizationNotPerformed < Error; end
-
-
# This error is raised when a user isn't allowed to access a given controller action.
-
# This usually happens within a call to ControllerAdditions#authorize! but can be
-
# raised manually.
-
#
-
# raise CanCan::AccessDenied.new("Not authorized!", :read, Article)
-
#
-
# The passed message, action, and subject are optional and can later be retrieved when
-
# rescuing from the exception.
-
#
-
# exception.message # => "Not authorized!"
-
# exception.action # => :read
-
# exception.subject # => Article
-
#
-
# If the message is not specified (or is nil) it will default to "You are not authorized
-
# to access this page." This default can be overridden by setting default_message.
-
#
-
# exception.default_message = "Default error message"
-
# exception.message # => "Default error message"
-
#
-
# See ControllerAdditions#authorized! for more information on rescuing from this exception
-
# and customizing the message using I18n.
-
1
class AccessDenied < Error
-
1
attr_reader :action, :subject
-
1
attr_writer :default_message
-
-
1
def initialize(message = nil, action = nil, subject = nil)
-
@message = message
-
@action = action
-
@subject = subject
-
@default_message = I18n.t(:"unauthorized.default", :default => "You are not authorized to access this page.")
-
end
-
-
1
def to_s
-
@message || @default_message
-
end
-
end
-
end
-
1
module CanCan
-
# For use with Inherited Resources
-
1
class InheritedResource < ControllerResource # :nodoc:
-
1
def load_resource_instance
-
if parent?
-
@controller.send :association_chain
-
@controller.instance_variable_get("@#{instance_name}")
-
elsif new_actions.include? @params[:action].to_sym
-
resource = @controller.send :build_resource
-
assign_attributes(resource)
-
else
-
@controller.send :resource
-
end
-
end
-
-
1
def resource_base
-
@controller.send :end_of_association_chain
-
end
-
end
-
end
-
1
module CanCan
-
1
module ModelAdapters
-
1
class AbstractAdapter
-
1
def self.inherited(subclass)
-
2
@subclasses ||= []
-
2
@subclasses << subclass
-
end
-
-
1
def self.adapter_class(model_class)
-
@subclasses.detect { |subclass| subclass.for_class?(model_class) } || DefaultAdapter
-
end
-
-
# Used to determine if the given adapter should be used for the passed in class.
-
1
def self.for_class?(member_class)
-
false # override in subclass
-
end
-
-
# Override if you need custom find behavior
-
1
def self.find(model_class, id)
-
model_class.find(id)
-
end
-
-
# Used to determine if this model adapter will override the matching behavior for a hash of conditions.
-
# If this returns true then matches_conditions_hash? will be called. See Rule#matches_conditions_hash
-
1
def self.override_conditions_hash_matching?(subject, conditions)
-
false
-
end
-
-
# Override if override_conditions_hash_matching? returns true
-
1
def self.matches_conditions_hash?(subject, conditions)
-
raise NotImplemented, "This model adapter does not support matching on a conditions hash."
-
end
-
-
# Used to determine if this model adapter will override the matching behavior for a specific condition.
-
# If this returns true then matches_condition? will be called. See Rule#matches_conditions_hash
-
1
def self.override_condition_matching?(subject, name, value)
-
false
-
end
-
-
# Override if override_condition_matching? returns true
-
1
def self.matches_condition?(subject, name, value)
-
raise NotImplemented, "This model adapter does not support matching on a specific condition."
-
end
-
-
1
def initialize(model_class, rules)
-
@model_class = model_class
-
@rules = rules
-
end
-
-
1
def database_records
-
# This should be overridden in a subclass to return records which match @rules
-
raise NotImplemented, "This model adapter does not support fetching records from the database."
-
end
-
end
-
end
-
end
-
1
module CanCan
-
1
module ModelAdapters
-
1
class ActiveRecordAdapter < AbstractAdapter
-
1
def self.for_class?(model_class)
-
model_class <= ActiveRecord::Base
-
end
-
-
1
def self.override_condition_matching?(subject, name, value)
-
name.kind_of?(MetaWhere::Column) if defined? MetaWhere
-
end
-
-
1
def self.matches_condition?(subject, name, value)
-
subject_value = subject.send(name.column)
-
if name.method.to_s.ends_with? "_any"
-
value.any? { |v| meta_where_match? subject_value, name.method.to_s.sub("_any", ""), v }
-
elsif name.method.to_s.ends_with? "_all"
-
value.all? { |v| meta_where_match? subject_value, name.method.to_s.sub("_all", ""), v }
-
else
-
meta_where_match? subject_value, name.method, value
-
end
-
end
-
-
1
def self.meta_where_match?(subject_value, method, value)
-
case method.to_sym
-
when :eq then subject_value == value
-
when :not_eq then subject_value != value
-
when :in then value.include?(subject_value)
-
when :not_in then !value.include?(subject_value)
-
when :lt then subject_value < value
-
when :lteq then subject_value <= value
-
when :gt then subject_value > value
-
when :gteq then subject_value >= value
-
when :matches then subject_value =~ Regexp.new("^" + Regexp.escape(value).gsub("%", ".*") + "$", true)
-
when :does_not_match then !meta_where_match?(subject_value, :matches, value)
-
else raise NotImplemented, "The #{method} MetaWhere condition is not supported."
-
end
-
end
-
-
# Returns conditions intended to be used inside a database query. Normally you will not call this
-
# method directly, but instead go through ModelAdditions#accessible_by.
-
#
-
# If there is only one "can" definition, a hash of conditions will be returned matching the one defined.
-
#
-
# can :manage, User, :id => 1
-
# query(:manage, User).conditions # => { :id => 1 }
-
#
-
# If there are multiple "can" definitions, a SQL string will be returned to handle complex cases.
-
#
-
# can :manage, User, :id => 1
-
# can :manage, User, :manager_id => 1
-
# cannot :manage, User, :self_managed => true
-
# query(:manage, User).conditions # => "not (self_managed = 't') AND ((manager_id = 1) OR (id = 1))"
-
#
-
1
def conditions
-
if @rules.size == 1 && @rules.first.base_behavior
-
# Return the conditions directly if there's just one definition
-
tableized_conditions(@rules.first.conditions).dup
-
else
-
@rules.reverse.inject(false_sql) do |sql, rule|
-
merge_conditions(sql, tableized_conditions(rule.conditions).dup, rule.base_behavior)
-
end
-
end
-
end
-
-
1
def tableized_conditions(conditions, model_class = @model_class)
-
return conditions unless conditions.kind_of? Hash
-
conditions.inject({}) do |result_hash, (name, value)|
-
if value.kind_of? Hash
-
value = value.dup
-
association_class = model_class.reflect_on_association(name).class_name.constantize
-
nested = value.inject({}) do |nested,(k,v)|
-
if v.kind_of? Hash
-
value.delete(k)
-
nested[k] = v
-
else
-
name = model_class.reflect_on_association(name).table_name.to_sym
-
result_hash[name] = value
-
end
-
nested
-
end
-
result_hash.merge!(tableized_conditions(nested,association_class))
-
else
-
result_hash[name] = value
-
end
-
result_hash
-
end
-
end
-
-
# Returns the associations used in conditions for the :joins option of a search.
-
# See ModelAdditions#accessible_by
-
1
def joins
-
joins_hash = {}
-
@rules.each do |rule|
-
merge_joins(joins_hash, rule.associations_hash)
-
end
-
clean_joins(joins_hash) unless joins_hash.empty?
-
end
-
-
1
def database_records
-
if override_scope
-
@model_class.scoped.merge(override_scope)
-
elsif @model_class.respond_to?(:where) && @model_class.respond_to?(:joins)
-
mergeable_conditions = @rules.select {|rule| rule.unmergeable? }.blank?
-
if mergeable_conditions
-
@model_class.where(conditions).joins(joins)
-
else
-
@model_class.where(*(@rules.map(&:conditions))).joins(joins)
-
end
-
else
-
@model_class.scoped(:conditions => conditions, :joins => joins)
-
end
-
end
-
-
1
private
-
-
1
def override_scope
-
conditions = @rules.map(&:conditions).compact
-
if defined?(ActiveRecord::Relation) && conditions.any? { |c| c.kind_of?(ActiveRecord::Relation) }
-
if conditions.size == 1
-
conditions.first
-
else
-
rule = @rules.detect { |rule| rule.conditions.kind_of?(ActiveRecord::Relation) }
-
raise Error, "Unable to merge an Active Record scope with other conditions. Instead use a hash or SQL for #{rule.actions.first} #{rule.subjects.first} ability."
-
end
-
end
-
end
-
-
1
def merge_conditions(sql, conditions_hash, behavior)
-
if conditions_hash.blank?
-
behavior ? true_sql : false_sql
-
else
-
conditions = sanitize_sql(conditions_hash)
-
case sql
-
when true_sql
-
behavior ? true_sql : "not (#{conditions})"
-
when false_sql
-
behavior ? conditions : false_sql
-
else
-
behavior ? "(#{conditions}) OR (#{sql})" : "not (#{conditions}) AND (#{sql})"
-
end
-
end
-
end
-
-
1
def false_sql
-
sanitize_sql(['?=?', true, false])
-
end
-
-
1
def true_sql
-
sanitize_sql(['?=?', true, true])
-
end
-
-
1
def sanitize_sql(conditions)
-
@model_class.send(:sanitize_sql, conditions)
-
end
-
-
# Takes two hashes and does a deep merge.
-
1
def merge_joins(base, add)
-
add.each do |name, nested|
-
if base[name].is_a?(Hash)
-
merge_joins(base[name], nested) unless nested.empty?
-
else
-
base[name] = nested
-
end
-
end
-
end
-
-
# Removes empty hashes and moves everything into arrays.
-
1
def clean_joins(joins_hash)
-
joins = []
-
joins_hash.each do |name, nested|
-
joins << (nested.empty? ? name : {name => clean_joins(nested)})
-
end
-
joins
-
end
-
end
-
end
-
end
-
-
1
ActiveRecord::Base.class_eval do
-
1
include CanCan::ModelAdditions
-
end
-
1
module CanCan
-
1
module ModelAdapters
-
1
class DefaultAdapter < AbstractAdapter
-
# This adapter is used when no matching adapter is found
-
end
-
end
-
end
-
1
module CanCan
-
-
# This module adds the accessible_by class method to a model. It is included in the model adapters.
-
1
module ModelAdditions
-
1
module ClassMethods
-
# Returns a scope which fetches only the records that the passed ability
-
# can perform a given action on. The action defaults to :index. This
-
# is usually called from a controller and passed the +current_ability+.
-
#
-
# @articles = Article.accessible_by(current_ability)
-
#
-
# Here only the articles which the user is able to read will be returned.
-
# If the user does not have permission to read any articles then an empty
-
# result is returned. Since this is a scope it can be combined with any
-
# other scopes or pagination.
-
#
-
# An alternative action can optionally be passed as a second argument.
-
#
-
# @articles = Article.accessible_by(current_ability, :update)
-
#
-
# Here only the articles which the user can update are returned.
-
1
def accessible_by(ability, action = :index)
-
ability.model_adapter(self, action).database_records
-
end
-
end
-
-
1
def self.included(base)
-
1
base.extend ClassMethods
-
end
-
end
-
end
-
1
module CanCan
-
# This class is used internally and should only be called through Ability.
-
# it holds the information about a "can" call made on Ability and provides
-
# helpful methods to determine permission checking and conditions hash generation.
-
1
class Rule # :nodoc:
-
1
attr_reader :base_behavior, :subjects, :actions, :conditions
-
1
attr_writer :expanded_actions
-
-
# The first argument when initializing is the base_behavior which is a true/false
-
# value. True for "can" and false for "cannot". The next two arguments are the action
-
# and subject respectively (such as :read, @project). The third argument is a hash
-
# of conditions and the last one is the block passed to the "can" call.
-
1
def initialize(base_behavior, action, subject, conditions, block)
-
raise Error, "You are not able to supply a block with a hash of conditions in #{action} #{subject} ability. Use either one." if conditions.kind_of?(Hash) && !block.nil?
-
@match_all = action.nil? && subject.nil?
-
@base_behavior = base_behavior
-
@actions = [action].flatten
-
@subjects = [subject].flatten
-
@conditions = conditions || {}
-
@block = block
-
end
-
-
# Matches both the subject and action, not necessarily the conditions
-
1
def relevant?(action, subject)
-
subject = subject.values.first if subject.class == Hash
-
@match_all || (matches_action?(action) && matches_subject?(subject))
-
end
-
-
# Matches the block or conditions hash
-
1
def matches_conditions?(action, subject, extra_args)
-
if @match_all
-
call_block_with_all(action, subject, extra_args)
-
elsif @block && !subject_class?(subject)
-
@block.call(subject, *extra_args)
-
elsif @conditions.kind_of?(Hash) && subject.class == Hash
-
nested_subject_matches_conditions?(subject)
-
elsif @conditions.kind_of?(Hash) && !subject_class?(subject)
-
matches_conditions_hash?(subject)
-
else
-
# Don't stop at "cannot" definitions when there are conditions.
-
@conditions.empty? ? true : @base_behavior
-
end
-
end
-
-
1
def only_block?
-
conditions_empty? && !@block.nil?
-
end
-
-
1
def only_raw_sql?
-
@block.nil? && !conditions_empty? && !@conditions.kind_of?(Hash)
-
end
-
-
1
def conditions_empty?
-
@conditions == {} || @conditions.nil?
-
end
-
-
1
def unmergeable?
-
@conditions.respond_to?(:keys) && @conditions.present? &&
-
(!@conditions.keys.first.kind_of? Symbol)
-
end
-
-
1
def associations_hash(conditions = @conditions)
-
hash = {}
-
conditions.map do |name, value|
-
hash[name] = associations_hash(value) if value.kind_of? Hash
-
end if conditions.kind_of? Hash
-
hash
-
end
-
-
1
def attributes_from_conditions
-
attributes = {}
-
@conditions.each do |key, value|
-
attributes[key] = value unless [Array, Range, Hash].include? value.class
-
end if @conditions.kind_of? Hash
-
attributes
-
end
-
-
1
private
-
-
1
def subject_class?(subject)
-
klass = (subject.kind_of?(Hash) ? subject.values.first : subject).class
-
klass == Class || klass == Module
-
end
-
-
1
def matches_action?(action)
-
@expanded_actions.include?(:manage) || @expanded_actions.include?(action)
-
end
-
-
1
def matches_subject?(subject)
-
@subjects.include?(:all) || @subjects.include?(subject) || matches_subject_class?(subject)
-
end
-
-
1
def matches_subject_class?(subject)
-
@subjects.any? { |sub| sub.kind_of?(Module) && (subject.kind_of?(sub) || subject.class.to_s == sub.to_s || subject.kind_of?(Module) && subject.ancestors.include?(sub)) }
-
end
-
-
# Checks if the given subject matches the given conditions hash.
-
# This behavior can be overriden by a model adapter by defining two class methods:
-
# override_matching_for_conditions?(subject, conditions) and
-
# matches_conditions_hash?(subject, conditions)
-
1
def matches_conditions_hash?(subject, conditions = @conditions)
-
if conditions.empty?
-
true
-
else
-
if model_adapter(subject).override_conditions_hash_matching? subject, conditions
-
model_adapter(subject).matches_conditions_hash? subject, conditions
-
else
-
conditions.all? do |name, value|
-
if model_adapter(subject).override_condition_matching? subject, name, value
-
model_adapter(subject).matches_condition? subject, name, value
-
else
-
attribute = subject.send(name)
-
if value.kind_of?(Hash)
-
if attribute.kind_of? Array
-
attribute.any? { |element| matches_conditions_hash? element, value }
-
else
-
!attribute.nil? && matches_conditions_hash?(attribute, value)
-
end
-
elsif !value.is_a?(String) && value.kind_of?(Enumerable)
-
value.include? attribute
-
else
-
attribute == value
-
end
-
end
-
end
-
end
-
end
-
end
-
-
1
def nested_subject_matches_conditions?(subject_hash)
-
parent, child = subject_hash.first
-
matches_conditions_hash?(parent, @conditions[parent.class.name.downcase.to_sym] || {})
-
end
-
-
1
def call_block_with_all(action, subject, extra_args)
-
if subject.class == Class
-
@block.call(action, subject, nil, *extra_args)
-
else
-
@block.call(action, subject.class, subject, *extra_args)
-
end
-
end
-
-
1
def model_adapter(subject)
-
CanCan::ModelAdapters::AbstractAdapter.adapter_class(subject_class?(subject) ? subject : subject.class)
-
end
-
end
-
end
-
# encoding: utf-8
-
-
1
require 'fileutils'
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'active_support/core_ext/class/attribute'
-
1
require 'active_support/concern'
-
-
1
module CarrierWave
-
-
1
class << self
-
1
attr_accessor :root, :base_path
-
-
1
def configure(&block)
-
CarrierWave::Uploader::Base.configure(&block)
-
end
-
-
1
def clean_cached_files!(seconds=60*60*24)
-
CarrierWave::Uploader::Base.clean_cached_files!(seconds)
-
end
-
end
-
-
end
-
-
1
if defined?(Merb)
-
-
CarrierWave.root = Merb.dir_for(:public)
-
Merb::BootLoader.before_app_loads do
-
# Setup path for uploaders and load all of them before classes are loaded
-
Merb.push_path(:uploaders, Merb.root / 'app' / 'uploaders', '*.rb')
-
Dir.glob(File.join(Merb.load_paths[:uploaders])).each {|f| require f }
-
end
-
-
elsif defined?(Rails)
-
-
1
module CarrierWave
-
1
class Railtie < Rails::Railtie
-
1
initializer "carrierwave.setup_paths" do
-
1
CarrierWave.root = Rails.root.join(Rails.public_path).to_s
-
1
CarrierWave.base_path = ENV['RAILS_RELATIVE_URL_ROOT']
-
end
-
-
1
initializer "carrierwave.active_record" do
-
1
ActiveSupport.on_load :active_record do
-
1
require 'carrierwave/orm/activerecord'
-
end
-
end
-
-
##
-
# Loads the Carrierwave locale files before the Rails application locales
-
# letting the Rails application overrite the carrierwave locale defaults
-
1
config.before_configuration do
-
1
I18n.load_path << File.join(File.dirname(__FILE__), "carrierwave", "locale", 'en.yml')
-
end
-
end
-
end
-
-
elsif defined?(Sinatra)
-
if defined?(Padrino) && defined?(PADRINO_ROOT)
-
CarrierWave.root = File.join(PADRINO_ROOT, "public")
-
else
-
-
CarrierWave.root = if Sinatra::Application.respond_to?(:public_folder)
-
# Sinatra >= 1.3
-
Sinatra::Application.public_folder
-
else
-
# Sinatra < 1.3
-
Sinatra::Application.public
-
end
-
end
-
end
-
-
1
require "carrierwave/utilities"
-
1
require "carrierwave/error"
-
1
require "carrierwave/sanitized_file"
-
1
require "carrierwave/mount"
-
1
require "carrierwave/processing"
-
1
require "carrierwave/version"
-
1
require "carrierwave/storage"
-
1
require "carrierwave/uploader"
-
1
require "carrierwave/compatibility/paperclip"
-
1
require "carrierwave/test/matchers"
-
# encoding: utf-8
-
-
1
module CarrierWave
-
1
module Compatibility
-
-
##
-
# Mix this module into an Uploader to make it mimic Paperclip's storage paths
-
# This will make your Uploader use the same default storage path as paperclip
-
# does. If you need to override it, you can override the +paperclip_path+ method
-
# and provide a Paperclip style path:
-
#
-
# class MyUploader < CarrierWave::Uploader::Base
-
# include CarrierWave::Compatibility::Paperclip
-
#
-
# def paperclip_path
-
# ":rails_root/public/uploads/:id/:attachment/:style_:basename.:extension"
-
# end
-
# end
-
#
-
# ---
-
#
-
# This file contains code taken from Paperclip
-
#
-
# LICENSE
-
#
-
# The MIT License
-
#
-
# Copyright (c) 2008 Jon Yurek and thoughtbot, inc.
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in
-
# all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#
-
1
module Paperclip
-
1
extend ActiveSupport::Concern
-
-
1
DEFAULT_MAPPINGS = {
-
:rails_root => lambda{|u, f| Rails.root.to_s },
-
:rails_env => lambda{|u, f| Rails.env },
-
:id_partition => lambda{|u, f| ("%09d" % u.model.id).scan(/\d{3}/).join("/")},
-
:id => lambda{|u, f| u.model.id },
-
:attachment => lambda{|u, f| u.mounted_as.to_s.downcase.pluralize },
-
:style => lambda{|u, f| u.paperclip_style },
-
:basename => lambda{|u, f| u.filename.gsub(/#{File.extname(u.filename)}$/, "") },
-
:extension => lambda{|u, d| File.extname(u.filename).gsub(/^\.+/, "")},
-
:class => lambda{|u, f| u.model.class.name.underscore.pluralize}
-
}
-
-
1
included do
-
attr_accessor :filename
-
class_attribute :mappings
-
self.mappings ||= DEFAULT_MAPPINGS.dup
-
end
-
-
1
def store_path(for_file=filename)
-
path = paperclip_path
-
self.filename = for_file
-
path ||= File.join(*[store_dir, paperclip_style.to_s, for_file].compact)
-
interpolate_paperclip_path(path)
-
end
-
-
1
def store_dir
-
":rails_root/public/system/:attachment/:id"
-
end
-
-
1
def paperclip_default_style
-
:original
-
end
-
-
1
def paperclip_path
-
end
-
-
1
def paperclip_style
-
version_name || paperclip_default_style
-
end
-
-
1
module ClassMethods
-
1
def interpolate(sym, &block)
-
mappings[sym] = block
-
end
-
end
-
-
1
private
-
1
def interpolate_paperclip_path(path)
-
mappings.each_pair.inject(path) do |agg, pair|
-
agg.gsub(":#{pair[0]}") { pair[1].call(self, self.paperclip_style).to_s }
-
end
-
end
-
end # Paperclip
-
end # Compatibility
-
end # CarrierWave
-
1
module CarrierWave
-
1
class UploadError < StandardError; end
-
1
class IntegrityError < UploadError; end
-
1
class InvalidParameter < UploadError; end
-
1
class ProcessingError < UploadError; end
-
1
class DownloadError < UploadError; end
-
end
-
# encoding: utf-8
-
-
1
module CarrierWave
-
-
##
-
# If a Class is extended with this module, it gains the mount_uploader
-
# method, which is used for mapping attributes to uploaders and allowing
-
# easy assignment.
-
#
-
# You can use mount_uploader with pretty much any class, however it is
-
# intended to be used with some kind of persistent storage, like an ORM.
-
# If you want to persist the uploaded files in a particular Class, it
-
# needs to implement a `read_uploader` and a `write_uploader` method.
-
#
-
1
module Mount
-
-
##
-
# === Returns
-
#
-
# [Hash{Symbol => CarrierWave}] what uploaders are mounted on which columns
-
#
-
1
def uploaders
-
5
@uploaders ||= superclass.respond_to?(:uploaders) ? superclass.uploaders.dup : {}
-
end
-
-
1
def uploader_options
-
5
@uploader_options ||= superclass.respond_to?(:uploader_options) ? superclass.uploader_options.dup : {}
-
end
-
-
##
-
# Return a particular option for a particular uploader
-
#
-
# === Parameters
-
#
-
# [column (Symbol)] The column the uploader is mounted at
-
# [option (Symbol)] The option, e.g. validate_integrity
-
#
-
# === Returns
-
#
-
# [Object] The option value
-
#
-
1
def uploader_option(column, option)
-
3
if uploader_options[column].has_key?(option)
-
uploader_options[column][option]
-
else
-
3
uploaders[column].send(option)
-
end
-
end
-
-
##
-
# Mounts the given uploader on the given column. This means that assigning
-
# and reading from the column will upload and retrieve files. Supposing
-
# that a User class has an uploader mounted on image, you can assign and
-
# retrieve files like this:
-
#
-
# @user.image # => <Uploader>
-
# @user.image.store!(some_file_object)
-
#
-
# @user.image.url # => '/some_url.png'
-
#
-
# It is also possible (but not recommended) to omit the uploader, which
-
# will create an anonymous uploader class.
-
#
-
# Passing a block makes it possible to customize the uploader. This can be
-
# convenient for brevity, but if there is any significatnt logic in the
-
# uploader, you should do the right thing and have it in its own file.
-
#
-
# === Added instance methods
-
#
-
# Supposing a class has used +mount_uploader+ to mount an uploader on a column
-
# named +image+, in that case the following methods will be added to the class:
-
#
-
# [image] Returns an instance of the uploader only if anything has been uploaded
-
# [image=] Caches the given file
-
#
-
# [image_url] Returns the url to the uploaded file
-
#
-
# [image_cache] Returns a string that identifies the cache location of the file
-
# [image_cache=] Retrieves the file from the cache based on the given cache name
-
#
-
# [remote_image_url] Returns previously cached remote url
-
# [remote_image_url=] Retrieve the file from the remote url
-
#
-
# [remove_image] An attribute reader that can be used with a checkbox to mark a file for removal
-
# [remove_image=] An attribute writer that can be used with a checkbox to mark a file for removal
-
# [remove_image?] Whether the file should be removed when store_image! is called.
-
#
-
# [store_image!] Stores a file that has been assigned with +image=+
-
# [remove_image!] Removes the uploaded file from the filesystem.
-
#
-
# [image_integrity_error] Returns an error object if the last file to be assigned caused an integrity error
-
# [image_processing_error] Returns an error object if the last file to be assigned caused a processing error
-
# [image_download_error] Returns an error object if the last file to be remotely assigned caused a download error
-
#
-
# [write_image_identifier] Uses the write_uploader method to set the identifier.
-
# [image_identifier] Reads out the identifier of the file
-
#
-
# === Parameters
-
#
-
# [column (Symbol)] the attribute to mount this uploader on
-
# [uploader (CarrierWave::Uploader)] the uploader class to mount
-
# [options (Hash{Symbol => Object})] a set of options
-
# [&block (Proc)] customize anonymous uploaders
-
#
-
# === Options
-
#
-
# [:mount_on => Symbol] if the name of the column to be serialized to differs you can override it using this option
-
# [:ignore_integrity_errors => Boolean] if set to true, integrity errors will result in caching failing silently
-
# [:ignore_processing_errors => Boolean] if set to true, processing errors will result in caching failing silently
-
#
-
# === Examples
-
#
-
# Mounting uploaders on different columns.
-
#
-
# class Song
-
# mount_uploader :lyrics, LyricsUploader
-
# mount_uploader :alternative_lyrics, LyricsUploader
-
# mount_uploader :file, SongUploader
-
# end
-
#
-
# This will add an anonymous uploader with only the default settings:
-
#
-
# class Data
-
# mount_uploader :csv
-
# end
-
#
-
# this will add an anonymous uploader overriding the store_dir:
-
#
-
# class Product
-
# mount_uploader :blueprint do
-
# def store_dir
-
# 'blueprints'
-
# end
-
# end
-
# end
-
#
-
1
def mount_uploader(column, uploader=nil, options={}, &block)
-
1
include CarrierWave::Mount::Extension
-
-
1
uploader = build_uploader(uploader, &block)
-
1
uploaders[column.to_sym] = uploader
-
1
uploader_options[column.to_sym] = options
-
-
# Make sure to write over accessors directly defined on the class.
-
# Simply super to the included module below.
-
1
class_eval <<-RUBY, __FILE__, __LINE__+1
-
def #{column}; super; end
-
def #{column}=(new_file); super; end
-
RUBY
-
-
# Mixing this in as a Module instead of class_evaling directly, so we
-
# can maintain the ability to super to any of these methods from within
-
# the class.
-
1
mod = Module.new
-
1
include mod
-
1
mod.class_eval <<-RUBY, __FILE__, __LINE__+1
-
-
def #{column}
-
_mounter(:#{column}).uploader
-
end
-
-
def #{column}=(new_file)
-
_mounter(:#{column}).cache(new_file)
-
end
-
-
def #{column}?
-
_mounter(:#{column}).present?
-
end
-
-
def #{column}_url(*args)
-
_mounter(:#{column}).url(*args)
-
end
-
-
def #{column}_cache
-
_mounter(:#{column}).cache_name
-
end
-
-
def #{column}_cache=(cache_name)
-
_mounter(:#{column}).cache_name = cache_name
-
end
-
-
def remote_#{column}_url
-
_mounter(:#{column}).remote_url
-
end
-
-
def remote_#{column}_url=(url)
-
_mounter(:#{column}).remote_url = url
-
end
-
-
def remove_#{column}
-
_mounter(:#{column}).remove
-
end
-
-
def remove_#{column}!
-
_mounter(:#{column}).remove!
-
end
-
-
def remove_#{column}=(value)
-
_mounter(:#{column}).remove = value
-
end
-
-
def remove_#{column}?
-
_mounter(:#{column}).remove?
-
end
-
-
def store_#{column}!
-
_mounter(:#{column}).store!
-
end
-
-
def #{column}_integrity_error
-
_mounter(:#{column}).integrity_error
-
end
-
-
def #{column}_processing_error
-
_mounter(:#{column}).processing_error
-
end
-
-
def #{column}_download_error
-
_mounter(:#{column}).download_error
-
end
-
-
def write_#{column}_identifier
-
_mounter(:#{column}).write_identifier
-
end
-
-
def #{column}_identifier
-
_mounter(:#{column}).identifier
-
end
-
-
def store_previous_model_for_#{column}
-
serialization_column = _mounter(:#{column}).serialization_column
-
-
if #{column}.remove_previously_stored_files_after_update && send(:"\#{serialization_column}_changed?")
-
@previous_model_for_#{column} ||= self.find_previous_model_for_#{column}
-
end
-
end
-
-
def find_previous_model_for_#{column}
-
self.class.find(to_key.first)
-
end
-
-
def remove_previously_stored_#{column}
-
if @previous_model_for_#{column} && @previous_model_for_#{column}.#{column}.path != #{column}.path
-
@previous_model_for_#{column}.#{column}.remove!
-
@previous_model_for_#{column} = nil
-
end
-
end
-
-
def mark_remove_#{column}_false
-
_mounter(:#{column}).remove = false
-
end
-
-
RUBY
-
end
-
-
1
private
-
-
1
def build_uploader(uploader, &block)
-
1
return uploader if uploader && !block_given?
-
-
uploader = Class.new(uploader || CarrierWave::Uploader::Base)
-
const_set("Uploader#{uploader.object_id}".gsub('-', '_'), uploader)
-
-
if block_given?
-
uploader.class_eval(&block)
-
uploader.recursively_apply_block_to_versions(&block)
-
end
-
-
uploader
-
end
-
-
1
module Extension
-
-
##
-
# overwrite this to read from a serialized attribute
-
#
-
1
def read_uploader(column); end
-
-
##
-
# overwrite this to write to a serialized attribute
-
#
-
1
def write_uploader(column, identifier); end
-
-
1
private
-
-
1
def _mounter(column)
-
# We cannot memoize in frozen objects :(
-
return Mounter.new(self, column) if frozen?
-
@_mounters ||= {}
-
@_mounters[column] ||= Mounter.new(self, column)
-
end
-
-
end # Extension
-
-
# this is an internal class, used by CarrierWave::Mount so that
-
# we don't pollute the model with a lot of methods.
-
1
class Mounter #:nodoc:
-
1
attr_reader :column, :record, :remote_url, :integrity_error, :processing_error, :download_error
-
1
attr_accessor :remove
-
-
1
def initialize(record, column, options={})
-
@record = record
-
@column = column
-
@options = record.class.uploader_options[column]
-
end
-
-
1
def write_identifier
-
return if record.frozen?
-
-
if remove?
-
record.write_uploader(serialization_column, nil)
-
elsif uploader.identifier.present?
-
record.write_uploader(serialization_column, uploader.identifier)
-
end
-
end
-
-
1
def identifier
-
record.read_uploader(serialization_column)
-
end
-
-
1
def uploader
-
@uploader ||= record.class.uploaders[column].new(record, column)
-
@uploader.retrieve_from_store!(identifier) if @uploader.blank? && identifier.present?
-
-
@uploader
-
end
-
-
1
def cache(new_file)
-
uploader.cache!(new_file)
-
@integrity_error = nil
-
@processing_error = nil
-
rescue CarrierWave::IntegrityError => e
-
@integrity_error = e
-
raise e unless option(:ignore_integrity_errors)
-
rescue CarrierWave::ProcessingError => e
-
@processing_error = e
-
raise e unless option(:ignore_processing_errors)
-
end
-
-
1
def cache_name
-
uploader.cache_name
-
end
-
-
1
def cache_name=(cache_name)
-
uploader.retrieve_from_cache!(cache_name) unless uploader.cached?
-
rescue CarrierWave::InvalidParameter
-
end
-
-
1
def remote_url=(url)
-
return if url.blank?
-
-
@remote_url = url
-
@download_error = nil
-
@integrity_error = nil
-
-
uploader.download!(url)
-
-
rescue CarrierWave::DownloadError => e
-
@download_error = e
-
raise e unless option(:ignore_download_errors)
-
rescue CarrierWave::ProcessingError => e
-
@processing_error = e
-
raise e unless option(:ignore_processing_errors)
-
rescue CarrierWave::IntegrityError => e
-
@integrity_error = e
-
raise e unless option(:ignore_integrity_errors)
-
end
-
-
1
def store!
-
return if uploader.blank?
-
-
if remove?
-
uploader.remove!
-
else
-
uploader.store!
-
end
-
end
-
-
1
def url(*args)
-
uploader.url(*args)
-
end
-
-
1
def blank?
-
uploader.blank?
-
end
-
-
1
def remove?
-
remove.present? && remove !~ /\A0|false$\z/
-
end
-
-
1
def remove!
-
uploader.remove!
-
end
-
-
1
def serialization_column
-
option(:mount_on) || column
-
end
-
-
1
attr_accessor :uploader_options
-
-
1
private
-
-
1
def option(name)
-
self.uploader_options ||= {}
-
self.uploader_options[name] ||= record.class.uploader_option(column, name)
-
end
-
-
end # Mounter
-
-
end # Mount
-
end # CarrierWave
-
# encoding: utf-8
-
-
1
require 'active_record'
-
1
require 'carrierwave/validations/active_model'
-
-
1
module CarrierWave
-
1
module ActiveRecord
-
-
1
include CarrierWave::Mount
-
-
##
-
# See +CarrierWave::Mount#mount_uploader+ for documentation
-
#
-
1
def mount_uploader(column, uploader=nil, options={}, &block)
-
1
super
-
-
1
alias_method :read_uploader, :read_attribute
-
1
alias_method :write_uploader, :write_attribute
-
1
public :read_uploader
-
1
public :write_uploader
-
-
1
include CarrierWave::Validations::ActiveModel
-
-
1
validates_integrity_of column if uploader_option(column.to_sym, :validate_integrity)
-
1
validates_processing_of column if uploader_option(column.to_sym, :validate_processing)
-
1
validates_download_of column if uploader_option(column.to_sym, :validate_download)
-
-
1
after_save :"store_#{column}!"
-
1
before_save :"write_#{column}_identifier"
-
1
after_commit :"remove_#{column}!", :on => :destroy
-
1
after_commit :"mark_remove_#{column}_false", :on => :update
-
1
before_update :"store_previous_model_for_#{column}"
-
1
after_save :"remove_previously_stored_#{column}"
-
-
1
class_eval <<-RUBY, __FILE__, __LINE__+1
-
def #{column}=(new_file)
-
column = _mounter(:#{column}).serialization_column
-
send(:"\#{column}_will_change!")
-
super
-
end
-
-
def remote_#{column}_url=(url)
-
column = _mounter(:#{column}).serialization_column
-
send(:"\#{column}_will_change!")
-
super
-
end
-
-
def remove_#{column}!
-
super
-
_mounter(:#{column}).remove = true
-
_mounter(:#{column}).write_identifier
-
end
-
-
def serializable_hash(options=nil)
-
hash = {}
-
-
except = options && options[:except] && Array.wrap(options[:except]).map(&:to_s)
-
only = options && options[:only] && Array.wrap(options[:only]).map(&:to_s)
-
-
self.class.uploaders.each do |column, uploader|
-
if (!only && !except) || (only && only.include?(column.to_s)) || (!only && except && !except.include?(column.to_s))
-
hash[column.to_s] = _mounter(column).uploader.serializable_hash
-
end
-
end
-
super(options).merge(hash)
-
end
-
RUBY
-
-
end
-
-
end # ActiveRecord
-
end # CarrierWave
-
-
1
ActiveRecord::Base.extend CarrierWave::ActiveRecord
-
1
require "carrierwave/processing/rmagick"
-
1
require "carrierwave/processing/mini_magick"
-
1
require "carrierwave/processing/mime_types"
-
# encoding: utf-8
-
-
1
module CarrierWave
-
-
##
-
# This module simplifies the use of the mime-types gem to intelligently
-
# guess and set the content-type of a file. If you want to use this, you'll
-
# need to require this file:
-
#
-
# require 'carrierwave/processing/mime_types'
-
#
-
# And then include it in your uploader:
-
#
-
# class MyUploader < CarrierWave::Uploader::Base
-
# include CarrierWave::MimeTypes
-
# end
-
#
-
# You can now use the provided helper:
-
#
-
# class MyUploader < CarrierWave::Uploader::Base
-
# include CarrierWave::MimeTypes
-
#
-
# process :set_content_type
-
# end
-
#
-
1
module MimeTypes
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
CarrierWave::Utilities::Deprecation.new "0.11.0", "CarrierWave::MimeTypes is deprecated and will be removed in the future, get the content_type from the SanitizedFile object directly."
-
begin
-
require "mime/types"
-
rescue LoadError => e
-
e.message << " (You may need to install the mime-types gem)"
-
raise e
-
end
-
end
-
-
1
module ClassMethods
-
1
def set_content_type(override=false)
-
process :set_content_type => override
-
end
-
end
-
-
1
GENERIC_CONTENT_TYPES = %w[application/octet-stream binary/octet-stream]
-
-
1
def generic_content_type?
-
GENERIC_CONTENT_TYPES.include? file.content_type
-
end
-
-
##
-
# Changes the file content_type using the mime-types gem
-
#
-
# === Parameters
-
#
-
# [override (Boolean)] whether or not to override the file's content_type
-
# if it is already set and not a generic content-type,
-
# false by default
-
#
-
1
def set_content_type(override=false)
-
if override || file.content_type.blank? || generic_content_type?
-
new_content_type = ::MIME::Types.type_for(file.original_filename).first.to_s
-
if file.respond_to?(:content_type=)
-
file.content_type = new_content_type
-
else
-
file.instance_variable_set(:@content_type, new_content_type)
-
end
-
end
-
rescue ::MIME::InvalidContentType => e
-
raise CarrierWave::ProcessingError, I18n.translate(:"errors.messages.mime_types_processing_error", :e => e)
-
end
-
-
end # MimeTypes
-
end # CarrierWave
-
# encoding: utf-8
-
-
1
module CarrierWave
-
-
##
-
# This module simplifies manipulation with MiniMagick by providing a set
-
# of convenient helper methods. If you want to use them, you'll need to
-
# require this file:
-
#
-
# require 'carrierwave/processing/mini_magick'
-
#
-
# And then include it in your uploader:
-
#
-
# class MyUploader < CarrierWave::Uploader::Base
-
# include CarrierWave::MiniMagick
-
# end
-
#
-
# You can now use the provided helpers:
-
#
-
# class MyUploader < CarrierWave::Uploader::Base
-
# include CarrierWave::MiniMagick
-
#
-
# process :resize_to_fit => [200, 200]
-
# end
-
#
-
# Or create your own helpers with the powerful manipulate! method. Check
-
# out the ImageMagick docs at http://www.imagemagick.org/script/command-line-options.php for more
-
# info
-
#
-
# class MyUploader < CarrierWave::Uploader::Base
-
# include CarrierWave::MiniMagick
-
#
-
# process :radial_blur => 10
-
#
-
# def radial_blur(amount)
-
# manipulate! do |img|
-
# img.radial_blur(amount)
-
# img = yield(img) if block_given?
-
# img
-
# end
-
# end
-
#
-
# === Note
-
#
-
# MiniMagick is a mini replacement for RMagick that uses the command line
-
# tool "mogrify" for image manipulation.
-
#
-
# You can find more information here:
-
#
-
# http://mini_magick.rubyforge.org/
-
# and
-
# https://github.com/minimagic/minimagick/
-
#
-
#
-
1
module MiniMagick
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
begin
-
1
require "mini_magick"
-
rescue LoadError => e
-
e.message << " (You may need to install the mini_magick gem)"
-
raise e
-
end
-
end
-
-
1
module ClassMethods
-
1
def convert(format)
-
process :convert => format
-
end
-
-
1
def resize_to_limit(width, height)
-
process :resize_to_limit => [width, height]
-
end
-
-
1
def resize_to_fit(width, height)
-
process :resize_to_fit => [width, height]
-
end
-
-
1
def resize_to_fill(width, height, gravity='Center')
-
process :resize_to_fill => [width, height, gravity]
-
end
-
-
1
def resize_and_pad(width, height, background=:transparent, gravity=::Magick::CenterGravity)
-
process :resize_and_pad => [width, height, background, gravity]
-
end
-
end
-
-
##
-
# Changes the image encoding format to the given format
-
#
-
# See http://www.imagemagick.org/script/command-line-options.php#format
-
#
-
# === Parameters
-
#
-
# [format (#to_s)] an abreviation of the format
-
#
-
# === Yields
-
#
-
# [MiniMagick::Image] additional manipulations to perform
-
#
-
# === Examples
-
#
-
# image.convert(:png)
-
#
-
1
def convert(format)
-
@format = format
-
manipulate! do |img|
-
img.format(format.to_s.downcase)
-
img = yield(img) if block_given?
-
img
-
end
-
end
-
-
##
-
# Resize the image to fit within the specified dimensions while retaining
-
# the original aspect ratio. Will only resize the image if it is larger than the
-
# specified dimensions. The resulting image may be shorter or narrower than specified
-
# in the smaller dimension but will not be larger than the specified values.
-
#
-
# === Parameters
-
#
-
# [width (Integer)] the width to scale the image to
-
# [height (Integer)] the height to scale the image to
-
#
-
# === Yields
-
#
-
# [MiniMagick::Image] additional manipulations to perform
-
#
-
1
def resize_to_limit(width, height)
-
manipulate! do |img|
-
img.resize "#{width}x#{height}>"
-
img = yield(img) if block_given?
-
img
-
end
-
end
-
-
##
-
# Resize the image to fit within the specified dimensions while retaining
-
# the original aspect ratio. The image may be shorter or narrower than
-
# specified in the smaller dimension but will not be larger than the specified values.
-
#
-
# === Parameters
-
#
-
# [width (Integer)] the width to scale the image to
-
# [height (Integer)] the height to scale the image to
-
#
-
# === Yields
-
#
-
# [MiniMagick::Image] additional manipulations to perform
-
#
-
1
def resize_to_fit(width, height)
-
manipulate! do |img|
-
img.resize "#{width}x#{height}"
-
img = yield(img) if block_given?
-
img
-
end
-
end
-
-
##
-
# Resize the image to fit within the specified dimensions while retaining
-
# the aspect ratio of the original image. If necessary, crop the image in the
-
# larger dimension.
-
#
-
# === Parameters
-
#
-
# [width (Integer)] the width to scale the image to
-
# [height (Integer)] the height to scale the image to
-
# [gravity (String)] the current gravity suggestion (default: 'Center'; options: 'NorthWest', 'North', 'NorthEast', 'West', 'Center', 'East', 'SouthWest', 'South', 'SouthEast')
-
#
-
# === Yields
-
#
-
# [MiniMagick::Image] additional manipulations to perform
-
#
-
1
def resize_to_fill(width, height, gravity = 'Center')
-
manipulate! do |img|
-
cols, rows = img[:dimensions]
-
img.combine_options do |cmd|
-
if width != cols || height != rows
-
scale_x = width/cols.to_f
-
scale_y = height/rows.to_f
-
if scale_x >= scale_y
-
cols = (scale_x * (cols + 0.5)).round
-
rows = (scale_x * (rows + 0.5)).round
-
cmd.resize "#{cols}"
-
else
-
cols = (scale_y * (cols + 0.5)).round
-
rows = (scale_y * (rows + 0.5)).round
-
cmd.resize "x#{rows}"
-
end
-
end
-
cmd.gravity gravity
-
cmd.background "rgba(255,255,255,0.0)"
-
cmd.extent "#{width}x#{height}" if cols != width || rows != height
-
end
-
img = yield(img) if block_given?
-
img
-
end
-
end
-
-
##
-
# Resize the image to fit within the specified dimensions while retaining
-
# the original aspect ratio. If necessary, will pad the remaining area
-
# with the given color, which defaults to transparent (for gif and png,
-
# white for jpeg).
-
#
-
# See http://www.imagemagick.org/script/command-line-options.php#gravity
-
# for gravity options.
-
#
-
# === Parameters
-
#
-
# [width (Integer)] the width to scale the image to
-
# [height (Integer)] the height to scale the image to
-
# [background (String, :transparent)] the color of the background as a hexcode, like "#ff45de"
-
# [gravity (String)] how to position the image
-
#
-
# === Yields
-
#
-
# [MiniMagick::Image] additional manipulations to perform
-
#
-
1
def resize_and_pad(width, height, background=:transparent, gravity='Center')
-
manipulate! do |img|
-
img.combine_options do |cmd|
-
cmd.thumbnail "#{width}x#{height}>"
-
if background == :transparent
-
cmd.background "rgba(255, 255, 255, 0.0)"
-
else
-
cmd.background background
-
end
-
cmd.gravity gravity
-
cmd.extent "#{width}x#{height}"
-
end
-
img = yield(img) if block_given?
-
img
-
end
-
end
-
-
##
-
# Manipulate the image with MiniMagick. This method will load up an image
-
# and then pass each of its frames to the supplied block. It will then
-
# save the image to disk.
-
#
-
# === Gotcha
-
#
-
# This method assumes that the object responds to +current_path+.
-
# Any class that this module is mixed into must have a +current_path+ method.
-
# CarrierWave::Uploader does, so you won't need to worry about this in
-
# most cases.
-
#
-
# === Yields
-
#
-
# [MiniMagick::Image] manipulations to perform
-
#
-
# === Raises
-
#
-
# [CarrierWave::ProcessingError] if manipulation failed.
-
#
-
1
def manipulate!
-
cache_stored_file! if !cached?
-
image = ::MiniMagick::Image.open(current_path)
-
-
begin
-
image.format(@format.to_s.downcase) if @format
-
image = yield(image)
-
image.write(current_path)
-
image.run_command("identify", current_path)
-
ensure
-
image.destroy!
-
end
-
rescue ::MiniMagick::Error, ::MiniMagick::Invalid => e
-
default = I18n.translate(:"errors.messages.mini_magick_processing_error", :e => e, :locale => :en)
-
message = I18n.translate(:"errors.messages.mini_magick_processing_error", :e => e, :default => default)
-
raise CarrierWave::ProcessingError, message
-
end
-
-
end # MiniMagick
-
end # CarrierWave
-
# encoding: utf-8
-
-
1
module CarrierWave
-
-
##
-
# This module simplifies manipulation with RMagick by providing a set
-
# of convenient helper methods. If you want to use them, you'll need to
-
# require this file:
-
#
-
# require 'carrierwave/processing/rmagick'
-
#
-
# And then include it in your uploader:
-
#
-
# class MyUploader < CarrierWave::Uploader::Base
-
# include CarrierWave::RMagick
-
# end
-
#
-
# You can now use the provided helpers:
-
#
-
# class MyUploader < CarrierWave::Uploader::Base
-
# include CarrierWave::RMagick
-
#
-
# process :resize_to_fit => [200, 200]
-
# end
-
#
-
# Or create your own helpers with the powerful manipulate! method. Check
-
# out the RMagick docs at http://www.imagemagick.org/RMagick/doc/ for more
-
# info
-
#
-
# class MyUploader < CarrierWave::Uploader::Base
-
# include CarrierWave::RMagick
-
#
-
# process :do_stuff => 10.0
-
#
-
# def do_stuff(blur_factor)
-
# manipulate! do |img|
-
# img = img.sepiatone
-
# img = img.auto_orient
-
# img = img.radial_blur(blur_factor)
-
# end
-
# end
-
# end
-
#
-
# === Note
-
#
-
# You should be aware how RMagick handles memory. manipulate! takes care
-
# of freeing up memory for you, but for optimum memory usage you should
-
# use destructive operations as much as possible:
-
#
-
# DON'T DO THIS:
-
# img = img.resize_to_fit
-
#
-
# DO THIS INSTEAD:
-
# img.resize_to_fit!
-
#
-
# Read this for more information why:
-
#
-
# http://rubyforge.org/forum/forum.php?thread_id=1374&forum_id=1618
-
#
-
1
module RMagick
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
begin
-
require "RMagick"
-
rescue LoadError => e
-
e.message << " (You may need to install the rmagick gem)"
-
raise e
-
end
-
end
-
-
1
module ClassMethods
-
1
def convert(format)
-
process :convert => format
-
end
-
-
1
def resize_to_limit(width, height)
-
process :resize_to_limit => [width, height]
-
end
-
-
1
def resize_to_fit(width, height)
-
process :resize_to_fit => [width, height]
-
end
-
-
1
def resize_to_fill(width, height, gravity=::Magick::CenterGravity)
-
process :resize_to_fill => [width, height, gravity]
-
end
-
-
1
def resize_and_pad(width, height, background=:transparent, gravity=::Magick::CenterGravity)
-
process :resize_and_pad => [width, height, background, gravity]
-
end
-
-
1
def resize_to_geometry_string(geometry_string)
-
process :resize_to_geometry_string => [geometry_string]
-
end
-
end
-
-
##
-
# Changes the image encoding format to the given format
-
#
-
# See even http://www.imagemagick.org/RMagick/doc/magick.html#formats
-
#
-
# === Parameters
-
#
-
# [format (#to_s)] an abreviation of the format
-
#
-
# === Yields
-
#
-
# [Magick::Image] additional manipulations to perform
-
#
-
# === Examples
-
#
-
# image.convert(:png)
-
#
-
1
def convert(format)
-
manipulate!(:format => format)
-
@format = format
-
end
-
-
##
-
# Resize the image to fit within the specified dimensions while retaining
-
# the original aspect ratio. Will only resize the image if it is larger than the
-
# specified dimensions. The resulting image may be shorter or narrower than specified
-
# in the smaller dimension but will not be larger than the specified values.
-
#
-
# === Parameters
-
#
-
# [width (Integer)] the width to scale the image to
-
# [height (Integer)] the height to scale the image to
-
#
-
# === Yields
-
#
-
# [Magick::Image] additional manipulations to perform
-
#
-
1
def resize_to_limit(width, height)
-
manipulate! do |img|
-
geometry = Magick::Geometry.new(width, height, 0, 0, Magick::GreaterGeometry)
-
new_img = img.change_geometry(geometry) do |new_width, new_height|
-
img.resize(new_width, new_height)
-
end
-
destroy_image(img)
-
new_img = yield(new_img) if block_given?
-
new_img
-
end
-
end
-
-
##
-
# From the RMagick documentation: "Resize the image to fit within the
-
# specified dimensions while retaining the original aspect ratio. The
-
# image may be shorter or narrower than specified in the smaller dimension
-
# but will not be larger than the specified values."
-
#
-
# See even http://www.imagemagick.org/RMagick/doc/image3.html#resize_to_fit
-
#
-
# === Parameters
-
#
-
# [width (Integer)] the width to scale the image to
-
# [height (Integer)] the height to scale the image to
-
#
-
# === Yields
-
#
-
# [Magick::Image] additional manipulations to perform
-
#
-
1
def resize_to_fit(width, height)
-
manipulate! do |img|
-
img.resize_to_fit!(width, height)
-
img = yield(img) if block_given?
-
img
-
end
-
end
-
-
##
-
# From the RMagick documentation: "Resize the image to fit within the
-
# specified dimensions while retaining the aspect ratio of the original
-
# image. If necessary, crop the image in the larger dimension."
-
#
-
# See even http://www.imagemagick.org/RMagick/doc/image3.html#resize_to_fill
-
#
-
# === Parameters
-
#
-
# [width (Integer)] the width to scale the image to
-
# [height (Integer)] the height to scale the image to
-
#
-
# === Yields
-
#
-
# [Magick::Image] additional manipulations to perform
-
#
-
1
def resize_to_fill(width, height, gravity=::Magick::CenterGravity)
-
manipulate! do |img|
-
img.crop_resized!(width, height, gravity)
-
img = yield(img) if block_given?
-
img
-
end
-
end
-
-
##
-
# Resize the image to fit within the specified dimensions while retaining
-
# the original aspect ratio. If necessary, will pad the remaining area
-
# with the given color, which defaults to transparent (for gif and png,
-
# white for jpeg).
-
#
-
# === Parameters
-
#
-
# [width (Integer)] the width to scale the image to
-
# [height (Integer)] the height to scale the image to
-
# [background (String, :transparent)] the color of the background as a hexcode, like "#ff45de"
-
# [gravity (Magick::GravityType)] how to position the image
-
#
-
# === Yields
-
#
-
# [Magick::Image] additional manipulations to perform
-
#
-
1
def resize_and_pad(width, height, background=:transparent, gravity=::Magick::CenterGravity)
-
manipulate! do |img|
-
img.resize_to_fit!(width, height)
-
new_img = ::Magick::Image.new(width, height) { self.background_color = background == :transparent ? 'rgba(255,255,255,0)' : background.to_s }
-
if background == :transparent
-
filled = new_img.matte_floodfill(1, 1)
-
else
-
filled = new_img.color_floodfill(1, 1, ::Magick::Pixel.from_color(background))
-
end
-
destroy_image(new_img)
-
filled.composite!(img, gravity, ::Magick::OverCompositeOp)
-
destroy_image(img)
-
filled = yield(filled) if block_given?
-
filled
-
end
-
end
-
-
##
-
# Resize the image per the provided geometry string.
-
#
-
# === Parameters
-
#
-
# [geometry_string (String)] the proportions in which to scale image
-
#
-
# === Yields
-
#
-
# [Magick::Image] additional manipulations to perform
-
#
-
1
def resize_to_geometry_string(geometry_string)
-
manipulate! do |img|
-
new_img = img.change_geometry(geometry_string) do |new_width, new_height|
-
img.resize(new_width, new_height)
-
end
-
destroy_image(img)
-
new_img = yield(new_img) if block_given?
-
new_img
-
end
-
end
-
-
##
-
# Manipulate the image with RMagick. This method will load up an image
-
# and then pass each of its frames to the supplied block. It will then
-
# save the image to disk.
-
#
-
# === Gotcha
-
#
-
# This method assumes that the object responds to +current_path+.
-
# Any class that this module is mixed into must have a +current_path+ method.
-
# CarrierWave::Uploader does, so you won't need to worry about this in
-
# most cases.
-
#
-
# === Yields
-
#
-
# [Magick::Image] manipulations to perform
-
# [Integer] Frame index if the image contains multiple frames
-
# [Hash] options, see below
-
#
-
# === Options
-
#
-
# The options argument to this method is also yielded as the third
-
# block argument.
-
#
-
# Currently, the following options are defined:
-
#
-
# ==== :write
-
# A hash of assignments to be evaluated in the block given to the RMagick write call.
-
#
-
# An example:
-
#
-
# manipulate! do |img, index, options|
-
# options[:write] = {
-
# :quality => 50,
-
# :depth => 8
-
# }
-
# img
-
# end
-
#
-
# This will translate to the following RMagick::Image#write call:
-
#
-
# image.write do |img|
-
# self.quality = 50
-
# self.depth = 8
-
# end
-
#
-
# ==== :read
-
# A hash of assignments to be given to the RMagick read call.
-
#
-
# The options available are identical to those for write, but are passed in directly, like this:
-
#
-
# manipulate! :read => { :density => 300 }
-
#
-
# ==== :format
-
# Specify the output format. If unset, the filename extension is used to determine the format.
-
#
-
# === Raises
-
#
-
# [CarrierWave::ProcessingError] if manipulation failed.
-
#
-
1
def manipulate!(options={}, &block)
-
cache_stored_file! if !cached?
-
-
read_block = create_info_block(options[:read])
-
image = ::Magick::Image.read(current_path, &read_block)
-
frames = ::Magick::ImageList.new
-
-
image.each_with_index do |frame, index|
-
frame = yield *[frame, index, options].take(block.arity) if block_given?
-
frames << frame if frame
-
end
-
frames.append(true) if block_given?
-
-
write_block = create_info_block(options[:write])
-
if options[:format] || @format
-
frames.write("#{options[:format] || @format}:#{current_path}", &write_block)
-
else
-
frames.write(current_path, &write_block)
-
end
-
destroy_image(frames)
-
rescue ::Magick::ImageMagickError => e
-
raise CarrierWave::ProcessingError, I18n.translate(:"errors.messages.rmagick_processing_error", :e => e, :default => I18n.translate(:"errors.messages.rmagick_processing_error", :e => e, :locale => :en))
-
end
-
-
1
private
-
-
1
def create_info_block(options)
-
return nil unless options
-
assignments = options.map { |k, v| "self.#{k} = #{v}" }
-
code = "lambda { |img| " + assignments.join(";") + "}"
-
eval code
-
end
-
-
1
def destroy_image(image)
-
image.destroy! if image.respond_to?(:destroy!)
-
end
-
-
end # RMagick
-
end # CarrierWave
-
# encoding: utf-8
-
-
1
require 'pathname'
-
1
require 'active_support/core_ext/string/multibyte'
-
1
require 'mime/types'
-
-
1
module CarrierWave
-
-
##
-
# SanitizedFile is a base class which provides a common API around all
-
# the different quirky Ruby File libraries. It has support for Tempfile,
-
# File, StringIO, Merb-style upload Hashes, as well as paths given as
-
# Strings and Pathnames.
-
#
-
# It's probably needlessly comprehensive and complex. Help is appreciated.
-
#
-
1
class SanitizedFile
-
-
1
attr_accessor :file
-
-
1
class << self
-
1
attr_writer :sanitize_regexp
-
-
1
def sanitize_regexp
-
@sanitize_regexp ||= /[^a-zA-Z0-9\.\-\+_]/
-
end
-
end
-
-
1
def initialize(file)
-
self.file = file
-
end
-
-
##
-
# Returns the filename as is, without sanitizing it.
-
#
-
# === Returns
-
#
-
# [String] the unsanitized filename
-
#
-
1
def original_filename
-
return @original_filename if @original_filename
-
if @file and @file.respond_to?(:original_filename)
-
@file.original_filename
-
elsif path
-
File.basename(path)
-
end
-
end
-
-
##
-
# Returns the filename, sanitized to strip out any evil characters.
-
#
-
# === Returns
-
#
-
# [String] the sanitized filename
-
#
-
1
def filename
-
sanitize(original_filename) if original_filename
-
end
-
-
1
alias_method :identifier, :filename
-
-
##
-
# Returns the part of the filename before the extension. So if a file is called 'test.jpeg'
-
# this would return 'test'
-
#
-
# === Returns
-
#
-
# [String] the first part of the filename
-
#
-
1
def basename
-
split_extension(filename)[0] if filename
-
end
-
-
##
-
# Returns the file extension
-
#
-
# === Returns
-
#
-
# [String] the extension
-
#
-
1
def extension
-
split_extension(filename)[1] if filename
-
end
-
-
##
-
# Returns the file's size.
-
#
-
# === Returns
-
#
-
# [Integer] the file's size in bytes.
-
#
-
1
def size
-
if is_path?
-
exists? ? File.size(path) : 0
-
elsif @file.respond_to?(:size)
-
@file.size
-
elsif path
-
exists? ? File.size(path) : 0
-
else
-
0
-
end
-
end
-
-
##
-
# Returns the full path to the file. If the file has no path, it will return nil.
-
#
-
# === Returns
-
#
-
# [String, nil] the path where the file is located.
-
#
-
1
def path
-
unless @file.blank?
-
if is_path?
-
File.expand_path(@file)
-
elsif @file.respond_to?(:path) and not @file.path.blank?
-
File.expand_path(@file.path)
-
end
-
end
-
end
-
-
##
-
# === Returns
-
#
-
# [Boolean] whether the file is supplied as a pathname or string.
-
#
-
1
def is_path?
-
!!((@file.is_a?(String) || @file.is_a?(Pathname)) && !@file.blank?)
-
end
-
-
##
-
# === Returns
-
#
-
# [Boolean] whether the file is valid and has a non-zero size
-
#
-
1
def empty?
-
@file.nil? || self.size.nil? || (self.size.zero? && ! self.exists?)
-
end
-
-
##
-
# === Returns
-
#
-
# [Boolean] Whether the file exists
-
#
-
1
def exists?
-
return File.exists?(self.path) if self.path
-
return false
-
end
-
-
##
-
# Returns the contents of the file.
-
#
-
# === Returns
-
#
-
# [String] contents of the file
-
#
-
1
def read
-
if @content
-
@content
-
elsif is_path?
-
File.open(@file, "rb") {|file| file.read}
-
else
-
@file.rewind if @file.respond_to?(:rewind)
-
@content = @file.read
-
@file.close if @file.respond_to?(:close) && @file.respond_to?(:closed?) && !@file.closed?
-
@content
-
end
-
end
-
-
##
-
# Moves the file to the given path
-
#
-
# === Parameters
-
#
-
# [new_path (String)] The path where the file should be moved.
-
# [permissions (Integer)] permissions to set on the file in its new location.
-
# [directory_permissions (Integer)] permissions to set on created directories.
-
#
-
1
def move_to(new_path, permissions=nil, directory_permissions=nil)
-
return if self.empty?
-
new_path = File.expand_path(new_path)
-
-
mkdir!(new_path, directory_permissions)
-
if exists?
-
FileUtils.mv(path, new_path) unless new_path == path
-
else
-
File.open(new_path, "wb") { |f| f.write(read) }
-
end
-
chmod!(new_path, permissions)
-
self.file = new_path
-
self
-
end
-
-
##
-
# Creates a copy of this file and moves it to the given path. Returns the copy.
-
#
-
# === Parameters
-
#
-
# [new_path (String)] The path where the file should be copied to.
-
# [permissions (Integer)] permissions to set on the copy
-
# [directory_permissions (Integer)] permissions to set on created directories.
-
#
-
# === Returns
-
#
-
# @return [CarrierWave::SanitizedFile] the location where the file will be stored.
-
#
-
1
def copy_to(new_path, permissions=nil, directory_permissions=nil)
-
return if self.empty?
-
new_path = File.expand_path(new_path)
-
-
mkdir!(new_path, directory_permissions)
-
if exists?
-
FileUtils.cp(path, new_path) unless new_path == path
-
else
-
File.open(new_path, "wb") { |f| f.write(read) }
-
end
-
chmod!(new_path, permissions)
-
self.class.new({:tempfile => new_path, :content_type => content_type})
-
end
-
-
##
-
# Removes the file from the filesystem.
-
#
-
1
def delete
-
FileUtils.rm(self.path) if exists?
-
end
-
-
##
-
# Returns a File object, or nil if it does not exist.
-
#
-
# === Returns
-
#
-
# [File] a File object representing the SanitizedFile
-
#
-
1
def to_file
-
return @file if @file.is_a?(File)
-
File.open(path, "rb") if exists?
-
end
-
-
##
-
# Returns the content type of the file.
-
#
-
# === Returns
-
#
-
# [String] the content type of the file
-
#
-
1
def content_type
-
return @content_type if @content_type
-
if @file.respond_to?(:content_type) and @file.content_type
-
@content_type = @file.content_type.to_s.chomp
-
elsif path
-
@content_type = ::MIME::Types.type_for(path).first.to_s
-
end
-
end
-
-
##
-
# Sets the content type of the file.
-
#
-
# === Returns
-
#
-
# [String] the content type of the file
-
#
-
1
def content_type=(type)
-
@content_type = type
-
end
-
-
##
-
# Used to sanitize the file name. Public to allow overriding for non-latin characters.
-
#
-
# === Returns
-
#
-
# [Regexp] the regexp for sanitizing the file name
-
#
-
1
def sanitize_regexp
-
CarrierWave::SanitizedFile.sanitize_regexp
-
end
-
-
1
private
-
-
1
def file=(file)
-
if file.is_a?(Hash)
-
@file = file["tempfile"] || file[:tempfile]
-
@original_filename = file["filename"] || file[:filename]
-
@content_type = file["content_type"] || file[:content_type]
-
else
-
@file = file
-
@original_filename = nil
-
@content_type = nil
-
end
-
end
-
-
# create the directory if it doesn't exist
-
1
def mkdir!(path, directory_permissions)
-
options = {}
-
options[:mode] = directory_permissions if directory_permissions
-
FileUtils.mkdir_p(File.dirname(path), options) unless File.exists?(File.dirname(path))
-
end
-
-
1
def chmod!(path, permissions)
-
File.chmod(permissions, path) if permissions
-
end
-
-
# Sanitize the filename, to prevent hacking
-
1
def sanitize(name)
-
name = name.gsub("\\", "/") # work-around for IE
-
name = File.basename(name)
-
name = name.gsub(sanitize_regexp,"_")
-
name = "_#{name}" if name =~ /\A\.+\z/
-
name = "unnamed" if name.size == 0
-
return name.mb_chars.to_s
-
end
-
-
1
def split_extension(filename)
-
# regular expressions to try for identifying extensions
-
extension_matchers = [
-
/\A(.+)\.(tar\.([glx]?z|bz2))\z/, # matches "something.tar.gz"
-
/\A(.+)\.([^\.]+)\z/ # matches "something.jpg"
-
]
-
-
extension_matchers.each do |regexp|
-
if filename =~ regexp
-
return $1, $2
-
end
-
end
-
return filename, "" # In case we weren't able to split the extension
-
end
-
-
end # SanitizedFile
-
end # CarrierWave
-
1
require "carrierwave/storage/abstract"
-
1
require "carrierwave/storage/file"
-
-
1
begin
-
1
require "fog"
-
rescue LoadError
-
end
-
-
1
require "carrierwave/storage/fog" if defined?(Fog)
-
# encoding: utf-8
-
-
1
module CarrierWave
-
1
module Storage
-
-
##
-
# This file serves mostly as a specification for Storage engines. There is no requirement
-
# that storage engines must be a subclass of this class.
-
#
-
1
class Abstract
-
-
1
attr_reader :uploader
-
-
1
def initialize(uploader)
-
@uploader = uploader
-
end
-
-
1
def identifier
-
uploader.filename
-
end
-
-
1
def store!(file)
-
end
-
-
1
def retrieve!(identifier)
-
end
-
-
end # Abstract
-
end # Storage
-
end # CarrierWave
-
# encoding: utf-8
-
-
1
module CarrierWave
-
1
module Storage
-
-
##
-
# File storage stores file to the Filesystem (surprising, no?). There's really not much
-
# to it, it uses the store_dir defined on the uploader as the storage location. That's
-
# pretty much it.
-
#
-
1
class File < Abstract
-
-
##
-
# Move the file to the uploader's store path.
-
#
-
# By default, store!() uses copy_to(), which operates by copying the file
-
# from the cache to the store, then deleting the file from the cache.
-
# If move_to_store() is overriden to return true, then store!() uses move_to(),
-
# which simply moves the file from cache to store. Useful for large files.
-
#
-
# === Parameters
-
#
-
# [file (CarrierWave::SanitizedFile)] the file to store
-
#
-
# === Returns
-
#
-
# [CarrierWave::SanitizedFile] a sanitized file
-
#
-
1
def store!(file)
-
path = ::File.expand_path(uploader.store_path, uploader.root)
-
if uploader.move_to_store
-
file.move_to(path, uploader.permissions, uploader.directory_permissions)
-
else
-
file.copy_to(path, uploader.permissions, uploader.directory_permissions)
-
end
-
end
-
-
##
-
# Retrieve the file from its store path
-
#
-
# === Parameters
-
#
-
# [identifier (String)] the filename of the file
-
#
-
# === Returns
-
#
-
# [CarrierWave::SanitizedFile] a sanitized file
-
#
-
1
def retrieve!(identifier)
-
path = ::File.expand_path(uploader.store_path(identifier), uploader.root)
-
CarrierWave::SanitizedFile.new(path)
-
end
-
-
end # File
-
end # Storage
-
end # CarrierWave
-
# encoding: utf-8
-
-
1
require "carrierwave/uploader/configuration"
-
1
require "carrierwave/uploader/callbacks"
-
1
require "carrierwave/uploader/proxy"
-
1
require "carrierwave/uploader/url"
-
1
require "carrierwave/uploader/mountable"
-
1
require "carrierwave/uploader/cache"
-
1
require "carrierwave/uploader/store"
-
1
require "carrierwave/uploader/download"
-
1
require "carrierwave/uploader/remove"
-
1
require "carrierwave/uploader/extension_whitelist"
-
1
require "carrierwave/uploader/extension_blacklist"
-
1
require "carrierwave/uploader/processing"
-
1
require "carrierwave/uploader/versions"
-
1
require "carrierwave/uploader/default_url"
-
-
1
require "carrierwave/uploader/serialization"
-
-
1
module CarrierWave
-
-
##
-
# See CarrierWave::Uploader::Base
-
#
-
1
module Uploader
-
-
##
-
# An uploader is a class that allows you to easily handle the caching and storage of
-
# uploaded files. Please refer to the README for configuration options.
-
#
-
# Once you have an uploader you can use it in isolation:
-
#
-
# my_uploader = MyUploader.new
-
# my_uploader.cache!(File.open(path_to_file))
-
# my_uploader.retrieve_from_store!('monkey.png')
-
#
-
# Alternatively, you can mount it on an ORM or other persistence layer, with
-
# +CarrierWave::Mount#mount_uploader+. There are extensions for activerecord and datamapper
-
# these are *very* simple (they are only a dozen lines of code), so adding your own should
-
# be trivial.
-
#
-
1
class Base
-
1
attr_reader :file
-
-
1
include CarrierWave::Uploader::Configuration
-
1
include CarrierWave::Uploader::Callbacks
-
1
include CarrierWave::Uploader::Proxy
-
1
include CarrierWave::Uploader::Url
-
1
include CarrierWave::Uploader::Mountable
-
1
include CarrierWave::Uploader::Cache
-
1
include CarrierWave::Uploader::Store
-
1
include CarrierWave::Uploader::Download
-
1
include CarrierWave::Uploader::Remove
-
1
include CarrierWave::Uploader::ExtensionWhitelist
-
1
include CarrierWave::Uploader::ExtensionBlacklist
-
1
include CarrierWave::Uploader::Processing
-
1
include CarrierWave::Uploader::Versions
-
1
include CarrierWave::Uploader::DefaultUrl
-
1
include CarrierWave::Uploader::Serialization
-
end # Base
-
-
end # Uploader
-
end # CarrierWave
-
# encoding: utf-8
-
-
1
module CarrierWave
-
-
1
class FormNotMultipart < UploadError
-
1
def message
-
"You tried to assign a String or a Pathname to an uploader, for security reasons, this is not allowed.\n\n If this is a file upload, please check that your upload form is multipart encoded."
-
end
-
end
-
-
##
-
# Generates a unique cache id for use in the caching system
-
#
-
# === Returns
-
#
-
# [String] a cache id in the format TIMEINT-PID-RND
-
#
-
1
def self.generate_cache_id
-
Time.now.utc.to_i.to_s + '-' + Process.pid.to_s + '-' + ("%04d" % rand(9999))
-
end
-
-
1
module Uploader
-
1
module Cache
-
1
extend ActiveSupport::Concern
-
-
1
include CarrierWave::Uploader::Callbacks
-
1
include CarrierWave::Uploader::Configuration
-
-
1
module ClassMethods
-
-
##
-
# Removes cached files which are older than one day. You could call this method
-
# from a rake task to clean out old cached files.
-
#
-
# You can call this method directly on the module like this:
-
#
-
# CarrierWave.clean_cached_files!
-
#
-
# === Note
-
#
-
# This only works as long as you haven't done anything funky with your cache_dir.
-
# It's recommended that you keep cache files in one place only.
-
#
-
1
def clean_cached_files!(seconds=60*60*24)
-
Dir.glob(File.expand_path(File.join(cache_dir, '*'), CarrierWave.root)).each do |dir|
-
time = dir.scan(/(\d+)-\d+-\d+/).first.map { |t| t.to_i }
-
time = Time.at(*time)
-
if time < (Time.now.utc - seconds)
-
FileUtils.rm_rf(dir)
-
end
-
end
-
end
-
end
-
-
##
-
# Returns true if the uploader has been cached
-
#
-
# === Returns
-
#
-
# [Bool] whether the current file is cached
-
#
-
1
def cached?
-
@cache_id
-
end
-
-
##
-
# Caches the remotely stored file
-
#
-
# This is useful when about to process images. Most processing solutions
-
# require the file to be stored on the local filesystem.
-
#
-
1
def cache_stored_file!
-
cache!
-
end
-
-
1
def sanitized_file
-
_content = file.read
-
if _content.is_a?(File) # could be if storage is Fog
-
sanitized = CarrierWave::Storage::Fog.new(self).retrieve!(File.basename(_content.path))
-
sanitized.read if sanitized.exists?
-
-
else
-
sanitized = SanitizedFile.new :tempfile => StringIO.new(file.read),
-
:filename => File.basename(path), :content_type => file.content_type
-
end
-
sanitized
-
end
-
-
##
-
# Returns a String which uniquely identifies the currently cached file for later retrieval
-
#
-
# === Returns
-
#
-
# [String] a cache name, in the format YYYYMMDD-HHMM-PID-RND/filename.txt
-
#
-
1
def cache_name
-
File.join(cache_id, full_original_filename) if cache_id and original_filename
-
end
-
-
##
-
# Caches the given file. Calls process! to trigger any process callbacks.
-
#
-
# By default, cache!() uses copy_to(), which operates by copying the file
-
# to the cache, then deleting the original file. If move_to_cache() is
-
# overriden to return true, then cache!() uses move_to(), which simply
-
# moves the file to the cache. Useful for large files.
-
#
-
# === Parameters
-
#
-
# [new_file (File, IOString, Tempfile)] any kind of file object
-
#
-
# === Raises
-
#
-
# [CarrierWave::FormNotMultipart] if the assigned parameter is a string
-
#
-
1
def cache!(new_file = sanitized_file)
-
new_file = CarrierWave::SanitizedFile.new(new_file)
-
-
unless new_file.empty?
-
raise CarrierWave::FormNotMultipart if new_file.is_path? && ensure_multipart_form
-
-
with_callbacks(:cache, new_file) do
-
self.cache_id = CarrierWave.generate_cache_id unless cache_id
-
-
@filename = new_file.filename
-
self.original_filename = new_file.filename
-
-
if move_to_cache
-
@file = new_file.move_to(cache_path, permissions, directory_permissions)
-
else
-
@file = new_file.copy_to(cache_path, permissions, directory_permissions)
-
end
-
end
-
end
-
end
-
-
##
-
# Retrieves the file with the given cache_name from the cache.
-
#
-
# === Parameters
-
#
-
# [cache_name (String)] uniquely identifies a cache file
-
#
-
# === Raises
-
#
-
# [CarrierWave::InvalidParameter] if the cache_name is incorrectly formatted.
-
#
-
1
def retrieve_from_cache!(cache_name)
-
with_callbacks(:retrieve_from_cache, cache_name) do
-
self.cache_id, self.original_filename = cache_name.to_s.split('/', 2)
-
@filename = original_filename
-
@file = CarrierWave::SanitizedFile.new(cache_path)
-
end
-
end
-
-
1
private
-
-
1
def cache_path
-
File.expand_path(File.join(cache_dir, cache_name), root)
-
end
-
-
1
attr_reader :cache_id, :original_filename
-
-
# We can override the full_original_filename method in other modules
-
1
alias_method :full_original_filename, :original_filename
-
-
1
def cache_id=(cache_id)
-
raise CarrierWave::InvalidParameter, "invalid cache id" unless cache_id =~ /\A[\d]+\-[\d]+\-[\d]{4}\z/
-
@cache_id = cache_id
-
end
-
-
1
def original_filename=(filename)
-
raise CarrierWave::InvalidParameter, "invalid filename" if filename =~ CarrierWave::SanitizedFile.sanitize_regexp
-
@original_filename = filename
-
end
-
-
end # Cache
-
end # Uploader
-
end # CarrierWave
-
# encoding: utf-8
-
-
1
module CarrierWave
-
1
module Uploader
-
1
module Callbacks
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
class_attribute :_before_callbacks, :_after_callbacks,
-
:instance_writer => false
-
1
self._before_callbacks = Hash.new []
-
1
self._after_callbacks = Hash.new []
-
end
-
-
1
def with_callbacks(kind, *args)
-
self.class._before_callbacks[kind].each { |c| send c, *args }
-
yield
-
self.class._after_callbacks[kind].each { |c| send c, *args }
-
end
-
-
1
module ClassMethods
-
1
def before(kind, callback)
-
2
self._before_callbacks = self._before_callbacks.
-
merge kind => _before_callbacks[kind] + [callback]
-
end
-
-
1
def after(kind, callback)
-
7
self._after_callbacks = self._after_callbacks.
-
merge kind => _after_callbacks[kind] + [callback]
-
end
-
end # ClassMethods
-
-
end # Callbacks
-
end # Uploader
-
end # CarrierWave
-
# encoding: utf-8
-
-
1
module CarrierWave
-
1
module Uploader
-
1
module DefaultUrl
-
-
1
def url(*args)
-
super || default_url
-
end
-
-
##
-
# Override this method in your uploader to provide a default url
-
# in case no file has been cached/stored yet.
-
#
-
1
def default_url; end
-
-
end # DefaultPath
-
end # Uploader
-
end # CarrierWave
-
# encoding: utf-8
-
-
1
require 'open-uri'
-
-
1
module CarrierWave
-
1
module Uploader
-
1
module Download
-
1
extend ActiveSupport::Concern
-
-
1
include CarrierWave::Uploader::Callbacks
-
1
include CarrierWave::Uploader::Configuration
-
1
include CarrierWave::Uploader::Cache
-
-
1
class RemoteFile
-
1
def initialize(uri)
-
@uri = uri
-
end
-
-
1
def original_filename
-
filename = filename_from_header || File.basename(file.base_uri.path)
-
mime_type = MIME::Types[file.content_type].first
-
unless File.extname(filename).present? || mime_type.blank?
-
filename = "#{filename}.#{mime_type.extensions.first}"
-
end
-
filename
-
end
-
-
1
def respond_to?(*args)
-
super or file.respond_to?(*args)
-
end
-
-
1
def http?
-
@uri.scheme =~ /^https?$/
-
end
-
-
1
private
-
-
1
def file
-
if @file.blank?
-
@file = Kernel.open(@uri.to_s)
-
@file = @file.is_a?(String) ? StringIO.new(@file) : @file
-
end
-
@file
-
-
rescue Exception => e
-
raise CarrierWave::DownloadError, "could not download file: #{e.message}"
-
end
-
-
1
def filename_from_header
-
if file.meta.include? 'content-disposition'
-
match = file.meta['content-disposition'].match(/filename="?([^"]+)/)
-
return match[1] unless match.nil? || match[1].empty?
-
end
-
end
-
-
1
def method_missing(*args, &block)
-
file.send(*args, &block)
-
end
-
end
-
-
##
-
# Caches the file by downloading it from the given URL.
-
#
-
# === Parameters
-
#
-
# [url (String)] The URL where the remote file is stored
-
#
-
1
def download!(uri)
-
processed_uri = process_uri(uri)
-
file = RemoteFile.new(processed_uri)
-
raise CarrierWave::DownloadError, "trying to download a file which is not served over HTTP" unless file.http?
-
cache!(file)
-
end
-
-
##
-
# Processes the given URL by parsing and escaping it. Public to allow overriding.
-
#
-
# === Parameters
-
#
-
# [url (String)] The URL where the remote file is stored
-
#
-
1
def process_uri(uri)
-
URI.parse(uri)
-
rescue URI::InvalidURIError
-
uri_parts = uri.split('?')
-
# regexp from Ruby's URI::Parser#regexp[:UNSAFE], with [] specifically removed
-
encoded_uri = URI.encode(uri_parts.shift, /[^\-_.!~*'()a-zA-Z\d;\/?:@&=+$,]/)
-
encoded_uri << '?' << URI.encode(uri_parts.join('?')) if uri_parts.any?
-
URI.parse(encoded_uri) rescue raise CarrierWave::DownloadError, "couldn't parse URL"
-
end
-
-
end # Download
-
end # Uploader
-
end # CarrierWave
-
1
module CarrierWave
-
1
module Uploader
-
1
module ExtensionBlacklist
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
before :cache, :check_blacklist!
-
end
-
-
##
-
# Override this method in your uploader to provide a black list of extensions which
-
# are prohibited to be uploaded. Compares the file's extension case insensitive.
-
# Furthermore, not only strings but Regexp are allowed as well.
-
#
-
# When using a Regexp in the black list, `\A` and `\z` are automatically added to
-
# the Regexp expression, also case insensitive.
-
#
-
# === Returns
-
-
# [NilClass, Array[String,Regexp]] a black list of extensions which are prohibited to be uploaded
-
#
-
# === Examples
-
#
-
# def extension_black_list
-
# %w(swf tiff)
-
# end
-
#
-
# Basically the same, but using a Regexp:
-
#
-
# def extension_black_list
-
# [/swf/, 'tiff']
-
# end
-
#
-
-
1
def extension_black_list; end
-
-
1
private
-
-
1
def check_blacklist!(new_file)
-
extension = new_file.extension.to_s
-
if extension_black_list and extension_black_list.detect { |item| extension =~ /\A#{item}\z/i }
-
raise CarrierWave::IntegrityError, I18n.translate(:"errors.messages.extension_black_list_error", :extension => new_file.extension.inspect, :prohibited_types => extension_black_list.join(", "))
-
end
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
-
1
module CarrierWave
-
1
module Uploader
-
1
module ExtensionWhitelist
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
before :cache, :check_whitelist!
-
end
-
-
##
-
# Override this method in your uploader to provide a white list of extensions which
-
# are allowed to be uploaded. Compares the file's extension case insensitive.
-
# Furthermore, not only strings but Regexp are allowed as well.
-
#
-
# When using a Regexp in the white list, `\A` and `\z` are automatically added to
-
# the Regexp expression, also case insensitive.
-
#
-
# === Returns
-
#
-
# [NilClass, Array[String,Regexp]] a white list of extensions which are allowed to be uploaded
-
#
-
# === Examples
-
#
-
# def extension_white_list
-
# %w(jpg jpeg gif png)
-
# end
-
#
-
# Basically the same, but using a Regexp:
-
#
-
# def extension_white_list
-
# [/jpe?g/, 'gif', 'png']
-
# end
-
#
-
1
def extension_white_list; end
-
-
1
private
-
-
1
def check_whitelist!(new_file)
-
extension = new_file.extension.to_s
-
if extension_white_list and not extension_white_list.detect { |item| extension =~ /\A#{item}\z/i }
-
raise CarrierWave::IntegrityError, I18n.translate(:"errors.messages.extension_white_list_error", :extension => new_file.extension.inspect, :allowed_types => extension_white_list.join(", "))
-
end
-
end
-
-
end # ExtensionWhitelist
-
end # Uploader
-
end # CarrierWave
-
# encoding: utf-8
-
-
1
module CarrierWave
-
1
module Uploader
-
1
module Mountable
-
-
1
attr_reader :model, :mounted_as
-
-
##
-
# If a model is given as the first parameter, it will be stored in the uploader, and
-
# available throught +#model+. Likewise, mounted_as stores the name of the column
-
# where this instance of the uploader is mounted. These values can then be used inside
-
# your uploader.
-
#
-
# If you do not wish to mount your uploaders with the ORM extensions in -more then you
-
# can override this method inside your uploader. Just be sure to call +super+
-
#
-
# === Parameters
-
#
-
# [model (Object)] Any kind of model object
-
# [mounted_as (Symbol)] The name of the column where this uploader is mounted
-
#
-
# === Examples
-
#
-
# class MyUploader < CarrierWave::Uploader::Base
-
#
-
# def store_dir
-
# File.join('public', 'files', mounted_as, model.permalink)
-
# end
-
# end
-
#
-
1
def initialize(model=nil, mounted_as=nil)
-
@model = model
-
@mounted_as = mounted_as
-
end
-
-
end # Mountable
-
end # Uploader
-
end # CarrierWave
-
# encoding: utf-8
-
-
1
module CarrierWave
-
1
module Uploader
-
1
module Processing
-
1
extend ActiveSupport::Concern
-
-
1
include CarrierWave::Uploader::Callbacks
-
-
1
included do
-
1
class_attribute :processors, :instance_writer => false
-
1
self.processors = []
-
-
1
after :cache, :process!
-
end
-
-
1
module ClassMethods
-
-
##
-
# Adds a processor callback which applies operations as a file is uploaded.
-
# The argument may be the name of any method of the uploader, expressed as a symbol,
-
# or a list of such methods, or a hash where the key is a method and the value is
-
# an array of arguments to call the method with
-
#
-
# === Parameters
-
#
-
# args (*Symbol, Hash{Symbol => Array[]})
-
#
-
# === Examples
-
#
-
# class MyUploader < CarrierWave::Uploader::Base
-
#
-
# process :sepiatone, :vignette
-
# process :scale => [200, 200]
-
# process :scale => [200, 200], :if => :image?
-
# process :sepiatone, :if => :image?
-
#
-
# def sepiatone
-
# ...
-
# end
-
#
-
# def vignette
-
# ...
-
# end
-
#
-
# def scale(height, width)
-
# ...
-
# end
-
#
-
# def image?
-
# ...
-
# end
-
#
-
# end
-
#
-
1
def process(*args)
-
4
new_processors = args.inject({}) do |hash, arg|
-
4
arg = { arg => [] } unless arg.is_a?(Hash)
-
4
hash.merge!(arg)
-
end
-
-
4
condition = new_processors.delete(:if)
-
4
new_processors.each do |processor, processor_args|
-
4
self.processors += [[processor, processor_args, condition]]
-
end
-
end
-
-
end # ClassMethods
-
-
##
-
# Apply all process callbacks added through CarrierWave.process
-
#
-
1
def process!(new_file=nil)
-
return unless enable_processing
-
-
self.class.processors.each do |method, args, condition|
-
if(condition)
-
if condition.respond_to?(:call)
-
next unless condition.call(self, :args => args, :method => method, :file => new_file)
-
else
-
next unless self.send(condition, new_file)
-
end
-
end
-
self.send(method, *args)
-
end
-
end
-
-
end # Processing
-
end # Uploader
-
end # CarrierWave
-
# encoding: utf-8
-
-
1
module CarrierWave
-
1
module Uploader
-
1
module Proxy
-
-
##
-
# === Returns
-
#
-
# [Boolean] Whether the uploaded file is blank
-
#
-
1
def blank?
-
file.blank?
-
end
-
-
##
-
# === Returns
-
#
-
# [String] the path where the file is currently located.
-
#
-
1
def current_path
-
file.path if file.respond_to?(:path)
-
end
-
-
1
alias_method :path, :current_path
-
-
##
-
# Returns a string that uniquely identifies the last stored file
-
#
-
# === Returns
-
#
-
# [String] uniquely identifies a file
-
#
-
1
def identifier
-
storage.identifier if storage.respond_to?(:identifier)
-
end
-
-
##
-
# Read the contents of the file
-
#
-
# === Returns
-
#
-
# [String] contents of the file
-
#
-
1
def read
-
file.read if file.respond_to?(:read)
-
end
-
-
##
-
# Fetches the size of the currently stored/cached file
-
#
-
# === Returns
-
#
-
# [Integer] size of the file
-
#
-
1
def size
-
file.respond_to?(:size) ? file.size : 0
-
end
-
-
##
-
# Return the size of the file when asked for its length
-
#
-
# === Returns
-
#
-
# [Integer] size of the file
-
#
-
# === Note
-
#
-
# This was added because of the way Rails handles length/size validations in 3.0.6 and above.
-
#
-
1
def length
-
size
-
end
-
-
##
-
# Read the content type of the file
-
#
-
# === Returns
-
#
-
# [String] content type of the file
-
#
-
1
def content_type
-
file.respond_to?(:content_type) ? file.content_type : nil
-
end
-
-
end # Proxy
-
end # Uploader
-
end # CarrierWave
-
# encoding: utf-8
-
-
1
module CarrierWave
-
1
module Uploader
-
1
module Remove
-
1
extend ActiveSupport::Concern
-
-
1
include CarrierWave::Uploader::Callbacks
-
-
##
-
# Removes the file and reset it
-
#
-
1
def remove!
-
with_callbacks(:remove) do
-
@file.delete if @file
-
@file = nil
-
@cache_id = nil
-
end
-
end
-
-
end # Remove
-
end # Uploader
-
end # CarrierWave
-
# encoding: utf-8
-
-
1
require "json"
-
1
require "active_support/core_ext/hash"
-
-
1
module CarrierWave
-
1
module Uploader
-
1
module Serialization
-
1
extend ActiveSupport::Concern
-
-
1
def serializable_hash(options = nil)
-
{"url" => url}.merge Hash[versions.map { |name, version| [name, { "url" => version.url }] }]
-
end
-
-
1
def as_json(options=nil)
-
Hash[mounted_as || "uploader", serializable_hash]
-
end
-
-
1
def to_json(options=nil)
-
JSON.generate(as_json)
-
end
-
-
1
def to_xml(options={})
-
merged_options = options.merge(:root => mounted_as || "uploader", :type => 'uploader')
-
serializable_hash.to_xml(merged_options)
-
end
-
-
end
-
end
-
end
-
# encoding: utf-8
-
-
1
module CarrierWave
-
1
module Uploader
-
1
module Store
-
1
extend ActiveSupport::Concern
-
-
1
include CarrierWave::Uploader::Callbacks
-
1
include CarrierWave::Uploader::Configuration
-
1
include CarrierWave::Uploader::Cache
-
-
##
-
# Override this in your Uploader to change the filename.
-
#
-
# Be careful using record ids as filenames. If the filename is stored in the database
-
# the record id will be nil when the filename is set. Don't use record ids unless you
-
# understand this limitation.
-
#
-
# Do not use the version_name in the filename, as it will prevent versions from being
-
# loaded correctly.
-
#
-
# === Returns
-
#
-
# [String] a filename
-
#
-
1
def filename
-
@filename
-
end
-
-
##
-
# Calculates the path where the file should be stored. If +for_file+ is given, it will be
-
# used as the filename, otherwise +CarrierWave::Uploader#filename+ is assumed.
-
#
-
# === Parameters
-
#
-
# [for_file (String)] name of the file <optional>
-
#
-
# === Returns
-
#
-
# [String] the store path
-
#
-
1
def store_path(for_file=filename)
-
File.join([store_dir, full_filename(for_file)].compact)
-
end
-
-
##
-
# Stores the file by passing it to this Uploader's storage engine.
-
#
-
# If new_file is omitted, a previously cached file will be stored.
-
#
-
# === Parameters
-
#
-
# [new_file (File, IOString, Tempfile)] any kind of file object
-
#
-
1
def store!(new_file=nil)
-
cache!(new_file) if new_file && ((@cache_id != parent_cache_id) || @cache_id.nil?)
-
if @file and @cache_id
-
with_callbacks(:store, new_file) do
-
new_file = storage.store!(@file)
-
@file.delete if (delete_tmp_file_after_storage && ! move_to_store)
-
delete_cache_id
-
@file = new_file
-
@cache_id = nil
-
end
-
end
-
end
-
-
##
-
# Deletes a cache id (tmp dir in cache)
-
#
-
1
def delete_cache_id
-
if @cache_id
-
path = File.expand_path(File.join(cache_dir, @cache_id), CarrierWave.root)
-
begin
-
Dir.rmdir(path)
-
rescue Errno::ENOENT
-
# Ignore: path does not exist
-
rescue Errno::ENOTDIR
-
# Ignore: path is not a dir
-
rescue Errno::ENOTEMPTY, Errno::EEXIST
-
# Ignore: dir is not empty
-
end
-
end
-
end
-
-
##
-
# Retrieves the file from the storage.
-
#
-
# === Parameters
-
#
-
# [identifier (String)] uniquely identifies the file to retrieve
-
#
-
1
def retrieve_from_store!(identifier)
-
with_callbacks(:retrieve_from_store, identifier) do
-
@file = storage.retrieve!(identifier)
-
end
-
end
-
-
1
private
-
-
1
def full_filename(for_file)
-
for_file
-
end
-
-
1
def storage
-
@storage ||= self.class.storage.new(self)
-
end
-
-
end # Store
-
end # Uploader
-
end # CarrierWave
-
# encoding: utf-8
-
-
1
module CarrierWave
-
1
module Uploader
-
1
module Url
-
1
extend ActiveSupport::Concern
-
1
include CarrierWave::Uploader::Configuration
-
1
include CarrierWave::Utilities::Uri
-
-
##
-
# === Parameters
-
#
-
# [Hash] optional, the query params (only AWS)
-
#
-
# === Returns
-
#
-
# [String] the location where this file is accessible via a url
-
#
-
1
def url(options = {})
-
if file.respond_to?(:url) and not file.url.blank?
-
file.method(:url).arity == 0 ? file.url : file.url(options)
-
elsif file.respond_to?(:path)
-
path = encode_path(file.path.gsub(File.expand_path(root), ''))
-
-
if host = asset_host
-
if host.respond_to? :call
-
"#{host.call(file)}#{path}"
-
else
-
"#{host}#{path}"
-
end
-
else
-
(base_path || "") + path
-
end
-
end
-
end
-
-
1
def to_s
-
url || ''
-
end
-
-
end # Url
-
end # Uploader
-
end # CarrierWave
-
# encoding: utf-8
-
-
1
module CarrierWave
-
1
module Uploader
-
1
module Versions
-
1
extend ActiveSupport::Concern
-
-
1
include CarrierWave::Uploader::Callbacks
-
-
1
included do
-
1
class_attribute :versions, :version_names, :instance_reader => false, :instance_writer => false
-
-
1
self.versions = {}
-
1
self.version_names = []
-
-
1
attr_accessor :parent_cache_id
-
-
1
after :cache, :assign_parent_cache_id
-
1
after :cache, :cache_versions!
-
1
after :store, :store_versions!
-
1
after :remove, :remove_versions!
-
1
after :retrieve_from_cache, :retrieve_versions_from_cache!
-
1
after :retrieve_from_store, :retrieve_versions_from_store!
-
end
-
-
1
module ClassMethods
-
-
##
-
# Adds a new version to this uploader
-
#
-
# === Parameters
-
#
-
# [name (#to_sym)] name of the version
-
# [options (Hash)] optional options hash
-
# [&block (Proc)] a block to eval on this version of the uploader
-
#
-
# === Examples
-
#
-
# class MyUploader < CarrierWave::Uploader::Base
-
#
-
# version :thumb do
-
# process :scale => [200, 200]
-
# end
-
#
-
# version :preview, :if => :image? do
-
# process :scale => [200, 200]
-
# end
-
#
-
# end
-
#
-
1
def version(name, options = {}, &block)
-
3
name = name.to_sym
-
3
build_version(name, options) unless versions[name]
-
-
3
versions[name][:uploader].class_eval(&block) if block
-
3
versions[name]
-
end
-
-
1
def recursively_apply_block_to_versions(&block)
-
versions.each do |name, version|
-
version[:uploader].class_eval(&block)
-
version[:uploader].recursively_apply_block_to_versions(&block)
-
end
-
end
-
-
1
private
-
-
1
def build_version(name, options)
-
3
uploader = Class.new(self)
-
3
const_set("Uploader#{uploader.object_id}".gsub('-', '_'), uploader)
-
3
uploader.version_names += [name]
-
3
uploader.versions = {}
-
3
uploader.processors = []
-
-
3
uploader.class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
# Define the enable_processing method for versions so they get the
-
# value from the parent class unless explicitly overwritten
-
def self.enable_processing(value=nil)
-
self.enable_processing = value if value
-
if !@enable_processing.nil?
-
@enable_processing
-
else
-
superclass.enable_processing
-
end
-
end
-
-
# Regardless of what is set in the parent uploader, do not enforce the
-
# move_to_cache config option on versions because it moves the original
-
# file to the version's target file.
-
#
-
# If you want to enforce this setting on versions, override this method
-
# in each version:
-
#
-
# version :thumb do
-
# def move_to_cache
-
# true
-
# end
-
# end
-
#
-
def move_to_cache
-
false
-
end
-
RUBY
-
-
3
class_eval <<-RUBY
-
def #{name}
-
versions[:#{name}]
-
end
-
RUBY
-
-
# Add the current version hash to class attribute :versions
-
3
current_version = {
-
name => {
-
:uploader => uploader,
-
:options => options
-
}
-
}
-
3
self.versions = versions.merge(current_version)
-
end
-
-
end # ClassMethods
-
-
##
-
# Returns a hash mapping the name of each version of the uploader to an instance of it
-
#
-
# === Returns
-
#
-
# [Hash{Symbol => CarrierWave::Uploader}] a list of uploader instances
-
#
-
1
def versions
-
return @versions if @versions
-
@versions = {}
-
self.class.versions.each do |name, version|
-
@versions[name] = version[:uploader].new(model, mounted_as)
-
end
-
@versions
-
end
-
-
##
-
# === Returns
-
#
-
# [String] the name of this version of the uploader
-
#
-
1
def version_name
-
self.class.version_names.join('_').to_sym unless self.class.version_names.blank?
-
end
-
-
##
-
#
-
# === Parameters
-
#
-
# [name (#to_sym)] name of the version
-
#
-
# === Returns
-
#
-
# [Boolean] True when the version exists according to its :if condition
-
#
-
1
def version_exists?(name)
-
name = name.to_sym
-
-
return false unless self.class.versions.has_key?(name)
-
-
condition = self.class.versions[name][:options][:if]
-
if(condition)
-
if(condition.respond_to?(:call))
-
condition.call(self, :version => name, :file => file)
-
else
-
send(condition, file)
-
end
-
else
-
true
-
end
-
end
-
-
##
-
# When given a version name as a parameter, will return the url for that version
-
# This also works with nested versions.
-
# When given a query hash as a parameter, will return the url with signature that contains query params
-
# Query hash only works with AWS (S3 storage).
-
#
-
# === Example
-
#
-
# my_uploader.url # => /path/to/my/uploader.gif
-
# my_uploader.url(:thumb) # => /path/to/my/thumb_uploader.gif
-
# my_uploader.url(:thumb, :small) # => /path/to/my/thumb_small_uploader.gif
-
# my_uploader.url(:query => {"response-content-disposition" => "attachment"})
-
# my_uploader.url(:version, :sub_version, :query => {"response-content-disposition" => "attachment"})
-
#
-
# === Parameters
-
#
-
# [*args (Symbol)] any number of versions
-
# OR/AND
-
# [Hash] query params
-
#
-
# === Returns
-
#
-
# [String] the location where this file is accessible via a url
-
#
-
1
def url(*args)
-
if (version = args.first) && version.respond_to?(:to_sym)
-
raise ArgumentError, "Version #{version} doesn't exist!" if versions[version.to_sym].nil?
-
# recursively proxy to version
-
versions[version.to_sym].url(*args[1..-1])
-
elsif args.first
-
super(args.first)
-
else
-
super
-
end
-
end
-
-
##
-
# Recreate versions and reprocess them. This can be used to recreate
-
# versions if their parameters somehow have changed.
-
#
-
1
def recreate_versions!(*versions)
-
# Some files could possibly not be stored on the local disk. This
-
# doesn't play nicely with processing. Make sure that we're only
-
# processing a cached file
-
#
-
# The call to store! will trigger the necessary callbacks to both
-
# process this version and all sub-versions
-
if versions.any?
-
file = sanitized_file if !cached?
-
store_versions!(file, versions)
-
else
-
cache! if !cached?
-
store!
-
end
-
end
-
-
1
private
-
1
def assign_parent_cache_id(file)
-
active_versions.each do |name, uploader|
-
uploader.parent_cache_id = @cache_id
-
end
-
end
-
-
1
def active_versions
-
versions.select do |name, uploader|
-
version_exists?(name)
-
end
-
end
-
-
1
def full_filename(for_file)
-
[version_name, super(for_file)].compact.join('_')
-
end
-
-
1
def full_original_filename
-
[version_name, super].compact.join('_')
-
end
-
-
1
def cache_versions!(new_file)
-
# We might have processed the new_file argument after the callbacks were
-
# initialized, so get the actual file based off of the current state of
-
# our file
-
processed_parent = SanitizedFile.new :tempfile => self.file,
-
:filename => new_file.original_filename
-
-
active_versions.each do |name, v|
-
next if v.cached?
-
-
v.send(:cache_id=, cache_id)
-
# If option :from_version is present, create cache using cached file from
-
# version indicated
-
if self.class.versions[name][:options] && self.class.versions[name][:options][:from_version]
-
# Maybe the reference version has not been cached yet
-
unless versions[self.class.versions[name][:options][:from_version]].cached?
-
versions[self.class.versions[name][:options][:from_version]].cache!(processed_parent)
-
end
-
processed_version = SanitizedFile.new :tempfile => versions[self.class.versions[name][:options][:from_version]],
-
:filename => new_file.original_filename
-
v.cache!(processed_version)
-
else
-
v.cache!(processed_parent)
-
end
-
end
-
end
-
-
1
def store_versions!(new_file, versions=nil)
-
if versions
-
active = Hash[active_versions]
-
versions.each { |v| active[v].try(:store!, new_file) } unless active.empty?
-
else
-
active_versions.each { |name, v| v.store!(new_file) }
-
end
-
end
-
-
1
def remove_versions!
-
versions.each { |name, v| v.remove! }
-
end
-
-
1
def retrieve_versions_from_cache!(cache_name)
-
versions.each { |name, v| v.retrieve_from_cache!(cache_name) }
-
end
-
-
1
def retrieve_versions_from_store!(identifier)
-
versions.each { |name, v| v.retrieve_from_store!(identifier) }
-
end
-
-
end # Versions
-
end # Uploader
-
end # CarrierWave
-
# encoding: utf-8
-
-
1
require 'carrierwave/utilities/uri'
-
1
require 'carrierwave/utilities/deprecation'
-
-
1
module CarrierWave
-
1
module Utilities
-
end
-
end
-
# encoding: utf-8
-
1
require 'active_support/deprecation'
-
-
1
module CarrierWave
-
1
module Utilities
-
1
module Deprecation
-
-
1
def self.new version = '0.11.0', message = 'Carrierwave'
-
if ActiveSupport::VERSION::MAJOR < 4
-
ActiveSupport::Deprecation.warn("#{message} (will be removed from version #{version})")
-
else
-
ActiveSupport::Deprecation.new(version, message)
-
end
-
end
-
-
end # Deprecation
-
end # Utilities
-
end # CarrierWave
-
# encoding: utf-8
-
-
1
module CarrierWave
-
1
module Utilities
-
1
module Uri
-
-
1
private
-
1
def encode_path(path)
-
# based on Ruby < 2.0's URI.encode
-
safe_string = URI::REGEXP::PATTERN::UNRESERVED + '\/'
-
unsafe = Regexp.new("[^#{safe_string}]", false)
-
-
path.to_s.gsub(unsafe) do
-
us = $&
-
tmp = ''
-
us.each_byte do |uc|
-
tmp << sprintf('%%%02X', uc)
-
end
-
tmp
-
end
-
end
-
end # Uri
-
end # Utilities
-
end # CarrierWave
-
# encoding: utf-8
-
-
1
require 'active_model/validator'
-
1
require 'active_support/concern'
-
-
1
module CarrierWave
-
-
# == Active Model Presence Validator
-
1
module Validations
-
1
module ActiveModel
-
1
extend ActiveSupport::Concern
-
-
1
class ProcessingValidator < ::ActiveModel::EachValidator
-
-
1
def validate_each(record, attribute, value)
-
if e = record.send("#{attribute}_processing_error")
-
message = (e.message == e.class.to_s) ? :carrierwave_processing_error : e.message
-
record.errors.add(attribute, message)
-
end
-
end
-
end
-
-
1
class IntegrityValidator < ::ActiveModel::EachValidator
-
-
1
def validate_each(record, attribute, value)
-
if e = record.send("#{attribute}_integrity_error")
-
message = (e.message == e.class.to_s) ? :carrierwave_integrity_error : e.message
-
record.errors.add(attribute, message)
-
end
-
end
-
end
-
-
1
class DownloadValidator < ::ActiveModel::EachValidator
-
-
1
def validate_each(record, attribute, value)
-
if e = record.send("#{attribute}_download_error")
-
message = (e.message == e.class.to_s) ? :carrierwave_download_error : e.message
-
record.errors.add(attribute, message)
-
end
-
end
-
end
-
-
1
module HelperMethods
-
-
##
-
# Makes the record invalid if the file couldn't be uploaded due to an integrity error
-
#
-
# Accepts the usual parameters for validations in Rails (:if, :unless, etc...)
-
#
-
1
def validates_integrity_of(*attr_names)
-
1
validates_with IntegrityValidator, _merge_attributes(attr_names)
-
end
-
-
##
-
# Makes the record invalid if the file couldn't be processed (assuming the process failed
-
# with a CarrierWave::ProcessingError)
-
#
-
# Accepts the usual parameters for validations in Rails (:if, :unless, etc...)
-
#
-
1
def validates_processing_of(*attr_names)
-
1
validates_with ProcessingValidator, _merge_attributes(attr_names)
-
end
-
#
-
##
-
# Makes the record invalid if the remote file couldn't be downloaded
-
#
-
# Accepts the usual parameters for validations in Rails (:if, :unless, etc...)
-
#
-
1
def validates_download_of(*attr_names)
-
1
validates_with DownloadValidator, _merge_attributes(attr_names)
-
end
-
end
-
-
1
included do
-
1
extend HelperMethods
-
1
include HelperMethods
-
end
-
end
-
end
-
end
-
1
module CarrierWave
-
1
VERSION = "0.10.0"
-
end
-
1
require 'coffee-script'
-
1
require 'coffee/rails/engine'
-
1
require 'coffee/rails/template_handler'
-
1
require 'coffee/rails/version'
-
1
require 'rails/engine'
-
-
1
module Coffee
-
1
module Rails
-
1
class Engine < ::Rails::Engine
-
1
config.app_generators.javascript_engine :coffee
-
end
-
end
-
end
-
1
module Coffee
-
1
module Rails
-
1
class TemplateHandler
-
1
def self.erb_handler
-
@@erb_handler ||= ActionView::Template.registered_template_handler(:erb)
-
end
-
-
1
def self.call(template)
-
compiled_source = erb_handler.call(template)
-
"CoffeeScript.compile(begin;#{compiled_source};end)"
-
end
-
end
-
end
-
end
-
-
1
ActiveSupport.on_load(:action_view) do
-
1
ActionView::Template.register_template_handler :coffee, Coffee::Rails::TemplateHandler
-
end
-
1
module Coffee
-
1
module Rails
-
1
VERSION = "4.0.1"
-
end
-
end
-
1
require 'coffee_script'
-
1
require 'execjs'
-
1
require 'coffee_script/source'
-
-
1
module CoffeeScript
-
1
Error = ExecJS::Error
-
1
EngineError = ExecJS::RuntimeError
-
1
CompilationError = ExecJS::ProgramError
-
-
1
module Source
-
1
def self.path
-
@path ||= ENV['COFFEESCRIPT_SOURCE_PATH'] || bundled_path
-
end
-
-
1
def self.path=(path)
-
@contents = @version = @bare_option = @context = nil
-
@path = path
-
end
-
-
1
def self.contents
-
@contents ||= File.read(path)
-
end
-
-
1
def self.version
-
@version ||= contents[/CoffeeScript Compiler v([\d.]+)/, 1]
-
end
-
-
1
def self.bare_option
-
@bare_option ||= contents.match(/noWrap/) ? 'noWrap' : 'bare'
-
end
-
-
1
def self.context
-
@context ||= ExecJS.compile(contents)
-
end
-
end
-
-
1
class << self
-
1
def engine
-
end
-
-
1
def engine=(engine)
-
end
-
-
1
def version
-
Source.version
-
end
-
-
# Compile a script (String or IO) to JavaScript.
-
1
def compile(script, options = {})
-
script = script.read if script.respond_to?(:read)
-
-
if options.key?(:bare)
-
elsif options.key?(:no_wrap)
-
options[:bare] = options[:no_wrap]
-
else
-
options[:bare] = false
-
end
-
-
wrapper = <<-WRAPPER
-
(function(script, options) {
-
try {
-
return CoffeeScript.compile(script, options);
-
} catch (err) {
-
if (err instanceof SyntaxError && err.location) {
-
throw new SyntaxError([
-
err.filename || "[stdin]",
-
err.location.first_line + 1,
-
err.location.first_column + 1
-
].join(":") + ": " + err.message)
-
} else {
-
throw err;
-
}
-
}
-
})
-
WRAPPER
-
-
Source.context.call(wrapper, script, options)
-
end
-
end
-
end
-
1
module CoffeeScript
-
1
module Source
-
1
def self.bundled_path
-
File.expand_path("../coffee-script.js", __FILE__)
-
end
-
end
-
end
-
1
require "commonjs/version"
-
-
1
module CommonJS
-
1
autoload :Environment, 'commonjs/environment'
-
1
autoload :Module, 'commonjs/module'
-
end
-
1
require 'pathname'
-
1
module CommonJS
-
1
class Environment
-
-
1
attr_reader :runtime
-
-
1
def initialize(runtime, options = {})
-
1
@runtime = runtime
-
2
@paths = [options[:path]].flatten.map {|path| Pathname(path)}
-
1
@modules = {}
-
end
-
-
1
def require(module_id)
-
97
unless mod = @modules[module_id]
-
40
filepath = find(module_id) or fail LoadError, "no such module '#{module_id}'"
-
40
load = @runtime.eval("(function(module, require, exports) {#{File.read(filepath)}})", filepath.expand_path.to_s)
-
40
@modules[module_id] = mod = Module.new(module_id, self)
-
40
load.call(mod, mod.require_function, mod.exports)
-
end
-
97
return mod.exports
-
end
-
-
1
def native(module_id, impl)
-
5
@modules[module_id] = Module::Native.new(impl)
-
end
-
-
1
def new_object
-
40
@runtime['Object'].new
-
end
-
-
1
private
-
-
1
def find(module_id)
-
# Add `.js` extension if neccessary.
-
40
target = if File.extname(module_id) == '.js' then module_id else "#{module_id}.js" end
-
80
if loadpath = @paths.find { |path| path.join(target).exist? }
-
40
loadpath.join(target)
-
end
-
end
-
-
end
-
end
-
1
module CommonJS
-
1
class Module
-
-
1
attr_reader :id
-
1
attr_accessor :exports
-
-
1
def initialize(id, env)
-
40
@id = id
-
40
@env = env
-
40
@exports = env.new_object
-
40
@segments = id.split('/')
-
end
-
-
1
def require_function
-
@require_function ||= lambda do |*args|
-
81
this, module_id = *args
-
81
module_id ||= this #backwards compatibility with TRR < 0.10
-
81
@env.require(expand(module_id))
-
40
end
-
end
-
-
1
private
-
-
1
def expand(module_id)
-
81
return module_id unless module_id =~ /(\.|\..)/
-
module_id.split('/').inject(@segments[0..-2]) do |path, element|
-
184
path.tap do
-
184
if element == '.'
-
#do nothing
-
elsif element == '..'
-
28
path.pop
-
else
-
106
path.push element
-
end
-
end
-
78
end.join('/')
-
end
-
-
-
1
class Native
-
-
1
attr_reader :exports
-
-
1
def initialize(impl)
-
5
@exports = impl
-
end
-
end
-
end
-
end
-
1
module CommonJS
-
1
VERSION = "0.2.7"
-
end
-
1
module DeviseHelper
-
# A simple way to show error messages for the current devise resource. If you need
-
# to customize this method, you can either overwrite it in your application helpers or
-
# copy the views to your application.
-
#
-
# This method is intended to stay simple and it is unlikely that we are going to change
-
# it to add more behavior or options.
-
1
def devise_error_messages!
-
return "" if resource.errors.empty?
-
-
messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join
-
sentence = I18n.t("errors.messages.not_saved",
-
count: resource.errors.count,
-
resource: resource.class.model_name.human.downcase)
-
-
html = <<-HTML
-
<div id="error_explanation">
-
<h2>#{sentence}</h2>
-
<ul>#{messages}</ul>
-
</div>
-
HTML
-
-
html.html_safe
-
end
-
end
-
1
require 'rails'
-
1
require 'active_support/core_ext/numeric/time'
-
1
require 'active_support/dependencies'
-
1
require 'orm_adapter'
-
1
require 'set'
-
1
require 'securerandom'
-
-
1
module Devise
-
1
autoload :Delegator, 'devise/delegator'
-
1
autoload :FailureApp, 'devise/failure_app'
-
1
autoload :OmniAuth, 'devise/omniauth'
-
1
autoload :ParameterFilter, 'devise/parameter_filter'
-
1
autoload :BaseSanitizer, 'devise/parameter_sanitizer'
-
1
autoload :ParameterSanitizer, 'devise/parameter_sanitizer'
-
1
autoload :TestHelpers, 'devise/test_helpers'
-
1
autoload :TimeInflector, 'devise/time_inflector'
-
1
autoload :TokenGenerator, 'devise/token_generator'
-
-
1
module Controllers
-
1
autoload :Helpers, 'devise/controllers/helpers'
-
1
autoload :Rememberable, 'devise/controllers/rememberable'
-
1
autoload :ScopedViews, 'devise/controllers/scoped_views'
-
1
autoload :SignInOut, 'devise/controllers/sign_in_out'
-
1
autoload :StoreLocation, 'devise/controllers/store_location'
-
1
autoload :UrlHelpers, 'devise/controllers/url_helpers'
-
end
-
-
1
module Hooks
-
1
autoload :Proxy, 'devise/hooks/proxy'
-
end
-
-
1
module Mailers
-
1
autoload :Helpers, 'devise/mailers/helpers'
-
end
-
-
1
module Strategies
-
1
autoload :Base, 'devise/strategies/base'
-
1
autoload :Authenticatable, 'devise/strategies/authenticatable'
-
end
-
-
# Constants which holds devise configuration for extensions. Those should
-
# not be modified by the "end user" (this is why they are constants).
-
1
ALL = []
-
1
CONTROLLERS = ActiveSupport::OrderedHash.new
-
1
ROUTES = ActiveSupport::OrderedHash.new
-
1
STRATEGIES = ActiveSupport::OrderedHash.new
-
1
URL_HELPERS = ActiveSupport::OrderedHash.new
-
-
# Strategies that do not require user input.
-
1
NO_INPUT = []
-
-
# True values used to check params
-
1
TRUE_VALUES = [true, 1, '1', 't', 'T', 'true', 'TRUE']
-
-
# Secret key used by the key generator
-
1
mattr_accessor :secret_key
-
1
@@secret_key = nil
-
-
[ :allow_insecure_token_lookup,
-
:allow_insecure_sign_in_after_confirmation,
-
1
:token_authentication_key ].each do |method|
-
3
class_eval <<-RUBY
-
def self.#{method}
-
ActiveSupport::Deprecation.warn "Devise.#{method} is deprecated " \
-
"and has no effect"
-
end
-
-
def self.#{method}=(val)
-
ActiveSupport::Deprecation.warn "Devise.#{method}= is deprecated " \
-
"and has no effect"
-
end
-
RUBY
-
end
-
-
# Custom domain or key for cookies. Not set by default
-
1
mattr_accessor :rememberable_options
-
1
@@rememberable_options = {}
-
-
# The number of times to encrypt password.
-
1
mattr_accessor :stretches
-
1
@@stretches = 10
-
-
# The default key used when authenticating over http auth.
-
1
mattr_accessor :http_authentication_key
-
1
@@http_authentication_key = nil
-
-
# Keys used when authenticating a user.
-
1
mattr_accessor :authentication_keys
-
1
@@authentication_keys = [ :email ]
-
-
# Request keys used when authenticating a user.
-
1
mattr_accessor :request_keys
-
1
@@request_keys = []
-
-
# Keys that should be case-insensitive.
-
1
mattr_accessor :case_insensitive_keys
-
1
@@case_insensitive_keys = [ :email ]
-
-
# Keys that should have whitespace stripped.
-
1
mattr_accessor :strip_whitespace_keys
-
1
@@strip_whitespace_keys = []
-
-
# If http authentication is enabled by default.
-
1
mattr_accessor :http_authenticatable
-
1
@@http_authenticatable = false
-
-
# If http headers should be returned for ajax requests. True by default.
-
1
mattr_accessor :http_authenticatable_on_xhr
-
1
@@http_authenticatable_on_xhr = true
-
-
# If params authenticatable is enabled by default.
-
1
mattr_accessor :params_authenticatable
-
1
@@params_authenticatable = true
-
-
# The realm used in Http Basic Authentication.
-
1
mattr_accessor :http_authentication_realm
-
1
@@http_authentication_realm = "Application"
-
-
# Email regex used to validate email formats. It simply asserts that
-
# an one (and only one) @ exists in the given string. This is mainly
-
# to give user feedback and not to assert the e-mail validity.
-
1
mattr_accessor :email_regexp
-
1
@@email_regexp = /\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/
-
-
# Range validation for password length
-
1
mattr_accessor :password_length
-
1
@@password_length = 6..128
-
-
# The time the user will be remembered without asking for credentials again.
-
1
mattr_accessor :remember_for
-
1
@@remember_for = 2.weeks
-
-
# If true, extends the user's remember period when remembered via cookie.
-
1
mattr_accessor :extend_remember_period
-
1
@@extend_remember_period = false
-
-
# If true, all the remember me tokens are going to be invalidated when the user signs out.
-
1
mattr_accessor :expire_all_remember_me_on_sign_out
-
1
@@expire_all_remember_me_on_sign_out = true
-
-
# Time interval you can access your account before confirming your account.
-
# nil - allows unconfirmed access for unlimited time
-
1
mattr_accessor :allow_unconfirmed_access_for
-
1
@@allow_unconfirmed_access_for = 0.days
-
-
# Time interval the confirmation token is valid. nil = unlimited
-
1
mattr_accessor :confirm_within
-
1
@@confirm_within = nil
-
-
# Defines which key will be used when confirming an account.
-
1
mattr_accessor :confirmation_keys
-
1
@@confirmation_keys = [ :email ]
-
-
# Defines if email should be reconfirmable.
-
# False by default for backwards compatibility.
-
1
mattr_accessor :reconfirmable
-
1
@@reconfirmable = false
-
-
# Time interval to timeout the user session without activity.
-
1
mattr_accessor :timeout_in
-
1
@@timeout_in = 30.minutes
-
-
# Authentication token expiration on timeout
-
1
mattr_accessor :expire_auth_token_on_timeout
-
1
@@expire_auth_token_on_timeout = false
-
-
# Used to encrypt password. Please generate one with rake secret.
-
1
mattr_accessor :pepper
-
1
@@pepper = nil
-
-
# Scoped views. Since it relies on fallbacks to render default views, it's
-
# turned off by default.
-
1
mattr_accessor :scoped_views
-
1
@@scoped_views = false
-
-
# Defines which strategy can be used to lock an account.
-
# Values: :failed_attempts, :none
-
1
mattr_accessor :lock_strategy
-
1
@@lock_strategy = :failed_attempts
-
-
# Defines which key will be used when locking and unlocking an account
-
1
mattr_accessor :unlock_keys
-
1
@@unlock_keys = [ :email ]
-
-
# Defines which strategy can be used to unlock an account.
-
# Values: :email, :time, :both
-
1
mattr_accessor :unlock_strategy
-
1
@@unlock_strategy = :both
-
-
# Number of authentication tries before locking an account
-
1
mattr_accessor :maximum_attempts
-
1
@@maximum_attempts = 20
-
-
# Time interval to unlock the account if :time is defined as unlock_strategy.
-
1
mattr_accessor :unlock_in
-
1
@@unlock_in = 1.hour
-
-
# Defines which key will be used when recovering the password for an account
-
1
mattr_accessor :reset_password_keys
-
1
@@reset_password_keys = [ :email ]
-
-
# Time interval you can reset your password with a reset password key
-
1
mattr_accessor :reset_password_within
-
1
@@reset_password_within = 6.hours
-
-
# The default scope which is used by warden.
-
1
mattr_accessor :default_scope
-
1
@@default_scope = nil
-
-
# Address which sends Devise e-mails.
-
1
mattr_accessor :mailer_sender
-
1
@@mailer_sender = nil
-
-
# Skip session storage for the following strategies
-
1
mattr_accessor :skip_session_storage
-
1
@@skip_session_storage = []
-
-
# Which formats should be treated as navigational.
-
1
mattr_accessor :navigational_formats
-
1
@@navigational_formats = ["*/*", :html]
-
-
# When set to true, signing out a user signs out all other scopes.
-
1
mattr_accessor :sign_out_all_scopes
-
1
@@sign_out_all_scopes = true
-
-
# The default method used while signing out
-
1
mattr_accessor :sign_out_via
-
1
@@sign_out_via = :get
-
-
# The parent controller all Devise controllers inherits from.
-
# Defaults to ApplicationController. This should be set early
-
# in the initialization process and should be set to a string.
-
1
mattr_accessor :parent_controller
-
1
@@parent_controller = "ApplicationController"
-
-
# The parent mailer all Devise mailers inherit from.
-
# Defaults to ActionMailer::Base. This should be set early
-
# in the initialization process and should be set to a string.
-
1
mattr_accessor :parent_mailer
-
1
@@parent_mailer = "ActionMailer::Base"
-
-
# The router Devise should use to generate routes. Defaults
-
# to :main_app. Should be overridden by engines in order
-
# to provide custom routes.
-
1
mattr_accessor :router_name
-
1
@@router_name = nil
-
-
# Set the omniauth path prefix so it can be overridden when
-
# Devise is used in a mountable engine
-
1
mattr_accessor :omniauth_path_prefix
-
1
@@omniauth_path_prefix = nil
-
-
# Set if we should clean up the CSRF Token on authentication
-
1
mattr_accessor :clean_up_csrf_token_on_authentication
-
1
@@clean_up_csrf_token_on_authentication = true
-
-
# PRIVATE CONFIGURATION
-
-
# Store scopes mappings.
-
1
mattr_reader :mappings
-
1
@@mappings = ActiveSupport::OrderedHash.new
-
-
# Omniauth configurations.
-
1
mattr_reader :omniauth_configs
-
1
@@omniauth_configs = ActiveSupport::OrderedHash.new
-
-
# Define a set of modules that are called when a mapping is added.
-
1
mattr_reader :helpers
-
1
@@helpers = Set.new
-
1
@@helpers << Devise::Controllers::Helpers
-
-
# Private methods to interface with Warden.
-
1
mattr_accessor :warden_config
-
1
@@warden_config = nil
-
1
@@warden_config_blocks = []
-
-
# When true, enter in paranoid mode to avoid user enumeration.
-
1
mattr_accessor :paranoid
-
1
@@paranoid = false
-
-
# When true, warn user if they just used next-to-last attempt of authentication
-
1
mattr_accessor :last_attempt_warning
-
1
@@last_attempt_warning = false
-
-
# Stores the token generator
-
1
mattr_accessor :token_generator
-
1
@@token_generator = nil
-
-
# Default way to setup Devise. Run rails generate devise_install to create
-
# a fresh initializer with all configuration values.
-
1
def self.setup
-
1
yield self
-
end
-
-
1
class Getter
-
1
def initialize name
-
2
@name = name
-
end
-
-
1
def get
-
3
ActiveSupport::Dependencies.constantize(@name)
-
end
-
end
-
-
1
def self.ref(arg)
-
2
if defined?(ActiveSupport::Dependencies::ClassCache)
-
2
ActiveSupport::Dependencies::reference(arg)
-
2
Getter.new(arg)
-
else
-
ActiveSupport::Dependencies.ref(arg)
-
end
-
end
-
-
1
def self.available_router_name
-
router_name || :main_app
-
end
-
-
1
def self.omniauth_providers
-
omniauth_configs.keys
-
end
-
-
# Get the mailer class from the mailer reference object.
-
1
def self.mailer
-
@@mailer_ref.get
-
end
-
-
# Set the mailer reference object to access the mailer.
-
1
def self.mailer=(class_name)
-
1
@@mailer_ref = ref(class_name)
-
end
-
1
self.mailer = "Devise::Mailer"
-
-
# Small method that adds a mapping to Devise.
-
1
def self.add_mapping(resource, options)
-
1
mapping = Devise::Mapping.new(resource, options)
-
1
@@mappings[mapping.name] = mapping
-
1
@@default_scope ||= mapping.name
-
2
@@helpers.each { |h| h.define_helpers(mapping) }
-
1
mapping
-
end
-
-
# Make Devise aware of an 3rd party Devise-module (like invitable). For convenience.
-
#
-
# == Options:
-
#
-
# +model+ - String representing the load path to a custom *model* for this module (to autoload.)
-
# +controller+ - Symbol representing the name of an existing or custom *controller* for this module.
-
# +route+ - Symbol representing the named *route* helper for this module.
-
# +strategy+ - Symbol representing if this module got a custom *strategy*.
-
#
-
# All values, except :model, accept also a boolean and will have the same name as the given module
-
# name.
-
#
-
# == Examples:
-
#
-
# Devise.add_module(:party_module)
-
# Devise.add_module(:party_module, strategy: true, controller: :sessions)
-
# Devise.add_module(:party_module, model: 'party_module/model')
-
#
-
1
def self.add_module(module_name, options = {})
-
10
ALL << module_name
-
10
options.assert_valid_keys(:strategy, :model, :controller, :route, :no_input)
-
-
10
if strategy = options[:strategy]
-
2
strategy = (strategy == true ? module_name : strategy)
-
2
STRATEGIES[module_name] = strategy
-
end
-
-
10
if controller = options[:controller]
-
6
controller = (controller == true ? module_name : controller)
-
6
CONTROLLERS[module_name] = controller
-
end
-
-
10
NO_INPUT << strategy if options[:no_input]
-
-
10
if route = options[:route]
-
6
case route
-
when TrueClass
-
key, value = module_name, []
-
when Symbol
-
1
key, value = route, []
-
when Hash
-
5
key, value = route.keys.first, route.values.flatten
-
else
-
raise ArgumentError, ":route should be true, a Symbol or a Hash"
-
end
-
-
6
URL_HELPERS[key] ||= []
-
6
URL_HELPERS[key].concat(value)
-
6
URL_HELPERS[key].uniq!
-
-
6
ROUTES[module_name] = key
-
end
-
-
10
if options[:model]
-
10
path = (options[:model] == true ? "devise/models/#{module_name}" : options[:model])
-
10
camelized = ActiveSupport::Inflector.camelize(module_name.to_s)
-
10
Devise::Models.send(:autoload, camelized.to_sym, path)
-
end
-
-
10
Devise::Mapping.add_module module_name
-
end
-
-
# Sets warden configuration using a block that will be invoked on warden
-
# initialization.
-
#
-
# Devise.setup do |config|
-
# config.allow_unconfirmed_access_for = 2.days
-
#
-
# config.warden do |manager|
-
# # Configure warden to use other strategies, like oauth.
-
# manager.oauth(:twitter)
-
# end
-
# end
-
1
def self.warden(&block)
-
@@warden_config_blocks << block
-
end
-
-
# Specify an omniauth provider.
-
#
-
# config.omniauth :github, APP_ID, APP_SECRET
-
#
-
1
def self.omniauth(provider, *args)
-
@@helpers << Devise::OmniAuth::UrlHelpers
-
config = Devise::OmniAuth::Config.new(provider, args)
-
@@omniauth_configs[config.strategy_name.to_sym] = config
-
end
-
-
# Include helpers in the given scope to AC and AV.
-
1
def self.include_helpers(scope)
-
1
ActiveSupport.on_load(:action_controller) do
-
1
include scope::Helpers if defined?(scope::Helpers)
-
1
include scope::UrlHelpers
-
end
-
-
1
ActiveSupport.on_load(:action_view) do
-
1
include scope::UrlHelpers
-
end
-
end
-
-
# Regenerates url helpers considering Devise.mapping
-
1
def self.regenerate_helpers!
-
2
Devise::Controllers::UrlHelpers.remove_helpers!
-
2
Devise::Controllers::UrlHelpers.generate_helpers!
-
end
-
-
# A method used internally to setup warden manager from the Rails initialize
-
# block.
-
1
def self.configure_warden! #:nodoc:
-
@@warden_configured ||= begin
-
1
warden_config.failure_app = Devise::Delegator.new
-
1
warden_config.default_scope = Devise.default_scope
-
1
warden_config.intercept_401 = false
-
-
1
Devise.mappings.each_value do |mapping|
-
1
warden_config.scope_defaults mapping.name, strategies: mapping.strategies
-
-
1
warden_config.serialize_into_session(mapping.name) do |record|
-
mapping.to.serialize_into_session(record)
-
end
-
-
1
warden_config.serialize_from_session(mapping.name) do |key|
-
# Previous versions contained an additional entry at the beginning of
-
# key with the record's class name.
-
args = key[-2, 2]
-
mapping.to.serialize_from_session(*args)
-
end
-
end
-
-
1
@@warden_config_blocks.map { |block| block.call Devise.warden_config }
-
1
true
-
2
end
-
end
-
-
# Generate a friendly string randomly to be used as token.
-
1
def self.friendly_token
-
SecureRandom.urlsafe_base64(15).tr('lIO0', 'sxyz')
-
end
-
-
# constant-time comparison algorithm to prevent timing attacks
-
1
def self.secure_compare(a, b)
-
return false if a.blank? || b.blank? || a.bytesize != b.bytesize
-
l = a.unpack "C#{a.bytesize}"
-
-
res = 0
-
b.each_byte { |byte| res |= byte ^ l.shift }
-
res == 0
-
end
-
end
-
-
1
require 'warden'
-
1
require 'devise/mapping'
-
1
require 'devise/models'
-
1
require 'devise/modules'
-
1
require 'devise/rails'
-
1
module Devise
-
1
module Controllers
-
# Those helpers are convenience methods added to ApplicationController.
-
1
module Helpers
-
1
extend ActiveSupport::Concern
-
1
include Devise::Controllers::SignInOut
-
1
include Devise::Controllers::StoreLocation
-
-
1
included do
-
1
helper_method :warden, :signed_in?, :devise_controller?
-
end
-
-
1
module ClassMethods
-
# Define authentication filters and accessor helpers for a group of mappings.
-
# These methods are useful when you are working with multiple mappings that
-
# share some functionality. They are pretty much the same as the ones
-
# defined for normal mappings.
-
#
-
# Example:
-
#
-
# inside BlogsController (or any other controller, it doesn't matter which):
-
# devise_group :blogger, contains: [:user, :admin]
-
#
-
# Generated methods:
-
# authenticate_blogger! # Redirects unless user or admin are signed in
-
# blogger_signed_in? # Checks whether there is either a user or an admin signed in
-
# current_blogger # Currently signed in user or admin
-
# current_bloggers # Currently signed in user and admin
-
#
-
# Use:
-
# before_filter :authenticate_blogger! # Redirects unless either a user or an admin are authenticated
-
# before_filter ->{ authenticate_blogger! :admin } # Redirects to the admin login page
-
# current_blogger :user # Preferably returns a User if one is signed in
-
#
-
1
def devise_group(group_name, opts={})
-
mappings = "[#{ opts[:contains].map { |m| ":#{m}" }.join(',') }]"
-
-
class_eval <<-METHODS, __FILE__, __LINE__ + 1
-
def authenticate_#{group_name}!(favourite=nil, opts={})
-
unless #{group_name}_signed_in?
-
mappings = #{mappings}
-
mappings.unshift mappings.delete(favourite.to_sym) if favourite
-
mappings.each do |mapping|
-
opts[:scope] = mapping
-
warden.authenticate!(opts) if !devise_controller? || opts.delete(:force)
-
end
-
end
-
end
-
-
def #{group_name}_signed_in?
-
#{mappings}.any? do |mapping|
-
warden.authenticate?(scope: mapping)
-
end
-
end
-
-
def current_#{group_name}(favourite=nil)
-
mappings = #{mappings}
-
mappings.unshift mappings.delete(favourite.to_sym) if favourite
-
mappings.each do |mapping|
-
current = warden.authenticate(scope: mapping)
-
return current if current
-
end
-
nil
-
end
-
-
def current_#{group_name.to_s.pluralize}
-
#{mappings}.map do |mapping|
-
warden.authenticate(scope: mapping)
-
end.compact
-
end
-
-
helper_method "current_#{group_name}", "current_#{group_name.to_s.pluralize}", "#{group_name}_signed_in?"
-
METHODS
-
end
-
-
1
def log_process_action(payload)
-
payload[:status] ||= 401 unless payload[:exception]
-
super
-
end
-
end
-
-
# Define authentication filters and accessor helpers based on mappings.
-
# These filters should be used inside the controllers as before_filters,
-
# so you can control the scope of the user who should be signed in to
-
# access that specific controller/action.
-
# Example:
-
#
-
# Roles:
-
# User
-
# Admin
-
#
-
# Generated methods:
-
# authenticate_user! # Signs user in or redirect
-
# authenticate_admin! # Signs admin in or redirect
-
# user_signed_in? # Checks whether there is a user signed in or not
-
# admin_signed_in? # Checks whether there is an admin signed in or not
-
# current_user # Current signed in user
-
# current_admin # Current signed in admin
-
# user_session # Session data available only to the user scope
-
# admin_session # Session data available only to the admin scope
-
#
-
# Use:
-
# before_filter :authenticate_user! # Tell devise to use :user map
-
# before_filter :authenticate_admin! # Tell devise to use :admin map
-
#
-
1
def self.define_helpers(mapping) #:nodoc:
-
1
mapping = mapping.name
-
-
1
class_eval <<-METHODS, __FILE__, __LINE__ + 1
-
def authenticate_#{mapping}!(opts={})
-
opts[:scope] = :#{mapping}
-
warden.authenticate!(opts) if !devise_controller? || opts.delete(:force)
-
end
-
-
def #{mapping}_signed_in?
-
!!current_#{mapping}
-
end
-
-
def current_#{mapping}
-
@current_#{mapping} ||= warden.authenticate(scope: :#{mapping})
-
end
-
-
def #{mapping}_session
-
current_#{mapping} && warden.session(:#{mapping})
-
end
-
METHODS
-
-
1
ActiveSupport.on_load(:action_controller) do
-
1
helper_method "current_#{mapping}", "#{mapping}_signed_in?", "#{mapping}_session"
-
end
-
end
-
-
# The main accessor for the warden proxy instance
-
1
def warden
-
request.env['warden']
-
end
-
-
# Return true if it's a devise_controller. false to all controllers unless
-
# the controllers defined inside devise. Useful if you want to apply a before
-
# filter to all controllers, except the ones in devise:
-
#
-
# before_filter :my_filter, unless: :devise_controller?
-
1
def devise_controller?
-
is_a?(::DeviseController)
-
end
-
-
# Setup a param sanitizer to filter parameters using strong_parameters. See
-
# lib/devise/parameter_sanitizer.rb for more info. Override this
-
# method in your application controller to use your own parameter sanitizer.
-
1
def devise_parameter_sanitizer
-
@devise_parameter_sanitizer ||= if defined?(ActionController::StrongParameters)
-
Devise::ParameterSanitizer.new(resource_class, resource_name, params)
-
else
-
Devise::BaseSanitizer.new(resource_class, resource_name, params)
-
end
-
end
-
-
# Tell warden that params authentication is allowed for that specific page.
-
1
def allow_params_authentication!
-
request.env["devise.allow_params_authentication"] = true
-
end
-
-
# The scope root url to be used when they're signed in. By default, it first
-
# tries to find a resource_root_path, otherwise it uses the root_path.
-
1
def signed_in_root_path(resource_or_scope)
-
scope = Devise::Mapping.find_scope!(resource_or_scope)
-
router_name = Devise.mappings[scope].router_name
-
-
home_path = "#{scope}_root_path"
-
-
context = router_name ? send(router_name) : self
-
-
if context.respond_to?(home_path, true)
-
context.send(home_path)
-
elsif context.respond_to?(:root_path)
-
context.root_path
-
elsif respond_to?(:root_path)
-
root_path
-
else
-
"/"
-
end
-
end
-
-
# The default url to be used after signing in. This is used by all Devise
-
# controllers and you can overwrite it in your ApplicationController to
-
# provide a custom hook for a custom resource.
-
#
-
# By default, it first tries to find a valid resource_return_to key in the
-
# session, then it fallbacks to resource_root_path, otherwise it uses the
-
# root path. For a user scope, you can define the default url in
-
# the following way:
-
#
-
# map.user_root '/users', controller: 'users' # creates user_root_path
-
#
-
# map.namespace :user do |user|
-
# user.root controller: 'users' # creates user_root_path
-
# end
-
#
-
# If the resource root path is not defined, root_path is used. However,
-
# if this default is not enough, you can customize it, for example:
-
#
-
# def after_sign_in_path_for(resource)
-
# stored_location_for(resource) ||
-
# if resource.is_a?(User) && resource.can_publish?
-
# publisher_url
-
# else
-
# super
-
# end
-
# end
-
#
-
1
def after_sign_in_path_for(resource_or_scope)
-
stored_location_for(resource_or_scope) || signed_in_root_path(resource_or_scope)
-
end
-
-
# Method used by sessions controller to sign out a user. You can overwrite
-
# it in your ApplicationController to provide a custom hook for a custom
-
# scope. Notice that differently from +after_sign_in_path_for+ this method
-
# receives a symbol with the scope, and not the resource.
-
#
-
# By default it is the root_path.
-
1
def after_sign_out_path_for(resource_or_scope)
-
scope = Devise::Mapping.find_scope!(resource_or_scope)
-
router_name = Devise.mappings[scope].router_name
-
context = router_name ? send(router_name) : self
-
context.respond_to?(:root_path) ? context.root_path : "/"
-
end
-
-
# Sign in a user and tries to redirect first to the stored location and
-
# then to the url specified by after_sign_in_path_for. It accepts the same
-
# parameters as the sign_in method.
-
1
def sign_in_and_redirect(resource_or_scope, *args)
-
options = args.extract_options!
-
scope = Devise::Mapping.find_scope!(resource_or_scope)
-
resource = args.last || resource_or_scope
-
sign_in(scope, resource, options)
-
redirect_to after_sign_in_path_for(resource)
-
end
-
-
# Sign out a user and tries to redirect to the url specified by
-
# after_sign_out_path_for.
-
1
def sign_out_and_redirect(resource_or_scope)
-
scope = Devise::Mapping.find_scope!(resource_or_scope)
-
redirect_path = after_sign_out_path_for(scope)
-
Devise.sign_out_all_scopes ? sign_out : sign_out(scope)
-
redirect_to redirect_path
-
end
-
-
# Overwrite Rails' handle unverified request to sign out all scopes,
-
# clear run strategies and remove cached variables.
-
1
def handle_unverified_request
-
super # call the default behaviour which resets/nullifies/raises
-
request.env["devise.skip_storage"] = true
-
sign_out_all_scopes(false)
-
end
-
-
1
def request_format
-
@request_format ||= request.format.try(:ref)
-
end
-
-
1
def is_navigational_format?
-
Devise.navigational_formats.include?(request_format)
-
end
-
-
# Check if flash messages should be emitted. Default is to do it on
-
# navigational formats
-
1
def is_flashing_format?
-
is_navigational_format?
-
end
-
-
1
private
-
-
1
def expire_session_data_after_sign_in!
-
ActiveSupport::Deprecation.warn "expire_session_data_after_sign_in! is deprecated " \
-
"in favor of expire_data_after_sign_in!"
-
expire_data_after_sign_in!
-
end
-
-
1
def expire_data_after_sign_out!
-
Devise.mappings.each { |_,m| instance_variable_set("@current_#{m.name}", nil) }
-
super
-
end
-
end
-
end
-
end
-
1
module Devise
-
1
module Controllers
-
# Provide sign in and sign out functionality.
-
# Included by default in all controllers.
-
1
module SignInOut
-
# Return true if the given scope is signed in session. If no scope given, return
-
# true if any scope is signed in. Does not run authentication hooks.
-
1
def signed_in?(scope=nil)
-
[ scope || Devise.mappings.keys ].flatten.any? do |_scope|
-
warden.authenticate?(scope: _scope)
-
end
-
end
-
-
# Sign in a user that already was authenticated. This helper is useful for logging
-
# users in after sign up.
-
#
-
# All options given to sign_in is passed forward to the set_user method in warden.
-
# The only exception is the :bypass option, which bypass warden callbacks and stores
-
# the user straight in session. This option is useful in cases the user is already
-
# signed in, but we want to refresh the credentials in session.
-
#
-
# Examples:
-
#
-
# sign_in :user, @user # sign_in(scope, resource)
-
# sign_in @user # sign_in(resource)
-
# sign_in @user, event: :authentication # sign_in(resource, options)
-
# sign_in @user, store: false # sign_in(resource, options)
-
# sign_in @user, bypass: true # sign_in(resource, options)
-
#
-
1
def sign_in(resource_or_scope, *args)
-
options = args.extract_options!
-
scope = Devise::Mapping.find_scope!(resource_or_scope)
-
resource = args.last || resource_or_scope
-
-
expire_data_after_sign_in!
-
-
if options[:bypass]
-
warden.session_serializer.store(resource, scope)
-
elsif warden.user(scope) == resource && !options.delete(:force)
-
# Do nothing. User already signed in and we are not forcing it.
-
true
-
else
-
warden.set_user(resource, options.merge!(scope: scope))
-
end
-
end
-
-
# Sign out a given user or scope. This helper is useful for signing out a user
-
# after deleting accounts. Returns true if there was a logout and false if there
-
# is no user logged in on the referred scope
-
#
-
# Examples:
-
#
-
# sign_out :user # sign_out(scope)
-
# sign_out @user # sign_out(resource)
-
#
-
1
def sign_out(resource_or_scope=nil)
-
return sign_out_all_scopes unless resource_or_scope
-
scope = Devise::Mapping.find_scope!(resource_or_scope)
-
user = warden.user(scope: scope, run_callbacks: false) # If there is no user
-
-
warden.raw_session.inspect # Without this inspect here. The session does not clear.
-
warden.logout(scope)
-
warden.clear_strategies_cache!(scope: scope)
-
instance_variable_set(:"@current_#{scope}", nil)
-
-
!!user
-
end
-
-
# Sign out all active users or scopes. This helper is useful for signing out all roles
-
# in one click. This signs out ALL scopes in warden. Returns true if there was at least one logout
-
# and false if there was no user logged in on all scopes.
-
1
def sign_out_all_scopes(lock=true)
-
users = Devise.mappings.keys.map { |s| warden.user(scope: s, run_callbacks: false) }
-
-
warden.logout
-
expire_data_after_sign_out!
-
warden.clear_strategies_cache!
-
warden.lock! if lock
-
-
users.any?
-
end
-
-
1
private
-
-
1
def expire_data_after_sign_in!
-
# session.keys will return an empty array if the session is not yet loaded.
-
# This is a bug in both Rack and Rails.
-
# A call to #empty? forces the session to be loaded.
-
session.empty?
-
session.keys.grep(/^devise\./).each { |k| session.delete(k) }
-
end
-
-
1
def expire_data_after_sign_out!
-
# session.keys will return an empty array if the session is not yet loaded.
-
# This is a bug in both Rack and Rails.
-
# A call to #empty? forces the session to be loaded.
-
session.empty?
-
session.keys.grep(/^devise\./).each { |k| session.delete(k) }
-
end
-
end
-
end
-
end
-
1
require "uri"
-
-
1
module Devise
-
1
module Controllers
-
# Provide the ability to store a location.
-
# Used to redirect back to a desired path after sign in.
-
# Included by default in all controllers.
-
1
module StoreLocation
-
# Returns and delete (if it's navigational format) the url stored in the session for
-
# the given scope. Useful for giving redirect backs after sign up:
-
#
-
# Example:
-
#
-
# redirect_to stored_location_for(:user) || root_path
-
#
-
1
def stored_location_for(resource_or_scope)
-
session_key = stored_location_key_for(resource_or_scope)
-
-
if is_navigational_format?
-
session.delete(session_key)
-
else
-
session[session_key]
-
end
-
end
-
-
# Stores the provided location to redirect the user after signing in.
-
# Useful in combination with the `stored_location_for` helper.
-
#
-
# Example:
-
#
-
# store_location_for(:user, dashboard_path)
-
# redirect_to user_omniauth_authorize_path(:facebook)
-
#
-
1
def store_location_for(resource_or_scope, location)
-
session_key = stored_location_key_for(resource_or_scope)
-
uri = parse_uri(location)
-
if uri
-
session[session_key] = [uri.path.sub(/\A\/+/, '/'), uri.query].compact.join('?')
-
end
-
end
-
-
1
private
-
-
1
def parse_uri(location)
-
location && URI.parse(location)
-
rescue URI::InvalidURIError
-
nil
-
end
-
-
1
def stored_location_key_for(resource_or_scope)
-
scope = Devise::Mapping.find_scope!(resource_or_scope)
-
"#{scope}_return_to"
-
end
-
end
-
end
-
end
-
1
module Devise
-
1
module Controllers
-
# Create url helpers to be used with resource/scope configuration. Acts as
-
# proxies to the generated routes created by devise.
-
# Resource param can be a string or symbol, a class, or an instance object.
-
# Example using a :user resource:
-
#
-
# new_session_path(:user) => new_user_session_path
-
# session_path(:user) => user_session_path
-
# destroy_session_path(:user) => destroy_user_session_path
-
#
-
# new_password_path(:user) => new_user_password_path
-
# password_path(:user) => user_password_path
-
# edit_password_path(:user) => edit_user_password_path
-
#
-
# new_confirmation_path(:user) => new_user_confirmation_path
-
# confirmation_path(:user) => user_confirmation_path
-
#
-
# Those helpers are included by default to ActionController::Base.
-
#
-
# In case you want to add such helpers to another class, you can do
-
# that as long as this new class includes both url_helpers and
-
# mounted_helpers. Example:
-
#
-
# include Rails.application.routes.url_helpers
-
# include Rails.application.routes.mounted_helpers
-
#
-
1
module UrlHelpers
-
1
def self.remove_helpers!
-
2
self.instance_methods.map(&:to_s).grep(/_(url|path)$/).each do |method|
-
48
remove_method method
-
end
-
end
-
-
1
def self.generate_helpers!(routes=nil)
-
routes ||= begin
-
2
mappings = Devise.mappings.values.map(&:used_helpers).flatten.uniq
-
2
Devise::URL_HELPERS.slice(*mappings)
-
3
end
-
-
3
routes.each do |module_name, actions|
-
12
[:path, :url].each do |path_or_url|
-
24
actions.each do |action|
-
68
action = action ? "#{action}_" : ""
-
68
method = "#{action}#{module_name}_#{path_or_url}"
-
-
68
class_eval <<-URL_HELPERS, __FILE__, __LINE__ + 1
-
def #{method}(resource_or_scope, *args)
-
scope = Devise::Mapping.find_scope!(resource_or_scope)
-
router_name = Devise.mappings[scope].router_name
-
context = router_name ? send(router_name) : _devise_route_context
-
context.send("#{action}\#{scope}_#{module_name}_#{path_or_url}", *args)
-
end
-
URL_HELPERS
-
end
-
end
-
end
-
end
-
-
1
generate_helpers!(Devise::URL_HELPERS)
-
-
1
private
-
-
1
def _devise_route_context
-
@_devise_route_context ||= send(Devise.available_router_name)
-
end
-
end
-
end
-
end
-
1
module Devise
-
# Checks the scope in the given environment and returns the associated failure app.
-
1
class Delegator
-
1
def call(env)
-
failure_app(env).call(env)
-
end
-
-
1
def failure_app(env)
-
app = env["warden.options"] &&
-
(scope = env["warden.options"][:scope]) &&
-
Devise.mappings[scope.to_sym].failure_app
-
-
app || Devise::FailureApp
-
end
-
end
-
end
-
1
require "action_controller/metal"
-
-
1
module Devise
-
# Failure application that will be called every time :warden is thrown from
-
# any strategy or hook. Responsible for redirect the user to the sign in
-
# page based on current scope and mapping. If no scope is given, redirect
-
# to the default_url.
-
1
class FailureApp < ActionController::Metal
-
1
include ActionController::RackDelegation
-
1
include ActionController::UrlFor
-
1
include ActionController::Redirecting
-
-
1
include Rails.application.routes.url_helpers
-
1
include Rails.application.routes.mounted_helpers
-
-
1
include Devise::Controllers::StoreLocation
-
-
1
delegate :flash, to: :request
-
-
1
def self.call(env)
-
@respond ||= action(:respond)
-
@respond.call(env)
-
end
-
-
1
def self.default_url_options(*args)
-
if defined?(ApplicationController)
-
ApplicationController.default_url_options(*args)
-
else
-
{}
-
end
-
end
-
-
1
def respond
-
if http_auth?
-
http_auth
-
elsif warden_options[:recall]
-
recall
-
else
-
redirect
-
end
-
end
-
-
1
def http_auth
-
self.status = 401
-
self.headers["WWW-Authenticate"] = %(Basic realm=#{Devise.http_authentication_realm.inspect}) if http_auth_header?
-
self.content_type = request.format.to_s
-
self.response_body = http_auth_body
-
end
-
-
1
def recall
-
env["PATH_INFO"] = attempted_path
-
flash.now[:alert] = i18n_message(:invalid)
-
self.response = recall_app(warden_options[:recall]).call(env)
-
end
-
-
1
def redirect
-
store_location!
-
if flash[:timedout] && flash[:alert]
-
flash.keep(:timedout)
-
flash.keep(:alert)
-
else
-
flash[:alert] = i18n_message
-
end
-
redirect_to redirect_url
-
end
-
-
1
protected
-
-
1
def i18n_options(options)
-
options
-
end
-
-
1
def i18n_message(default = nil)
-
message = warden_message || default || :unauthenticated
-
-
if message.is_a?(Symbol)
-
options = {}
-
options[:resource_name] = scope
-
options[:scope] = "devise.failure"
-
options[:default] = [message]
-
options = i18n_options(options)
-
-
I18n.t(:"#{scope}.#{message}", options)
-
else
-
message.to_s
-
end
-
end
-
-
1
def redirect_url
-
if warden_message == :timeout
-
flash[:timedout] = true
-
-
path = if request.get?
-
attempted_path
-
else
-
request.referrer
-
end
-
-
path || scope_url
-
else
-
scope_url
-
end
-
end
-
-
1
def scope_url
-
opts = {}
-
route = :"new_#{scope}_session_url"
-
opts[:format] = request_format unless skip_format?
-
-
config = Rails.application.config
-
opts[:script_name] = (config.relative_url_root if config.respond_to?(:relative_url_root))
-
-
context = send(Devise.available_router_name)
-
-
if context.respond_to?(route)
-
context.send(route, opts)
-
elsif respond_to?(:root_url)
-
root_url(opts)
-
else
-
"/"
-
end
-
end
-
-
1
def skip_format?
-
%w(html */*).include? request_format.to_s
-
end
-
-
# Choose whether we should respond in a http authentication fashion,
-
# including 401 and optional headers.
-
#
-
# This method allows the user to explicitly disable http authentication
-
# on ajax requests in case they want to redirect on failures instead of
-
# handling the errors on their own. This is useful in case your ajax API
-
# is the same as your public API and uses a format like JSON (so you
-
# cannot mark JSON as a navigational format).
-
1
def http_auth?
-
if request.xhr?
-
Devise.http_authenticatable_on_xhr
-
else
-
!(request_format && is_navigational_format?)
-
end
-
end
-
-
# It does not make sense to send authenticate headers in ajax requests
-
# or if the user disabled them.
-
1
def http_auth_header?
-
Devise.mappings[scope].to.http_authenticatable && !request.xhr?
-
end
-
-
1
def http_auth_body
-
return i18n_message unless request_format
-
method = "to_#{request_format}"
-
if method == "to_xml"
-
{ error: i18n_message }.to_xml(root: "errors")
-
elsif {}.respond_to?(method)
-
{ error: i18n_message }.send(method)
-
else
-
i18n_message
-
end
-
end
-
-
1
def recall_app(app)
-
controller, action = app.split("#")
-
controller_name = ActiveSupport::Inflector.camelize(controller)
-
controller_klass = ActiveSupport::Inflector.constantize("#{controller_name}Controller")
-
controller_klass.action(action)
-
end
-
-
1
def warden
-
env['warden']
-
end
-
-
1
def warden_options
-
env['warden.options']
-
end
-
-
1
def warden_message
-
@message ||= warden.message || warden_options[:message]
-
end
-
-
1
def scope
-
@scope ||= warden_options[:scope] || Devise.default_scope
-
end
-
-
1
def attempted_path
-
warden_options[:attempted_path]
-
end
-
-
# Stores requested uri to redirect the user after signing in. We cannot use
-
# scoped session provided by warden here, since the user is not authenticated
-
# yet, but we still need to store the uri based on scope, so different scopes
-
# would never use the same uri to redirect.
-
1
def store_location!
-
store_location_for(scope, attempted_path) if request.get? && !http_auth?
-
end
-
-
1
def is_navigational_format?
-
Devise.navigational_formats.include?(request_format)
-
end
-
-
1
def request_format
-
@request_format ||= request.format.try(:ref)
-
end
-
end
-
end
-
# Deny user access whenever their account is not active yet.
-
# We need this as hook to validate the user activity on each request
-
# and in case the user is using other strategies beside Devise ones.
-
1
Warden::Manager.after_set_user do |record, warden, options|
-
if record && record.respond_to?(:active_for_authentication?) && !record.active_for_authentication?
-
scope = options[:scope]
-
warden.logout(scope)
-
throw :warden, scope: scope, message: record.inactive_message
-
end
-
end
-
1
Warden::Manager.after_authentication do |record, warden, options|
-
clean_up_for_winning_strategy = !warden.winning_strategy.respond_to?(:clean_up_csrf?) ||
-
warden.winning_strategy.clean_up_csrf?
-
if Devise.clean_up_csrf_token_on_authentication && clean_up_for_winning_strategy
-
warden.request.session.try(:delete, :_csrf_token)
-
end
-
end
-
# Before logout hook to forget the user in the given scope, if it responds
-
# to forget_me! Also clear remember token to ensure the user won't be
-
# remembered again. Notice that we forget the user unless the record is not persisted.
-
# This avoids forgetting deleted users.
-
1
Warden::Manager.before_logout do |record, warden, options|
-
if record.respond_to?(:forget_me!)
-
Devise::Hooks::Proxy.new(warden).forget_me(record)
-
end
-
end
-
1
Warden::Manager.after_set_user except: :fetch do |record, warden, options|
-
scope = options[:scope]
-
if record.respond_to?(:remember_me) && options[:store] != false &&
-
record.remember_me && warden.authenticated?(scope)
-
Devise::Hooks::Proxy.new(warden).remember_me(record)
-
end
-
end
-
# After each sign in, update sign in time, sign in count and sign in IP.
-
# This is only triggered when the user is explicitly set (with set_user)
-
# and on authentication. Retrieving the user from session (:fetch) does
-
# not trigger it.
-
1
Warden::Manager.after_set_user except: :fetch do |record, warden, options|
-
if record.respond_to?(:update_tracked_fields!) && warden.authenticated?(options[:scope]) && !warden.request.env['devise.skip_trackable']
-
record.update_tracked_fields!(warden.request)
-
end
-
end
-
1
module Devise
-
# Responsible for handling devise mappings and routes configuration. Each
-
# resource configured by devise_for in routes is actually creating a mapping
-
# object. You can refer to devise_for in routes for usage options.
-
#
-
# The required value in devise_for is actually not used internally, but it's
-
# inflected to find all other values.
-
#
-
# map.devise_for :users
-
# mapping = Devise.mappings[:user]
-
#
-
# mapping.name #=> :user
-
# # is the scope used in controllers and warden, given in the route as :singular.
-
#
-
# mapping.as #=> "users"
-
# # how the mapping should be search in the path, given in the route as :as.
-
#
-
# mapping.to #=> User
-
# # is the class to be loaded from routes, given in the route as :class_name.
-
#
-
# mapping.modules #=> [:authenticatable]
-
# # is the modules included in the class
-
#
-
1
class Mapping #:nodoc:
-
1
attr_reader :singular, :scoped_path, :path, :controllers, :path_names,
-
:class_name, :sign_out_via, :format, :used_routes, :used_helpers,
-
:failure_app, :router_name
-
-
1
alias :name :singular
-
-
# Receives an object and find a scope for it. If a scope cannot be found,
-
# raises an error. If a symbol is given, it's considered to be the scope.
-
1
def self.find_scope!(obj)
-
case obj
-
when String, Symbol
-
return obj
-
when Class
-
Devise.mappings.each_value { |m| return m.name if obj <= m.to }
-
else
-
Devise.mappings.each_value { |m| return m.name if obj.is_a?(m.to) }
-
end
-
-
raise "Could not find a valid mapping for #{obj.inspect}"
-
end
-
-
1
def self.find_by_path!(path, path_type=:fullpath)
-
Devise.mappings.each_value { |m| return m if path.include?(m.send(path_type)) }
-
raise "Could not find a valid mapping for path #{path.inspect}"
-
end
-
-
1
def initialize(name, options) #:nodoc:
-
1
@scoped_path = options[:as] ? "#{options[:as]}/#{name}" : name.to_s
-
1
@singular = (options[:singular] || @scoped_path.tr('/', '_').singularize).to_sym
-
-
1
@class_name = (options[:class_name] || name.to_s.classify).to_s
-
1
@klass = Devise.ref(@class_name)
-
-
1
@path = (options[:path] || name).to_s
-
1
@path_prefix = options[:path_prefix]
-
-
1
@sign_out_via = options[:sign_out_via] || Devise.sign_out_via
-
1
@format = options[:format]
-
-
1
@router_name = options[:router_name]
-
-
1
default_failure_app(options)
-
1
default_controllers(options)
-
1
default_path_names(options)
-
1
default_used_route(options)
-
1
default_used_helpers(options)
-
end
-
-
# Return modules for the mapping.
-
1
def modules
-
2
@modules ||= to.respond_to?(:devise_modules) ? to.devise_modules : []
-
end
-
-
# Gives the class the mapping points to.
-
1
def to
-
3
@klass.get
-
end
-
-
1
def strategies
-
1
@strategies ||= STRATEGIES.values_at(*self.modules).compact.uniq.reverse
-
end
-
-
1
def no_input_strategies
-
self.strategies & Devise::NO_INPUT
-
end
-
-
1
def routes
-
2
@routes ||= ROUTES.values_at(*self.modules).compact.uniq
-
end
-
-
1
def authenticatable?
-
@authenticatable ||= self.modules.any? { |m| m.to_s =~ /authenticatable/ }
-
end
-
-
1
def fullpath
-
1
"/#{@path_prefix}/#{@path}".squeeze("/")
-
end
-
-
# Create magic predicates for verifying what module is activated by this map.
-
# Example:
-
#
-
# def confirmable?
-
# self.modules.include?(:confirmable)
-
# end
-
#
-
1
def self.add_module(m)
-
10
class_eval <<-METHOD, __FILE__, __LINE__ + 1
-
def #{m}?
-
self.modules.include?(:#{m})
-
end
-
METHOD
-
end
-
-
1
private
-
-
1
def default_failure_app(options)
-
1
@failure_app = options[:failure_app] || Devise::FailureApp
-
1
if @failure_app.is_a?(String)
-
ref = Devise.ref(@failure_app)
-
@failure_app = lambda { |env| ref.get.call(env) }
-
end
-
end
-
-
1
def default_controllers(options)
-
1
mod = options[:module] || "devise"
-
3
@controllers = Hash.new { |h,k| h[k] = "#{mod}/#{k}" }
-
1
@controllers.merge!(options[:controllers]) if options[:controllers]
-
2
@controllers.each { |k,v| @controllers[k] = v.to_s }
-
end
-
-
1
def default_path_names(options)
-
6
@path_names = Hash.new { |h,k| h[k] = k.to_s }
-
1
@path_names[:registration] = ""
-
1
@path_names.merge!(options[:path_names]) if options[:path_names]
-
end
-
-
1
def default_constraints(options)
-
@constraints = Hash.new
-
@constraints.merge!(options[:constraints]) if options[:constraints]
-
end
-
-
1
def default_defaults(options)
-
@defaults = Hash.new
-
@defaults.merge!(options[:defaults]) if options[:defaults]
-
end
-
-
1
def default_used_route(options)
-
1
singularizer = lambda { |s| s.to_s.singularize.to_sym }
-
-
1
if options.has_key?(:only)
-
@used_routes = self.routes & Array(options[:only]).map(&singularizer)
-
1
elsif options[:skip] == :all
-
@used_routes = []
-
else
-
1
@used_routes = self.routes - Array(options[:skip]).map(&singularizer)
-
end
-
end
-
-
1
def default_used_helpers(options)
-
1
singularizer = lambda { |s| s.to_s.singularize.to_sym }
-
-
1
if options[:skip_helpers] == true
-
@used_helpers = @used_routes
-
1
elsif skip = options[:skip_helpers]
-
@used_helpers = self.routes - Array(skip).map(&singularizer)
-
else
-
1
@used_helpers = self.routes
-
end
-
end
-
end
-
end
-
1
module Devise
-
1
module Models
-
1
class MissingAttribute < StandardError
-
1
def initialize(attributes)
-
@attributes = attributes
-
end
-
-
1
def message
-
"The following attribute(s) is (are) missing on your model: #{@attributes.join(", ")}"
-
end
-
end
-
-
# Creates configuration values for Devise and for the given module.
-
#
-
# Devise::Models.config(Devise::Authenticatable, :stretches, 10)
-
#
-
# The line above creates:
-
#
-
# 1) An accessor called Devise.stretches, which value is used by default;
-
#
-
# 2) Some class methods for your model Model.stretches and Model.stretches=
-
# which have higher priority than Devise.stretches;
-
#
-
# 3) And an instance method stretches.
-
#
-
# To add the class methods you need to have a module ClassMethods defined
-
# inside the given class.
-
#
-
1
def self.config(mod, *accessors) #:nodoc:
-
10
class << mod; attr_accessor :available_configs; end
-
5
mod.available_configs = accessors
-
-
5
accessors.each do |accessor|
-
18
mod.class_eval <<-METHOD, __FILE__, __LINE__ + 1
-
def #{accessor}
-
if defined?(@#{accessor})
-
@#{accessor}
-
elsif superclass.respond_to?(:#{accessor})
-
superclass.#{accessor}
-
else
-
Devise.#{accessor}
-
end
-
end
-
-
def #{accessor}=(value)
-
@#{accessor} = value
-
end
-
METHOD
-
end
-
end
-
-
1
def self.check_fields!(klass)
-
failed_attributes = []
-
instance = klass.new
-
-
klass.devise_modules.each do |mod|
-
constant = const_get(mod.to_s.classify)
-
-
constant.required_fields(klass).each do |field|
-
failed_attributes << field unless instance.respond_to?(field)
-
end
-
end
-
-
if failed_attributes.any?
-
fail Devise::Models::MissingAttribute.new(failed_attributes)
-
end
-
end
-
-
# Include the chosen devise modules in your model:
-
#
-
# devise :database_authenticatable, :confirmable, :recoverable
-
#
-
# You can also give any of the devise configuration values in form of a hash,
-
# with specific values for this model. Please check your Devise initializer
-
# for a complete description on those values.
-
#
-
1
def devise(*modules)
-
1
options = modules.extract_options!.dup
-
-
1
selected_modules = modules.map(&:to_sym).uniq.sort_by do |s|
-
6
Devise::ALL.index(s) || -1 # follow Devise::ALL order
-
end
-
-
1
devise_modules_hook! do
-
1
include Devise::Models::Authenticatable
-
-
1
selected_modules.each do |m|
-
6
mod = Devise::Models.const_get(m.to_s.classify)
-
-
6
if mod.const_defined?("ClassMethods")
-
5
class_mod = mod.const_get("ClassMethods")
-
5
extend class_mod
-
-
5
if class_mod.respond_to?(:available_configs)
-
4
available_configs = class_mod.available_configs
-
4
available_configs.each do |config|
-
10
next unless options.key?(config)
-
send(:"#{config}=", options.delete(config))
-
end
-
end
-
end
-
-
6
include mod
-
end
-
-
1
self.devise_modules |= selected_modules
-
1
options.each { |key, value| send(:"#{key}=", value) }
-
end
-
end
-
-
# The hook which is called inside devise.
-
# So your ORM can include devise compatibility stuff.
-
1
def devise_modules_hook!
-
1
yield
-
end
-
end
-
end
-
-
1
require 'devise/models/authenticatable'
-
1
require 'devise/hooks/activatable'
-
1
require 'devise/hooks/csrf_cleaner'
-
-
1
module Devise
-
1
module Models
-
# Authenticatable module. Holds common settings for authentication.
-
#
-
# == Options
-
#
-
# Authenticatable adds the following options to devise_for:
-
#
-
# * +authentication_keys+: parameters used for authentication. By default [:email].
-
#
-
# * +http_authentication_key+: map the username passed via HTTP Auth to this parameter. Defaults to
-
# the first element in +authentication_keys+.
-
#
-
# * +request_keys+: parameters from the request object used for authentication.
-
# By specifying a symbol (which should be a request method), it will automatically be
-
# passed to find_for_authentication method and considered in your model lookup.
-
#
-
# For instance, if you set :request_keys to [:subdomain], :subdomain will be considered
-
# as key on authentication. This can also be a hash where the value is a boolean specifying
-
# if the value is required or not.
-
#
-
# * +http_authenticatable+: if this model allows http authentication. By default false.
-
# It also accepts an array specifying the strategies that should allow http.
-
#
-
# * +params_authenticatable+: if this model allows authentication through request params. By default true.
-
# It also accepts an array specifying the strategies that should allow params authentication.
-
#
-
# * +skip_session_storage+: By default Devise will store the user in session.
-
# By default is set to skip_session_storage: [:http_auth].
-
#
-
# == active_for_authentication?
-
#
-
# After authenticating a user and in each request, Devise checks if your model is active by
-
# calling model.active_for_authentication?. This method is overwritten by other devise modules. For instance,
-
# :confirmable overwrites .active_for_authentication? to only return true if your model was confirmed.
-
#
-
# You overwrite this method yourself, but if you do, don't forget to call super:
-
#
-
# def active_for_authentication?
-
# super && special_condition_is_valid?
-
# end
-
#
-
# Whenever active_for_authentication? returns false, Devise asks the reason why your model is inactive using
-
# the inactive_message method. You can overwrite it as well:
-
#
-
# def inactive_message
-
# special_condition_is_valid? ? super : :special_condition_is_not_valid
-
# end
-
#
-
1
module Authenticatable
-
1
extend ActiveSupport::Concern
-
-
1
BLACKLIST_FOR_SERIALIZATION = [:encrypted_password, :reset_password_token, :reset_password_sent_at,
-
:remember_created_at, :sign_in_count, :current_sign_in_at, :last_sign_in_at, :current_sign_in_ip,
-
:last_sign_in_ip, :password_salt, :confirmation_token, :confirmed_at, :confirmation_sent_at,
-
:remember_token, :unconfirmed_email, :failed_attempts, :unlock_token, :locked_at]
-
-
1
included do
-
1
class_attribute :devise_modules, instance_writer: false
-
1
self.devise_modules ||= []
-
-
1
before_validation :downcase_keys
-
1
before_validation :strip_whitespace
-
end
-
-
1
def self.required_fields(klass)
-
[]
-
end
-
-
# Check if the current object is valid for authentication. This method and
-
# find_for_authentication are the methods used in a Warden::Strategy to check
-
# if a model should be signed in or not.
-
#
-
# However, you should not overwrite this method, you should overwrite active_for_authentication?
-
# and inactive_message instead.
-
1
def valid_for_authentication?
-
block_given? ? yield : true
-
end
-
-
1
def unauthenticated_message
-
:invalid
-
end
-
-
1
def active_for_authentication?
-
true
-
end
-
-
1
def inactive_message
-
:inactive
-
end
-
-
1
def authenticatable_salt
-
end
-
-
1
array = %w(serializable_hash)
-
# to_xml does not call serializable_hash on 3.1
-
1
array << "to_xml" if Rails::VERSION::STRING[0,3] == "3.1"
-
-
1
array.each do |method|
-
1
class_eval <<-RUBY, __FILE__, __LINE__
-
# Redefine to_xml and serializable_hash in models for more secure defaults.
-
# By default, it removes from the serializable model all attributes that
-
# are *not* accessible. You can remove this default by using :force_except
-
# and passing a new list of attributes you want to exempt. All attributes
-
# given to :except will simply add names to exempt to Devise internal list.
-
def #{method}(options=nil)
-
options ||= {}
-
options[:except] = Array(options[:except])
-
-
if options[:force_except]
-
options[:except].concat Array(options[:force_except])
-
else
-
options[:except].concat BLACKLIST_FOR_SERIALIZATION
-
end
-
super(options)
-
end
-
RUBY
-
end
-
-
1
protected
-
-
1
def devise_mailer
-
Devise.mailer
-
end
-
-
# This is an internal method called every time Devise needs
-
# to send a notification/mail. This can be overridden if you
-
# need to customize the e-mail delivery logic. For instance,
-
# if you are using a queue to deliver e-mails (delayed job,
-
# sidekiq, resque, etc), you must add the delivery to the queue
-
# just after the transaction was committed. To achieve this,
-
# you can override send_devise_notification to store the
-
# deliveries until the after_commit callback is triggered:
-
#
-
# class User
-
# devise :database_authenticatable, :confirmable
-
#
-
# after_commit :send_pending_notifications
-
#
-
# protected
-
#
-
# def send_devise_notification(notification, *args)
-
# # If the record is new or changed then delay the
-
# # delivery until the after_commit callback otherwise
-
# # send now because after_commit will not be called.
-
# if new_record? || changed?
-
# pending_notifications << [notification, args]
-
# else
-
# devise_mailer.send(notification, self, *args).deliver
-
# end
-
# end
-
#
-
# def send_pending_notifications
-
# pending_notifications.each do |notification, args|
-
# devise_mailer.send(notification, self, *args).deliver
-
# end
-
#
-
# # Empty the pending notifications array because the
-
# # after_commit hook can be called multiple times which
-
# # could cause multiple emails to be sent.
-
# pending_notifications.clear
-
# end
-
#
-
# def pending_notifications
-
# @pending_notifications ||= []
-
# end
-
# end
-
#
-
1
def send_devise_notification(notification, *args)
-
devise_mailer.send(notification, self, *args).deliver
-
end
-
-
1
def downcase_keys
-
self.class.case_insensitive_keys.each { |k| apply_to_attribute_or_variable(k, :downcase) }
-
end
-
-
1
def strip_whitespace
-
self.class.strip_whitespace_keys.each { |k| apply_to_attribute_or_variable(k, :strip) }
-
end
-
-
1
def apply_to_attribute_or_variable(attr, method)
-
if self[attr]
-
self[attr] = self[attr].try(method)
-
-
# Use respond_to? here to avoid a regression where globally
-
# configured strip_whitespace_keys or case_insensitive_keys were
-
# attempting to strip or downcase when a model didn't have the
-
# globally configured key.
-
elsif respond_to?(attr) && respond_to?("#{attr}=")
-
new_value = send(attr).try(method)
-
send("#{attr}=", new_value)
-
end
-
end
-
-
1
module ClassMethods
-
1
Devise::Models.config(self, :authentication_keys, :request_keys, :strip_whitespace_keys,
-
:case_insensitive_keys, :http_authenticatable, :params_authenticatable, :skip_session_storage,
-
:http_authentication_key)
-
-
1
def serialize_into_session(record)
-
[record.to_key, record.authenticatable_salt]
-
end
-
-
1
def serialize_from_session(key, salt)
-
record = to_adapter.get(key)
-
record if record && record.authenticatable_salt == salt
-
end
-
-
1
def params_authenticatable?(strategy)
-
params_authenticatable.is_a?(Array) ?
-
params_authenticatable.include?(strategy) : params_authenticatable
-
end
-
-
1
def http_authenticatable?(strategy)
-
http_authenticatable.is_a?(Array) ?
-
http_authenticatable.include?(strategy) : http_authenticatable
-
end
-
-
# Find first record based on conditions given (ie by the sign in form).
-
# This method is always called during an authentication process but
-
# it may be wrapped as well. For instance, database authenticatable
-
# provides a `find_for_database_authentication` that wraps a call to
-
# this method. This allows you to customize both database authenticatable
-
# or the whole authenticate stack by customize `find_for_authentication.`
-
#
-
# Overwrite to add customized conditions, create a join, or maybe use a
-
# namedscope to filter records while authenticating.
-
# Example:
-
#
-
# def self.find_for_authentication(tainted_conditions)
-
# find_first_by_auth_conditions(tainted_conditions, active: true)
-
# end
-
#
-
# Finally, notice that Devise also queries for users in other scenarios
-
# besides authentication, for example when retrieving an user to send
-
# an e-mail for password reset. In such cases, find_for_authentication
-
# is not called.
-
1
def find_for_authentication(tainted_conditions)
-
find_first_by_auth_conditions(tainted_conditions)
-
end
-
-
1
def find_first_by_auth_conditions(tainted_conditions, opts={})
-
to_adapter.find_first(devise_parameter_filter.filter(tainted_conditions).merge(opts))
-
end
-
-
# Find an initialize a record setting an error if it can't be found.
-
1
def find_or_initialize_with_error_by(attribute, value, error=:invalid) #:nodoc:
-
find_or_initialize_with_errors([attribute], { attribute => value }, error)
-
end
-
-
# Find an initialize a group of attributes based on a list of required attributes.
-
1
def find_or_initialize_with_errors(required_attributes, attributes, error=:invalid) #:nodoc:
-
attributes = attributes.slice(*required_attributes)
-
attributes.delete_if { |key, value| value.blank? }
-
-
if attributes.size == required_attributes.size
-
record = find_first_by_auth_conditions(attributes)
-
end
-
-
unless record
-
record = new
-
-
required_attributes.each do |key|
-
value = attributes[key]
-
record.send("#{key}=", value)
-
record.errors.add(key, value.present? ? error : :blank)
-
end
-
end
-
-
record
-
end
-
-
1
protected
-
-
1
def devise_parameter_filter
-
@devise_parameter_filter ||= Devise::ParameterFilter.new(case_insensitive_keys, strip_whitespace_keys)
-
end
-
end
-
end
-
end
-
end
-
1
require 'devise/strategies/database_authenticatable'
-
1
require 'bcrypt'
-
-
1
module Devise
-
# Digests the password using bcrypt.
-
1
def self.bcrypt(klass, password)
-
::BCrypt::Password.create("#{password}#{klass.pepper}", cost: klass.stretches).to_s
-
end
-
-
1
module Models
-
# Authenticatable Module, responsible for encrypting password and validating
-
# authenticity of a user while signing in.
-
#
-
# == Options
-
#
-
# DatabaseAuthenticable adds the following options to devise_for:
-
#
-
# * +pepper+: a random string used to provide a more secure hash. Use
-
# `rake secret` to generate new keys.
-
#
-
# * +stretches+: the cost given to bcrypt.
-
#
-
# == Examples
-
#
-
# User.find(1).valid_password?('password123') # returns true/false
-
#
-
1
module DatabaseAuthenticatable
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
attr_reader :password, :current_password
-
1
attr_accessor :password_confirmation
-
end
-
-
1
def self.required_fields(klass)
-
[:encrypted_password] + klass.authentication_keys
-
end
-
-
# Generates password encryption based on the given value.
-
1
def password=(new_password)
-
@password = new_password
-
self.encrypted_password = password_digest(@password) if @password.present?
-
end
-
-
# Verifies whether an password (ie from sign in) is the user password.
-
1
def valid_password?(password)
-
return false if encrypted_password.blank?
-
bcrypt = ::BCrypt::Password.new(encrypted_password)
-
password = ::BCrypt::Engine.hash_secret("#{password}#{self.class.pepper}", bcrypt.salt)
-
Devise.secure_compare(password, encrypted_password)
-
end
-
-
# Set password and password confirmation to nil
-
1
def clean_up_passwords
-
self.password = self.password_confirmation = nil
-
end
-
-
# Update record attributes when :current_password matches, otherwise
-
# returns error on :current_password.
-
#
-
# This method also rejects the password field if it is blank (allowing
-
# users to change relevant information like the e-mail without changing
-
# their password). In case the password field is rejected, the confirmation
-
# is also rejected as long as it is also blank.
-
1
def update_with_password(params, *options)
-
current_password = params.delete(:current_password)
-
-
if params[:password].blank?
-
params.delete(:password)
-
params.delete(:password_confirmation) if params[:password_confirmation].blank?
-
end
-
-
result = if valid_password?(current_password)
-
update_attributes(params, *options)
-
else
-
self.assign_attributes(params, *options)
-
self.valid?
-
self.errors.add(:current_password, current_password.blank? ? :blank : :invalid)
-
false
-
end
-
-
clean_up_passwords
-
result
-
end
-
-
# Updates record attributes without asking for the current password.
-
# Never allows a change to the current password. If you are using this
-
# method, you should probably override this method to protect other
-
# attributes you would not like to be updated without a password.
-
#
-
# Example:
-
#
-
# def update_without_password(params, *options)
-
# params.delete(:email)
-
# super(params)
-
# end
-
#
-
1
def update_without_password(params, *options)
-
params.delete(:password)
-
params.delete(:password_confirmation)
-
-
result = update_attributes(params, *options)
-
clean_up_passwords
-
result
-
end
-
-
# Destroy record when :current_password matches, otherwise returns
-
# error on :current_password. It also automatically rejects
-
# :current_password if it is blank.
-
1
def destroy_with_password(current_password)
-
result = if valid_password?(current_password)
-
destroy
-
else
-
self.valid?
-
self.errors.add(:current_password, current_password.blank? ? :blank : :invalid)
-
false
-
end
-
-
result
-
end
-
-
# A callback initiated after successfully authenticating. This can be
-
# used to insert your own logic that is only run after the user successfully
-
# authenticates.
-
#
-
# Example:
-
#
-
# def after_database_authentication
-
# self.update_attribute(:invite_code, nil)
-
# end
-
#
-
1
def after_database_authentication
-
end
-
-
# A reliable way to expose the salt regardless of the implementation.
-
1
def authenticatable_salt
-
encrypted_password[0,29] if encrypted_password
-
end
-
-
1
protected
-
-
# Digests the password using bcrypt. Custom encryption should override
-
# this method to apply their own algorithm.
-
#
-
# See https://github.com/plataformatec/devise-encryptable for examples
-
# of other encryption engines.
-
1
def password_digest(password)
-
Devise.bcrypt(self.class, password)
-
end
-
-
1
module ClassMethods
-
1
Devise::Models.config(self, :pepper, :stretches)
-
-
# We assume this method already gets the sanitized values from the
-
# DatabaseAuthenticatable strategy. If you are using this method on
-
# your own, be sure to sanitize the conditions hash to only include
-
# the proper fields.
-
1
def find_for_database_authentication(conditions)
-
find_for_authentication(conditions)
-
end
-
end
-
end
-
end
-
end
-
1
module Devise
-
1
module Models
-
-
# Recoverable takes care of resetting the user password and send reset instructions.
-
#
-
# ==Options
-
#
-
# Recoverable adds the following options to devise_for:
-
#
-
# * +reset_password_keys+: the keys you want to use when recovering the password for an account
-
#
-
# == Examples
-
#
-
# # resets the user password and save the record, true if valid passwords are given, otherwise false
-
# User.find(1).reset_password!('password123', 'password123')
-
#
-
# # only resets the user password, without saving the record
-
# user = User.find(1)
-
# user.reset_password('password123', 'password123')
-
#
-
# # creates a new token and send it with instructions about how to reset the password
-
# User.find(1).send_reset_password_instructions
-
#
-
1
module Recoverable
-
1
extend ActiveSupport::Concern
-
-
1
def self.required_fields(klass)
-
[:reset_password_sent_at, :reset_password_token]
-
end
-
-
# Update password saving the record and clearing token. Returns true if
-
# the passwords are valid and the record was saved, false otherwise.
-
1
def reset_password!(new_password, new_password_confirmation)
-
self.password = new_password
-
self.password_confirmation = new_password_confirmation
-
-
if valid?
-
clear_reset_password_token
-
after_password_reset
-
end
-
-
save
-
end
-
-
# Resets reset password token and send reset password instructions by email.
-
# Returns the token sent in the e-mail.
-
1
def send_reset_password_instructions
-
token = set_reset_password_token
-
send_reset_password_instructions_notification(token)
-
-
token
-
end
-
-
# Checks if the reset password token sent is within the limit time.
-
# We do this by calculating if the difference between today and the
-
# sending date does not exceed the confirm in time configured.
-
# Returns true if the resource is not responding to reset_password_sent_at at all.
-
# reset_password_within is a model configuration, must always be an integer value.
-
#
-
# Example:
-
#
-
# # reset_password_within = 1.day and reset_password_sent_at = today
-
# reset_password_period_valid? # returns true
-
#
-
# # reset_password_within = 5.days and reset_password_sent_at = 4.days.ago
-
# reset_password_period_valid? # returns true
-
#
-
# # reset_password_within = 5.days and reset_password_sent_at = 5.days.ago
-
# reset_password_period_valid? # returns false
-
#
-
# # reset_password_within = 0.days
-
# reset_password_period_valid? # will always return false
-
#
-
1
def reset_password_period_valid?
-
reset_password_sent_at && reset_password_sent_at.utc >= self.class.reset_password_within.ago
-
end
-
-
1
protected
-
-
# Removes reset_password token
-
1
def clear_reset_password_token
-
self.reset_password_token = nil
-
self.reset_password_sent_at = nil
-
end
-
-
1
def after_password_reset
-
end
-
-
1
def set_reset_password_token
-
raw, enc = Devise.token_generator.generate(self.class, :reset_password_token)
-
-
self.reset_password_token = enc
-
self.reset_password_sent_at = Time.now.utc
-
self.save(validate: false)
-
raw
-
end
-
-
1
def send_reset_password_instructions_notification(token)
-
send_devise_notification(:reset_password_instructions, token, {})
-
end
-
-
1
module ClassMethods
-
# Attempt to find a user by password reset token. If a user is found, return it
-
# If a user is not found, return nil
-
1
def with_reset_password_token(token)
-
reset_password_token = Devise.token_generator.digest(self, :reset_password_token, token)
-
to_adapter.find_first(reset_password_token: reset_password_token)
-
end
-
-
# Attempt to find a user by its email. If a record is found, send new
-
# password instructions to it. If user is not found, returns a new user
-
# with an email not found error.
-
# Attributes must contain the user's email
-
1
def send_reset_password_instructions(attributes={})
-
recoverable = find_or_initialize_with_errors(reset_password_keys, attributes, :not_found)
-
recoverable.send_reset_password_instructions if recoverable.persisted?
-
recoverable
-
end
-
-
# Attempt to find a user by its reset_password_token to reset its
-
# password. If a user is found and token is still valid, reset its password and automatically
-
# try saving the record. If not user is found, returns a new user
-
# containing an error in reset_password_token attribute.
-
# Attributes must contain reset_password_token, password and confirmation
-
1
def reset_password_by_token(attributes={})
-
original_token = attributes[:reset_password_token]
-
reset_password_token = Devise.token_generator.digest(self, :reset_password_token, original_token)
-
-
recoverable = find_or_initialize_with_error_by(:reset_password_token, reset_password_token)
-
-
if recoverable.persisted?
-
if recoverable.reset_password_period_valid?
-
recoverable.reset_password!(attributes[:password], attributes[:password_confirmation])
-
else
-
recoverable.errors.add(:reset_password_token, :expired)
-
end
-
end
-
-
recoverable.reset_password_token = original_token
-
recoverable
-
end
-
-
1
Devise::Models.config(self, :reset_password_keys, :reset_password_within)
-
end
-
end
-
end
-
end
-
1
module Devise
-
1
module Models
-
# Registerable is responsible for everything related to registering a new
-
# resource (ie user sign up).
-
1
module Registerable
-
1
extend ActiveSupport::Concern
-
-
1
def self.required_fields(klass)
-
[]
-
end
-
-
1
module ClassMethods
-
# A convenience method that receives both parameters and session to
-
# initialize a user. This can be used by OAuth, for example, to send
-
# in the user token and be stored on initialization.
-
#
-
# By default discards all information sent by the session by calling
-
# new with params.
-
1
def new_with_session(params, session)
-
new(params)
-
end
-
end
-
end
-
end
-
end
-
1
require 'devise/strategies/rememberable'
-
1
require 'devise/hooks/rememberable'
-
1
require 'devise/hooks/forgetable'
-
-
1
module Devise
-
1
module Models
-
# Rememberable manages generating and clearing token for remember the user
-
# from a saved cookie. Rememberable also has utility methods for dealing
-
# with serializing the user into the cookie and back from the cookie, trying
-
# to lookup the record based on the saved information.
-
# You probably wouldn't use rememberable methods directly, they are used
-
# mostly internally for handling the remember token.
-
#
-
# == Options
-
#
-
# Rememberable adds the following options in devise_for:
-
#
-
# * +remember_for+: the time you want the user will be remembered without
-
# asking for credentials. After this time the user will be blocked and
-
# will have to enter their credentials again. This configuration is also
-
# used to calculate the expires time for the cookie created to remember
-
# the user. By default remember_for is 2.weeks.
-
#
-
# * +extend_remember_period+: if true, extends the user's remember period
-
# when remembered via cookie. False by default.
-
#
-
# * +rememberable_options+: configuration options passed to the created cookie.
-
#
-
# == Examples
-
#
-
# User.find(1).remember_me! # regenerating the token
-
# User.find(1).forget_me! # clearing the token
-
#
-
# # generating info to put into cookies
-
# User.serialize_into_cookie(user)
-
#
-
# # lookup the user based on the incoming cookie information
-
# User.serialize_from_cookie(cookie_string)
-
1
module Rememberable
-
1
extend ActiveSupport::Concern
-
-
1
attr_accessor :remember_me, :extend_remember_period
-
-
1
def self.required_fields(klass)
-
[:remember_created_at]
-
end
-
-
# Generate a new remember token and save the record without validations
-
# unless remember_across_browsers is true and the user already has a valid token.
-
1
def remember_me!(extend_period=false)
-
self.remember_token = self.class.remember_token if generate_remember_token?
-
self.remember_created_at = Time.now.utc if generate_remember_timestamp?(extend_period)
-
save(validate: false) if self.changed?
-
end
-
-
# If the record is persisted, remove the remember token (but only if
-
# it exists), and save the record without validations.
-
1
def forget_me!
-
return unless persisted?
-
self.remember_token = nil if respond_to?(:remember_token=)
-
self.remember_created_at = nil if self.class.expire_all_remember_me_on_sign_out
-
save(validate: false)
-
end
-
-
# Remember token should be expired if expiration time not overpass now.
-
1
def remember_expired?
-
remember_created_at.nil? || (remember_expires_at <= Time.now.utc)
-
end
-
-
# Remember token expires at created time + remember_for configuration
-
1
def remember_expires_at
-
remember_created_at + self.class.remember_for
-
end
-
-
1
def rememberable_value
-
if respond_to?(:remember_token)
-
remember_token
-
elsif respond_to?(:authenticatable_salt) && (salt = authenticatable_salt)
-
salt
-
else
-
raise "authenticable_salt returned nil for the #{self.class.name} model. " \
-
"In order to use rememberable, you must ensure a password is always set " \
-
"or have a remember_token column in your model or implement your own " \
-
"rememberable_value in the model with custom logic."
-
end
-
end
-
-
1
def rememberable_options
-
self.class.rememberable_options
-
end
-
-
1
protected
-
-
1
def generate_remember_token? #:nodoc:
-
respond_to?(:remember_token) && remember_expired?
-
end
-
-
# Generate a timestamp if extend_remember_period is true, if no remember_token
-
# exists, or if an existing remember token has expired.
-
1
def generate_remember_timestamp?(extend_period) #:nodoc:
-
extend_period || remember_created_at.nil? || remember_expired?
-
end
-
-
1
module ClassMethods
-
# Create the cookie key using the record id and remember_token
-
1
def serialize_into_cookie(record)
-
[record.to_key, record.rememberable_value]
-
end
-
-
# Recreate the user based on the stored cookie
-
1
def serialize_from_cookie(id, remember_token)
-
record = to_adapter.get(id)
-
record if record && !record.remember_expired? &&
-
Devise.secure_compare(record.rememberable_value, remember_token)
-
end
-
-
# Generate a token checking if one does not already exist in the database.
-
1
def remember_token #:nodoc:
-
loop do
-
token = Devise.friendly_token
-
break token unless to_adapter.find_first({ remember_token: token })
-
end
-
end
-
-
1
Devise::Models.config(self, :remember_for, :extend_remember_period, :rememberable_options, :expire_all_remember_me_on_sign_out)
-
end
-
end
-
end
-
end
-
1
require 'devise/hooks/trackable'
-
-
1
module Devise
-
1
module Models
-
# Track information about your user sign in. It tracks the following columns:
-
#
-
# * sign_in_count - Increased every time a sign in is made (by form, openid, oauth)
-
# * current_sign_in_at - A timestamp updated when the user signs in
-
# * last_sign_in_at - Holds the timestamp of the previous sign in
-
# * current_sign_in_ip - The remote ip updated when the user sign in
-
# * last_sign_in_ip - Holds the remote ip of the previous sign in
-
#
-
1
module Trackable
-
1
def self.required_fields(klass)
-
[:current_sign_in_at, :current_sign_in_ip, :last_sign_in_at, :last_sign_in_ip, :sign_in_count]
-
end
-
-
1
def update_tracked_fields(request)
-
old_current, new_current = self.current_sign_in_at, Time.now.utc
-
self.last_sign_in_at = old_current || new_current
-
self.current_sign_in_at = new_current
-
-
old_current, new_current = self.current_sign_in_ip, request.remote_ip
-
self.last_sign_in_ip = old_current || new_current
-
self.current_sign_in_ip = new_current
-
-
self.sign_in_count ||= 0
-
self.sign_in_count += 1
-
end
-
-
1
def update_tracked_fields!(request)
-
update_tracked_fields(request)
-
save(validate: false) or raise "Devise trackable could not save #{inspect}." \
-
"Please make sure a model using trackable can be saved at sign in."
-
end
-
end
-
end
-
end
-
1
module Devise
-
1
module Models
-
# Validatable creates all needed validations for a user email and password.
-
# It's optional, given you may want to create the validations by yourself.
-
# Automatically validate if the email is present, unique and its format is
-
# valid. Also tests presence of password, confirmation and length.
-
#
-
# == Options
-
#
-
# Validatable adds the following options to devise_for:
-
#
-
# * +email_regexp+: the regular expression used to validate e-mails;
-
# * +password_length+: a range expressing password length. Defaults to 8..128.
-
#
-
1
module Validatable
-
# All validations used by this module.
-
1
VALIDATIONS = [ :validates_presence_of, :validates_uniqueness_of, :validates_format_of,
-
:validates_confirmation_of, :validates_length_of ].freeze
-
-
1
def self.required_fields(klass)
-
[]
-
end
-
-
1
def self.included(base)
-
1
base.extend ClassMethods
-
1
assert_validations_api!(base)
-
-
1
base.class_eval do
-
1
validates_presence_of :email, if: :email_required?
-
1
validates_uniqueness_of :email, allow_blank: true, if: :email_changed?
-
1
validates_format_of :email, with: email_regexp, allow_blank: true, if: :email_changed?
-
-
1
validates_presence_of :password, if: :password_required?
-
1
validates_confirmation_of :password, if: :password_required?
-
1
validates_length_of :password, within: password_length, allow_blank: true
-
end
-
end
-
-
1
def self.assert_validations_api!(base) #:nodoc:
-
6
unavailable_validations = VALIDATIONS.select { |v| !base.respond_to?(v) }
-
-
1
unless unavailable_validations.empty?
-
raise "Could not use :validatable module since #{base} does not respond " <<
-
"to the following methods: #{unavailable_validations.to_sentence}."
-
end
-
end
-
-
1
protected
-
-
# Checks whether a password is needed or not. For validations only.
-
# Passwords are always required if it's a new record, or if the password
-
# or confirmation are being set somewhere.
-
1
def password_required?
-
!persisted? || !password.nil? || !password_confirmation.nil?
-
end
-
-
1
def email_required?
-
true
-
end
-
-
1
module ClassMethods
-
1
Devise::Models.config(self, :email_regexp, :password_length)
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/object/with_options'
-
-
1
Devise.with_options model: true do |d|
-
# Strategies first
-
1
d.with_options strategy: true do |s|
-
1
routes = [nil, :new, :destroy]
-
1
s.add_module :database_authenticatable, controller: :sessions, route: { session: routes }
-
1
s.add_module :rememberable, no_input: true
-
end
-
-
# Other authentications
-
1
d.add_module :omniauthable, controller: :omniauth_callbacks, route: :omniauth_callback
-
-
# Misc after
-
1
routes = [nil, :new, :edit]
-
1
d.add_module :recoverable, controller: :passwords, route: { password: routes }
-
1
d.add_module :registerable, controller: :registrations, route: { registration: (routes << :cancel) }
-
1
d.add_module :validatable
-
-
# The ones which can sign out after
-
1
routes = [nil, :new]
-
1
d.add_module :confirmable, controller: :confirmations, route: { confirmation: routes }
-
1
d.add_module :lockable, controller: :unlocks, route: { unlock: routes }
-
1
d.add_module :timeoutable
-
-
# Stats for last, so we make sure the user is really signed in
-
1
d.add_module :trackable
-
end
-
1
require 'orm_adapter/adapters/active_record'
-
-
1
ActiveRecord::Base.extend Devise::Models
-
1
require 'devise/rails/routes'
-
1
require 'devise/rails/warden_compat'
-
-
1
module Devise
-
1
class Engine < ::Rails::Engine
-
1
config.devise = Devise
-
-
# Initialize Warden and copy its configurations.
-
1
config.app_middleware.use Warden::Manager do |config|
-
1
Devise.warden_config = config
-
end
-
-
# Force routes to be loaded if we are doing any eager load.
-
1
config.before_eager_load { |app| app.reload_routes! }
-
-
1
initializer "devise.url_helpers" do
-
1
Devise.include_helpers(Devise::Controllers)
-
end
-
-
1
initializer "devise.omniauth" do |app|
-
1
Devise.omniauth_configs.each do |provider, config|
-
app.middleware.use config.strategy_class, *config.args do |strategy|
-
config.strategy = strategy
-
end
-
end
-
-
1
if Devise.omniauth_configs.any?
-
Devise.include_helpers(Devise::OmniAuth)
-
end
-
end
-
-
1
initializer "devise.secret_key" do |app|
-
1
if app.respond_to?(:secrets)
-
1
Devise.secret_key ||= app.secrets.secret_key_base
-
elsif app.config.respond_to?(:secret_key_base)
-
Devise.secret_key ||= app.config.secret_key_base
-
end
-
-
1
Devise.token_generator ||=
-
if secret_key = Devise.secret_key
-
1
Devise::TokenGenerator.new(
-
Devise::CachingKeyGenerator.new(Devise::KeyGenerator.new(secret_key))
-
)
-
end
-
end
-
-
1
initializer "devise.fix_routes_proxy_missing_respond_to_bug" do
-
# Deprecate: Remove once we move to Rails 4 only.
-
1
ActionDispatch::Routing::RoutesProxy.class_eval do
-
1
def respond_to?(method, include_private = false)
-
super || routes.url_helpers.respond_to?(method)
-
end
-
end
-
end
-
end
-
end
-
1
require "active_support/core_ext/object/try"
-
1
require "active_support/core_ext/hash/slice"
-
-
1
module ActionDispatch::Routing
-
1
class RouteSet #:nodoc:
-
# Ensure Devise modules are included only after loading routes, because we
-
# need devise_for mappings already declared to create filters and helpers.
-
1
def finalize_with_devise!
-
2
result = finalize_without_devise!
-
-
@devise_finalized ||= begin
-
2
if Devise.router_name.nil? && defined?(@devise_finalized) && self != Rails.application.try(:routes)
-
warn "[DEVISE] We have detected that you are using devise_for inside engine routes. " \
-
"In this case, you probably want to set Devise.router_name = MOUNT_POINT, where " \
-
"MOUNT_POINT is a symbol representing where this engine will be mounted at. For " \
-
"now Devise will default the mount point to :main_app. You can explicitly set it" \
-
" to :main_app as well in case you want to keep the current behavior."
-
end
-
-
2
Devise.configure_warden!
-
2
Devise.regenerate_helpers!
-
2
true
-
2
end
-
-
2
result
-
end
-
1
alias_method_chain :finalize!, :devise
-
end
-
-
1
class Mapper
-
# Includes devise_for method for routes. This method is responsible to
-
# generate all needed routes for devise, based on what modules you have
-
# defined in your model.
-
#
-
# ==== Examples
-
#
-
# Let's say you have an User model configured to use authenticatable,
-
# confirmable and recoverable modules. After creating this inside your routes:
-
#
-
# devise_for :users
-
#
-
# This method is going to look inside your User model and create the
-
# needed routes:
-
#
-
# # Session routes for Authenticatable (default)
-
# new_user_session GET /users/sign_in {controller:"devise/sessions", action:"new"}
-
# user_session POST /users/sign_in {controller:"devise/sessions", action:"create"}
-
# destroy_user_session DELETE /users/sign_out {controller:"devise/sessions", action:"destroy"}
-
#
-
# # Password routes for Recoverable, if User model has :recoverable configured
-
# new_user_password GET /users/password/new(.:format) {controller:"devise/passwords", action:"new"}
-
# edit_user_password GET /users/password/edit(.:format) {controller:"devise/passwords", action:"edit"}
-
# user_password PUT /users/password(.:format) {controller:"devise/passwords", action:"update"}
-
# POST /users/password(.:format) {controller:"devise/passwords", action:"create"}
-
#
-
# # Confirmation routes for Confirmable, if User model has :confirmable configured
-
# new_user_confirmation GET /users/confirmation/new(.:format) {controller:"devise/confirmations", action:"new"}
-
# user_confirmation GET /users/confirmation(.:format) {controller:"devise/confirmations", action:"show"}
-
# POST /users/confirmation(.:format) {controller:"devise/confirmations", action:"create"}
-
#
-
# ==== Routes integration
-
#
-
# +devise_for+ is meant to play nicely with other routes methods. For example,
-
# by calling +devise_for+ inside a namespace, it automatically nests your devise
-
# controllers:
-
#
-
# namespace :publisher do
-
# devise_for :account
-
# end
-
#
-
# The snippet above will use publisher/sessions controller instead of devise/sessions
-
# controller. You can revert this change or configure it directly by passing the :module
-
# option described below to +devise_for+.
-
#
-
# Also note that when you use a namespace it will affect all the helpers and methods
-
# for controllers and views. For example, using the above setup you'll end with
-
# following methods: current_publisher_account, authenticate_publisher_account!,
-
# publisher_account_signed_in, etc.
-
#
-
# The only aspect not affect by the router configuration is the model name. The
-
# model name can be explicitly set via the :class_name option.
-
#
-
# ==== Options
-
#
-
# You can configure your routes with some options:
-
#
-
# * class_name: setup a different class to be looked up by devise, if it cannot be
-
# properly found by the route name.
-
#
-
# devise_for :users, class_name: 'Account'
-
#
-
# * path: allows you to setup path name that will be used, as rails routes does.
-
# The following route configuration would setup your route as /accounts instead of /users:
-
#
-
# devise_for :users, path: 'accounts'
-
#
-
# * singular: setup the singular name for the given resource. This is used as the instance variable
-
# name in controller, as the name in routes and the scope given to warden.
-
#
-
# devise_for :users, singular: :user
-
#
-
# * path_names: configure different path names to overwrite defaults :sign_in, :sign_out, :sign_up,
-
# :password, :confirmation, :unlock.
-
#
-
# devise_for :users, path_names: {
-
# sign_in: 'login', sign_out: 'logout',
-
# password: 'secret', confirmation: 'verification',
-
# registration: 'register', edit: 'edit/profile'
-
# }
-
#
-
# * controllers: the controller which should be used. All routes by default points to Devise controllers.
-
# However, if you want them to point to custom controller, you should do:
-
#
-
# devise_for :users, controllers: { sessions: "users/sessions" }
-
#
-
# * failure_app: a rack app which is invoked whenever there is a failure. Strings representing a given
-
# are also allowed as parameter.
-
#
-
# * sign_out_via: the HTTP method(s) accepted for the :sign_out action (default: :get),
-
# if you wish to restrict this to accept only :post or :delete requests you should do:
-
#
-
# devise_for :users, sign_out_via: [ :post, :delete ]
-
#
-
# You need to make sure that your sign_out controls trigger a request with a matching HTTP method.
-
#
-
# * module: the namespace to find controllers (default: "devise", thus
-
# accessing devise/sessions, devise/registrations, and so on). If you want
-
# to namespace all at once, use module:
-
#
-
# devise_for :users, module: "users"
-
#
-
# * skip: tell which controller you want to skip routes from being created.
-
# It accepts :all as an option, meaning it will not generate any route at all:
-
#
-
# devise_for :users, skip: :sessions
-
#
-
# * only: the opposite of :skip, tell which controllers only to generate routes to:
-
#
-
# devise_for :users, only: :sessions
-
#
-
# * skip_helpers: skip generating Devise url helpers like new_session_path(@user).
-
# This is useful to avoid conflicts with previous routes and is false by default.
-
# It accepts true as option, meaning it will skip all the helpers for the controllers
-
# given in :skip but it also accepts specific helpers to be skipped:
-
#
-
# devise_for :users, skip: [:registrations, :confirmations], skip_helpers: true
-
# devise_for :users, skip_helpers: [:registrations, :confirmations]
-
#
-
# * format: include "(.:format)" in the generated routes? true by default, set to false to disable:
-
#
-
# devise_for :users, format: false
-
#
-
# * constraints: works the same as Rails' constraints
-
#
-
# * defaults: works the same as Rails' defaults
-
#
-
# * router_name: allows application level router name to be overwritten for the current scope
-
#
-
# ==== Scoping
-
#
-
# Following Rails 3 routes DSL, you can nest devise_for calls inside a scope:
-
#
-
# scope "/my" do
-
# devise_for :users
-
# end
-
#
-
# However, since Devise uses the request path to retrieve the current user,
-
# this has one caveat: If you are using a dynamic segment, like so ...
-
#
-
# scope ":locale" do
-
# devise_for :users
-
# end
-
#
-
# you are required to configure default_url_options in your
-
# ApplicationController class, so Devise can pick it:
-
#
-
# class ApplicationController < ActionController::Base
-
# def self.default_url_options
-
# { locale: I18n.locale }
-
# end
-
# end
-
#
-
# ==== Adding custom actions to override controllers
-
#
-
# You can pass a block to devise_for that will add any routes defined in the block to Devise's
-
# list of known actions. This is important if you add a custom action to a controller that
-
# overrides an out of the box Devise controller.
-
# For example:
-
#
-
# class RegistrationsController < Devise::RegistrationsController
-
# def update
-
# # do something different here
-
# end
-
#
-
# def deactivate
-
# # not a standard action
-
# # deactivate code here
-
# end
-
# end
-
#
-
# In order to get Devise to recognize the deactivate action, your devise_scope entry should look like this:
-
#
-
# devise_scope :owner do
-
# post "deactivate", to: "registrations#deactivate", as: "deactivate_registration"
-
# end
-
#
-
1
def devise_for(*resources)
-
1
@devise_finalized = false
-
1
raise_no_secret_key unless Devise.secret_key
-
1
options = resources.extract_options!
-
-
1
options[:as] ||= @scope[:as] if @scope[:as].present?
-
1
options[:module] ||= @scope[:module] if @scope[:module].present?
-
1
options[:path_prefix] ||= @scope[:path] if @scope[:path].present?
-
1
options[:path_names] = (@scope[:path_names] || {}).merge(options[:path_names] || {})
-
1
options[:constraints] = (@scope[:constraints] || {}).merge(options[:constraints] || {})
-
1
options[:defaults] = (@scope[:defaults] || {}).merge(options[:defaults] || {})
-
1
options[:options] = @scope[:options] || {}
-
1
options[:options][:format] = false if options[:format] == false
-
-
1
resources.map!(&:to_sym)
-
-
1
resources.each do |resource|
-
1
mapping = Devise.add_mapping(resource, options)
-
-
1
begin
-
1
raise_no_devise_method_error!(mapping.class_name) unless mapping.to.respond_to?(:devise)
-
rescue NameError => e
-
raise unless mapping.class_name == resource.to_s.classify
-
warn "[WARNING] You provided devise_for #{resource.inspect} but there is " \
-
"no model #{mapping.class_name} defined in your application"
-
next
-
rescue NoMethodError => e
-
raise unless e.message.include?("undefined method `devise'")
-
raise_no_devise_method_error!(mapping.class_name)
-
end
-
-
1
if options[:controllers] && options[:controllers][:omniauth_callbacks]
-
unless mapping.omniauthable?
-
raise ArgumentError, "Mapping omniauth_callbacks on a resource that is not omniauthable\n" \
-
"Please add `devise :omniauthable` to the `#{mapping.class_name}` model"
-
end
-
end
-
-
1
routes = mapping.used_routes
-
-
1
devise_scope mapping.name do
-
1
with_devise_exclusive_scope mapping.fullpath, mapping.name, options do
-
4
routes.each { |mod| send("devise_#{mod}", mapping, mapping.controllers) }
-
end
-
end
-
end
-
end
-
-
# Allow you to add authentication request from the router.
-
# Takes an optional scope and block to provide constraints
-
# on the model instance itself.
-
#
-
# authenticate do
-
# resources :post
-
# end
-
#
-
# authenticate(:admin) do
-
# resources :users
-
# end
-
#
-
# authenticate :user, lambda {|u| u.role == "admin"} do
-
# root to: "admin/dashboard#show", as: :user_root
-
# end
-
#
-
1
def authenticate(scope=nil, block=nil)
-
constraints_for(:authenticate!, scope, block) do
-
yield
-
end
-
end
-
-
# Allow you to route based on whether a scope is authenticated. You
-
# can optionally specify which scope and a block. The block accepts
-
# a model and allows extra constraints to be done on the instance.
-
#
-
# authenticated :admin do
-
# root to: 'admin/dashboard#show', as: :admin_root
-
# end
-
#
-
# authenticated do
-
# root to: 'dashboard#show', as: :authenticated_root
-
# end
-
#
-
# authenticated :user, lambda {|u| u.role == "admin"} do
-
# root to: "admin/dashboard#show", as: :user_root
-
# end
-
#
-
# root to: 'landing#show'
-
#
-
1
def authenticated(scope=nil, block=nil)
-
constraints_for(:authenticate?, scope, block) do
-
yield
-
end
-
end
-
-
# Allow you to route based on whether a scope is *not* authenticated.
-
# You can optionally specify which scope.
-
#
-
# unauthenticated do
-
# as :user do
-
# root to: 'devise/registrations#new'
-
# end
-
# end
-
#
-
# root to: 'dashboard#show'
-
#
-
1
def unauthenticated(scope=nil)
-
constraint = lambda do |request|
-
not request.env["warden"].authenticate? scope: scope
-
end
-
-
constraints(constraint) do
-
yield
-
end
-
end
-
-
# Sets the devise scope to be used in the controller. If you have custom routes,
-
# you are required to call this method (also aliased as :as) in order to specify
-
# to which controller it is targetted.
-
#
-
# as :user do
-
# get "sign_in", to: "devise/sessions#new"
-
# end
-
#
-
# Notice you cannot have two scopes mapping to the same URL. And remember, if
-
# you try to access a devise controller without specifying a scope, it will
-
# raise ActionNotFound error.
-
#
-
# Also be aware of that 'devise_scope' and 'as' use the singular form of the
-
# noun where other devise route commands expect the plural form. This would be a
-
# good and working example.
-
#
-
# devise_scope :user do
-
# get "/some/route" => "some_devise_controller"
-
# end
-
# devise_for :users
-
#
-
# Notice and be aware of the differences above between :user and :users
-
1
def devise_scope(scope)
-
1
constraint = lambda do |request|
-
request.env["devise.mapping"] = Devise.mappings[scope]
-
true
-
end
-
-
1
constraints(constraint) do
-
1
yield
-
end
-
end
-
1
alias :as :devise_scope
-
-
1
protected
-
-
1
def devise_session(mapping, controllers) #:nodoc:
-
1
resource :session, only: [], controller: controllers[:sessions], path: "" do
-
1
get :new, path: mapping.path_names[:sign_in], as: "new"
-
1
post :create, path: mapping.path_names[:sign_in]
-
1
match :destroy, path: mapping.path_names[:sign_out], as: "destroy", via: mapping.sign_out_via
-
end
-
end
-
-
1
def devise_password(mapping, controllers) #:nodoc:
-
1
resource :password, only: [:new, :create, :edit, :update],
-
path: mapping.path_names[:password], controller: controllers[:passwords]
-
end
-
-
1
def devise_confirmation(mapping, controllers) #:nodoc:
-
resource :confirmation, only: [:new, :create, :show],
-
path: mapping.path_names[:confirmation], controller: controllers[:confirmations]
-
end
-
-
1
def devise_unlock(mapping, controllers) #:nodoc:
-
if mapping.to.unlock_strategy_enabled?(:email)
-
resource :unlock, only: [:new, :create, :show],
-
path: mapping.path_names[:unlock], controller: controllers[:unlocks]
-
end
-
end
-
-
1
def devise_registration(mapping, controllers) #:nodoc:
-
1
path_names = {
-
new: mapping.path_names[:sign_up],
-
edit: mapping.path_names[:edit],
-
cancel: mapping.path_names[:cancel]
-
}
-
-
1
options = {
-
only: [:new, :create, :edit, :update, :destroy],
-
path: mapping.path_names[:registration],
-
path_names: path_names,
-
controller: controllers[:registrations]
-
}
-
-
1
resource :registration, options do
-
1
get :cancel
-
end
-
end
-
-
1
def devise_omniauth_callback(mapping, controllers) #:nodoc:
-
if mapping.fullpath =~ /:[a-zA-Z_]/
-
raise <<-ERROR
-
Devise does not support scoping omniauth callbacks under a dynamic segment
-
and you have set #{mapping.fullpath.inspect}. You can work around by passing
-
`skip: :omniauth_callbacks` and manually defining the routes. Here is an example:
-
-
match "/users/auth/:provider",
-
constraints: { provider: /google|facebook/ },
-
to: "devise/omniauth_callbacks#passthru",
-
as: :omniauth_authorize,
-
via: [:get, :post]
-
-
match "/users/auth/:action/callback",
-
constraints: { action: /google|facebook/ },
-
to: "devise/omniauth_callbacks",
-
as: :omniauth_callback,
-
via: [:get, :post]
-
ERROR
-
end
-
-
path, @scope[:path] = @scope[:path], nil
-
path_prefix = Devise.omniauth_path_prefix || "/#{mapping.fullpath}/auth".squeeze("/")
-
-
set_omniauth_path_prefix!(path_prefix)
-
-
providers = Regexp.union(mapping.to.omniauth_providers.map(&:to_s))
-
-
match "#{path_prefix}/:provider",
-
constraints: { provider: providers },
-
to: "#{controllers[:omniauth_callbacks]}#passthru",
-
as: :omniauth_authorize,
-
via: [:get, :post]
-
-
match "#{path_prefix}/:action/callback",
-
constraints: { action: providers },
-
to: controllers[:omniauth_callbacks],
-
as: :omniauth_callback,
-
via: [:get, :post]
-
ensure
-
@scope[:path] = path
-
end
-
-
1
DEVISE_SCOPE_KEYS = [:as, :path, :module, :constraints, :defaults, :options]
-
-
1
def with_devise_exclusive_scope(new_path, new_as, options) #:nodoc:
-
1
old = {}
-
7
DEVISE_SCOPE_KEYS.each { |k| old[k] = @scope[k] }
-
-
1
new = { as: new_as, path: new_path, module: nil }
-
1
new.merge!(options.slice(:constraints, :defaults, :options))
-
-
1
@scope.merge!(new)
-
1
yield
-
ensure
-
1
@scope.merge!(old)
-
end
-
-
1
def constraints_for(method_to_apply, scope=nil, block=nil)
-
constraint = lambda do |request|
-
request.env['warden'].send(method_to_apply, scope: scope) &&
-
(block.nil? || block.call(request.env["warden"].user(scope)))
-
end
-
-
constraints(constraint) do
-
yield
-
end
-
end
-
-
1
def set_omniauth_path_prefix!(path_prefix) #:nodoc:
-
if ::OmniAuth.config.path_prefix && ::OmniAuth.config.path_prefix != path_prefix
-
raise "Wrong OmniAuth configuration. If you are getting this exception, it means that either:\n\n" \
-
"1) You are manually setting OmniAuth.config.path_prefix and it doesn't match the Devise one\n" \
-
"2) You are setting :omniauthable in more than one model\n" \
-
"3) You changed your Devise routes/OmniAuth setting and haven't restarted your server"
-
else
-
::OmniAuth.config.path_prefix = path_prefix
-
end
-
end
-
-
1
def raise_no_secret_key #:nodoc:
-
raise <<-ERROR
-
Devise.secret_key was not set. Please add the following to your Devise initializer:
-
-
config.secret_key = '#{SecureRandom.hex(64)}'
-
-
Please ensure you restarted your application after installing Devise or setting the key.
-
ERROR
-
end
-
-
1
def raise_no_devise_method_error!(klass) #:nodoc:
-
raise "#{klass} does not respond to 'devise' method. This usually means you haven't " \
-
"loaded your ORM file or it's being loaded too late. To fix it, be sure to require 'devise/orm/YOUR_ORM' " \
-
"inside 'config/initializers/devise.rb' or before your application definition in 'config/application.rb'"
-
end
-
end
-
end
-
1
module Warden::Mixins::Common
-
1
def request
-
@request ||= ActionDispatch::Request.new(env)
-
end
-
-
# Deprecate: Remove this check once we move to Rails 4 only.
-
1
NULL_STORE =
-
defined?(ActionController::RequestForgeryProtection::ProtectionMethods::NullSession::NullSessionHash) ?
-
ActionController::RequestForgeryProtection::ProtectionMethods::NullSession::NullSessionHash : nil
-
-
1
def reset_session!
-
# Calling reset_session on NULL_STORE causes it fail.
-
# This is a bug that needs to be fixed in Rails.
-
unless NULL_STORE && request.session.is_a?(NULL_STORE)
-
request.reset_session
-
end
-
end
-
-
1
def cookies
-
request.cookie_jar
-
end
-
end
-
1
require 'devise/strategies/base'
-
-
1
module Devise
-
1
module Strategies
-
# This strategy should be used as basis for authentication strategies. It retrieves
-
# parameters both from params or from http authorization headers. See database_authenticatable
-
# for an example.
-
1
class Authenticatable < Base
-
1
attr_accessor :authentication_hash, :authentication_type, :password
-
-
1
def store?
-
super && !mapping.to.skip_session_storage.include?(authentication_type)
-
end
-
-
1
def valid?
-
valid_for_params_auth? || valid_for_http_auth?
-
end
-
-
# Override and set to false for things like OmniAuth that technically
-
# run through Authentication (user_set) very often, which would normally
-
# reset CSRF data in the session
-
1
def clean_up_csrf?
-
true
-
end
-
-
1
private
-
-
# Receives a resource and check if it is valid by calling valid_for_authentication?
-
# An optional block that will be triggered while validating can be optionally
-
# given as parameter. Check Devise::Models::Authenticable.valid_for_authentication?
-
# for more information.
-
#
-
# In case the resource can't be validated, it will fail with the given
-
# unauthenticated_message.
-
1
def validate(resource, &block)
-
result = resource && resource.valid_for_authentication?(&block)
-
-
if result
-
decorate(resource)
-
true
-
else
-
if resource
-
fail!(resource.unauthenticated_message)
-
end
-
false
-
end
-
end
-
-
# Get values from params and set in the resource.
-
1
def decorate(resource)
-
resource.remember_me = remember_me? if resource.respond_to?(:remember_me=)
-
end
-
-
# Should this resource be marked to be remembered?
-
1
def remember_me?
-
valid_params? && Devise::TRUE_VALUES.include?(params_auth_hash[:remember_me])
-
end
-
-
# Check if this is a valid strategy for http authentication by:
-
#
-
# * Validating if the model allows params authentication;
-
# * If any of the authorization headers were sent;
-
# * If all authentication keys are present;
-
#
-
1
def valid_for_http_auth?
-
http_authenticatable? && request.authorization && with_authentication_hash(:http_auth, http_auth_hash)
-
end
-
-
# Check if this is a valid strategy for params authentication by:
-
#
-
# * Validating if the model allows params authentication;
-
# * If the request hits the sessions controller through POST;
-
# * If the params[scope] returns a hash with credentials;
-
# * If all authentication keys are present;
-
#
-
1
def valid_for_params_auth?
-
params_authenticatable? && valid_params_request? &&
-
valid_params? && with_authentication_hash(:params_auth, params_auth_hash)
-
end
-
-
# Check if the model accepts this strategy as http authenticatable.
-
1
def http_authenticatable?
-
mapping.to.http_authenticatable?(authenticatable_name)
-
end
-
-
# Check if the model accepts this strategy as params authenticatable.
-
1
def params_authenticatable?
-
mapping.to.params_authenticatable?(authenticatable_name)
-
end
-
-
# Extract the appropriate subhash for authentication from params.
-
1
def params_auth_hash
-
params[scope]
-
end
-
-
# Extract a hash with attributes:values from the http params.
-
1
def http_auth_hash
-
keys = [http_authentication_key, :password]
-
Hash[*keys.zip(decode_credentials).flatten]
-
end
-
-
# By default, a request is valid if the controller set the proper env variable.
-
1
def valid_params_request?
-
!!env["devise.allow_params_authentication"]
-
end
-
-
# If the request is valid, finally check if params_auth_hash returns a hash.
-
1
def valid_params?
-
params_auth_hash.is_a?(Hash)
-
end
-
-
# Check if password is present.
-
1
def valid_password?
-
password.present?
-
end
-
-
# Helper to decode credentials from HTTP.
-
1
def decode_credentials
-
return [] unless request.authorization && request.authorization =~ /^Basic (.*)/m
-
Base64.decode64($1).split(/:/, 2)
-
end
-
-
# Sets the authentication hash and the password from params_auth_hash or http_auth_hash.
-
1
def with_authentication_hash(auth_type, auth_values)
-
self.authentication_hash, self.authentication_type = {}, auth_type
-
self.password = auth_values[:password]
-
-
parse_authentication_key_values(auth_values, authentication_keys) &&
-
parse_authentication_key_values(request_values, request_keys)
-
end
-
-
1
def authentication_keys
-
@authentication_keys ||= mapping.to.authentication_keys
-
end
-
-
1
def http_authentication_key
-
@http_authentication_key ||= mapping.to.http_authentication_key || case authentication_keys
-
when Array then authentication_keys.first
-
when Hash then authentication_keys.keys.first
-
end
-
end
-
-
1
def request_keys
-
@request_keys ||= mapping.to.request_keys
-
end
-
-
1
def request_values
-
keys = request_keys.respond_to?(:keys) ? request_keys.keys : request_keys
-
values = keys.map { |k| self.request.send(k) }
-
Hash[keys.zip(values)]
-
end
-
-
1
def parse_authentication_key_values(hash, keys)
-
keys.each do |key, enforce|
-
value = hash[key].presence
-
if value
-
self.authentication_hash[key] = value
-
else
-
return false unless enforce == false
-
end
-
end
-
true
-
end
-
-
# Holds the authenticatable name for this class. Devise::Strategies::DatabaseAuthenticatable
-
# becomes simply :database.
-
1
def authenticatable_name
-
@authenticatable_name ||=
-
ActiveSupport::Inflector.underscore(self.class.name.split("::").last).
-
sub("_authenticatable", "").to_sym
-
end
-
end
-
end
-
end
-
1
module Devise
-
1
module Strategies
-
# Base strategy for Devise. Responsible for verifying correct scope and mapping.
-
1
class Base < ::Warden::Strategies::Base
-
# Whenever CSRF cannot be verified, we turn off any kind of storage
-
1
def store?
-
!env["devise.skip_storage"]
-
end
-
-
# Checks if a valid scope was given for devise and find mapping based on this scope.
-
1
def mapping
-
@mapping ||= begin
-
mapping = Devise.mappings[scope]
-
raise "Could not find mapping for #{scope}" unless mapping
-
mapping
-
end
-
end
-
end
-
end
-
end
-
1
require 'devise/strategies/authenticatable'
-
-
1
module Devise
-
1
module Strategies
-
# Default strategy for signing in a user, based on their email and password in the database.
-
1
class DatabaseAuthenticatable < Authenticatable
-
1
def authenticate!
-
resource = valid_password? && mapping.to.find_for_database_authentication(authentication_hash)
-
encrypted = false
-
-
if validate(resource){ encrypted = true; resource.valid_password?(password) }
-
resource.after_database_authentication
-
success!(resource)
-
end
-
-
mapping.to.new.password = password if !encrypted && Devise.paranoid
-
fail(:not_found_in_database) unless resource
-
end
-
end
-
end
-
end
-
-
1
Warden::Strategies.add(:database_authenticatable, Devise::Strategies::DatabaseAuthenticatable)
-
1
require 'devise/strategies/authenticatable'
-
-
1
module Devise
-
1
module Strategies
-
# Remember the user through the remember token. This strategy is responsible
-
# to verify whether there is a cookie with the remember token, and to
-
# recreate the user from this cookie if it exists. Must be called *before*
-
# authenticatable.
-
1
class Rememberable < Authenticatable
-
# A valid strategy for rememberable needs a remember token in the cookies.
-
1
def valid?
-
@remember_cookie = nil
-
remember_cookie.present?
-
end
-
-
# To authenticate a user we deserialize the cookie and attempt finding
-
# the record in the database. If the attempt fails, we pass to another
-
# strategy handle the authentication.
-
1
def authenticate!
-
resource = mapping.to.serialize_from_cookie(*remember_cookie)
-
-
unless resource
-
cookies.delete(remember_key)
-
return pass
-
end
-
-
if validate(resource)
-
success!(resource)
-
end
-
end
-
-
1
private
-
-
1
def decorate(resource)
-
super
-
resource.extend_remember_period = mapping.to.extend_remember_period if resource.respond_to?(:extend_remember_period=)
-
end
-
-
1
def remember_me?
-
true
-
end
-
-
1
def remember_key
-
mapping.to.rememberable_options.fetch(:key, "remember_#{scope}_token")
-
end
-
-
1
def remember_cookie
-
@remember_cookie ||= cookies.signed[remember_key]
-
end
-
-
end
-
end
-
end
-
-
1
Warden::Strategies.add(:rememberable, Devise::Strategies::Rememberable)
-
# Deprecate: Copied verbatim from Rails source, remove once we move to Rails 4 only.
-
1
require 'thread_safe'
-
1
require 'openssl'
-
1
require 'securerandom'
-
-
1
module Devise
-
1
class TokenGenerator
-
1
def initialize(key_generator, digest="SHA256")
-
1
@key_generator = key_generator
-
1
@digest = digest
-
end
-
-
1
def digest(klass, column, value)
-
value.present? && OpenSSL::HMAC.hexdigest(@digest, key_for(column), value.to_s)
-
end
-
-
1
def generate(klass, column)
-
key = key_for(column)
-
-
loop do
-
raw = Devise.friendly_token
-
enc = OpenSSL::HMAC.hexdigest(@digest, key, raw)
-
break [raw, enc] unless klass.to_adapter.find_first({ column => enc })
-
end
-
end
-
-
1
private
-
-
1
def key_for(column)
-
@key_generator.generate_key("Devise #{column}")
-
end
-
end
-
-
# KeyGenerator is a simple wrapper around OpenSSL's implementation of PBKDF2
-
# It can be used to derive a number of keys for various purposes from a given secret.
-
# This lets Rails applications have a single secure secret, but avoid reusing that
-
# key in multiple incompatible contexts.
-
1
class KeyGenerator
-
1
def initialize(secret, options = {})
-
1
@secret = secret
-
# The default iterations are higher than required for our key derivation uses
-
# on the off chance someone uses this for password storage
-
1
@iterations = options[:iterations] || 2**16
-
end
-
-
# Returns a derived key suitable for use. The default key_size is chosen
-
# to be compatible with the default settings of ActiveSupport::MessageVerifier.
-
# i.e. OpenSSL::Digest::SHA1#block_length
-
1
def generate_key(salt, key_size=64)
-
OpenSSL::PKCS5.pbkdf2_hmac_sha1(@secret, salt, @iterations, key_size)
-
end
-
end
-
-
# CachingKeyGenerator is a wrapper around KeyGenerator which allows users to avoid
-
# re-executing the key generation process when it's called using the same salt and
-
# key_size
-
1
class CachingKeyGenerator
-
1
def initialize(key_generator)
-
1
@key_generator = key_generator
-
1
@cache_keys = ThreadSafe::Cache.new
-
end
-
-
# Returns a derived key suitable for use. The default key_size is chosen
-
# to be compatible with the default settings of ActiveSupport::MessageVerifier.
-
# i.e. OpenSSL::Digest::SHA1#block_length
-
1
def generate_key(salt, key_size=64)
-
@cache_keys["#{salt}#{key_size}"] ||= @key_generator.generate_key(salt, key_size)
-
end
-
end
-
end
-
# -*- ruby encoding: utf-8 -*-
-
-
1
module Diff; end unless defined? Diff
-
# = Diff::LCS 1.2.5
-
#
-
# Computes "intelligent" differences between two sequenced Enumerables. This
-
# is an implementation of the McIlroy-Hunt "diff" algorithm for Enumerable
-
# objects that include Diffable.
-
#
-
# Based on Mario I. Wolczko's Smalltalk version (1.2, 1993) and Ned Konz's
-
# Perl version (Algorithm::Diff 1.15).
-
#
-
# == Synopsis
-
# require 'diff/lcs'
-
#
-
# seq1 = %w(a b c e h j l m n p)
-
# seq2 = %w(b c d e f j k l m r s t)
-
#
-
# lcs = Diff::LCS.lcs(seq1, seq2)
-
# diffs = Diff::LCS.diff(seq1, seq2)
-
# sdiff = Diff::LCS.sdiff(seq1, seq2)
-
# seq = Diff::LCS.traverse_sequences(seq1, seq2, callback_obj)
-
# bal = Diff::LCS.traverse_balanced(seq1, seq2, callback_obj)
-
# seq2 == Diff::LCS.patch(seq1, diffs)
-
# seq2 == Diff::LCS.patch!(seq1, diffs)
-
# seq1 == Diff::LCS.unpatch(seq2, diffs)
-
# seq1 == Diff::LCS.unpatch!(seq2, diffs)
-
# seq2 == Diff::LCS.patch(seq1, sdiff)
-
# seq2 == Diff::LCS.patch!(seq1, sdiff)
-
# seq1 == Diff::LCS.unpatch(seq2, sdiff)
-
# seq1 == Diff::LCS.unpatch!(seq2, sdiff)
-
#
-
# Alternatively, objects can be extended with Diff::LCS:
-
#
-
# seq1.extend(Diff::LCS)
-
# lcs = seq1.lcs(seq2)
-
# diffs = seq1.diff(seq2)
-
# sdiff = seq1.sdiff(seq2)
-
# seq = seq1.traverse_sequences(seq2, callback_obj)
-
# bal = seq1.traverse_balanced(seq2, callback_obj)
-
# seq2 == seq1.patch(diffs)
-
# seq2 == seq1.patch!(diffs)
-
# seq1 == seq2.unpatch(diffs)
-
# seq1 == seq2.unpatch!(diffs)
-
# seq2 == seq1.patch(sdiff)
-
# seq2 == seq1.patch!(sdiff)
-
# seq1 == seq2.unpatch(sdiff)
-
# seq1 == seq2.unpatch!(sdiff)
-
#
-
# Default extensions are provided for Array and String objects through the
-
# use of 'diff/lcs/array' and 'diff/lcs/string'.
-
#
-
# == Introduction (by Mark-Jason Dominus)
-
#
-
# <em>The following text is from the Perl documentation. The only changes
-
# have been to make the text appear better in Rdoc</em>.
-
#
-
# I once read an article written by the authors of +diff+; they said that
-
# they hard worked very hard on the algorithm until they found the right
-
# one.
-
#
-
# I think what they ended up using (and I hope someone will correct me,
-
# because I am not very confident about this) was the `longest common
-
# subsequence' method. In the LCS problem, you have two sequences of items:
-
#
-
# a b c d f g h j q z
-
# a b c d e f g i j k r x y z
-
#
-
# and you want to find the longest sequence of items that is present in both
-
# original sequences in the same order. That is, you want to find a new
-
# sequence *S* which can be obtained from the first sequence by deleting
-
# some items, and from the second sequence by deleting other items. You also
-
# want *S* to be as long as possible. In this case *S* is:
-
#
-
# a b c d f g j z
-
#
-
# From there it's only a small step to get diff-like output:
-
#
-
# e h i k q r x y
-
# + - + + - + + +
-
#
-
# This module solves the LCS problem. It also includes a canned function to
-
# generate +diff+-like output.
-
#
-
# It might seem from the example above that the LCS of two sequences is
-
# always pretty obvious, but that's not always the case, especially when the
-
# two sequences have many repeated elements. For example, consider
-
#
-
# a x b y c z p d q
-
# a b c a x b y c z
-
#
-
# A naive approach might start by matching up the +a+ and +b+ that appear at
-
# the beginning of each sequence, like this:
-
#
-
# a x b y c z p d q
-
# a b c a b y c z
-
#
-
# This finds the common subsequence +a b c z+. But actually, the LCS is +a x
-
# b y c z+:
-
#
-
# a x b y c z p d q
-
# a b c a x b y c z
-
#
-
# == Author
-
# This version is by Austin Ziegler <austin@rubyforge.org>.
-
#
-
# It is based on the Perl Algorithm::Diff (1.15) by Ned Konz , copyright
-
# © 2000–2002 and the Smalltalk diff version by Mario I.
-
# Wolczko, copyright © 1993. Documentation includes work by
-
# Mark-Jason Dominus.
-
#
-
# == Licence
-
# Copyright © 2004–2013 Austin Ziegler
-
# This program is free software; you can redistribute it and/or modify it
-
# under the same terms as Ruby, or alternatively under the Perl Artistic
-
# licence.
-
#
-
# == Credits
-
# Much of the documentation is taken directly from the Perl Algorithm::Diff
-
# implementation and was written originally by Mark-Jason Dominus and later
-
# by Ned Konz. The basic Ruby implementation was re-ported from the
-
# Smalltalk implementation, available at
-
# ftp://st.cs.uiuc.edu/pub/Smalltalk/MANCHESTER/manchester/4.0/diff.st
-
#
-
# #sdiff and #traverse_balanced were written for the Perl version by Mike
-
# Schilli <m@perlmeister.com>.
-
#
-
# "The algorithm is described in <em>A Fast Algorithm for Computing Longest
-
# Common Subsequences</em>, CACM, vol.20, no.5, pp.350-353, May
-
# 1977, with a few minor improvements to improve the speed."
-
1
module Diff::LCS
-
1
VERSION = '1.2.5'
-
end
-
-
1
require 'diff/lcs/callbacks'
-
1
require 'diff/lcs/internals'
-
-
1
module Diff::LCS
-
# Returns an Array containing the longest common subsequence(s) between
-
# +self+ and +other+. See Diff::LCS#LCS.
-
#
-
# lcs = seq1.lcs(seq2)
-
1
def lcs(other, &block) #:yields self[i] if there are matched subsequences:
-
Diff::LCS.lcs(self, other, &block)
-
end
-
-
# Returns the difference set between +self+ and +other+. See
-
# Diff::LCS#diff.
-
1
def diff(other, callbacks = nil, &block)
-
Diff::LCS.diff(self, other, callbacks, &block)
-
end
-
-
# Returns the balanced ("side-by-side") difference set between +self+ and
-
# +other+. See Diff::LCS#sdiff.
-
1
def sdiff(other, callbacks = nil, &block)
-
Diff::LCS.sdiff(self, other, callbacks, &block)
-
end
-
-
# Traverses the discovered longest common subsequences between +self+ and
-
# +other+. See Diff::LCS#traverse_sequences.
-
1
def traverse_sequences(other, callbacks = nil, &block)
-
traverse_sequences(self, other, callbacks ||
-
Diff::LCS.YieldingCallbacks, &block)
-
end
-
-
# Traverses the discovered longest common subsequences between +self+ and
-
# +other+ using the alternate, balanced algorithm. See
-
# Diff::LCS#traverse_balanced.
-
1
def traverse_balanced(other, callbacks = nil, &block)
-
traverse_balanced(self, other, callbacks ||
-
Diff::LCS.YieldingCallbacks, &block)
-
end
-
-
# Attempts to patch +self+ with the provided +patchset+. A new sequence
-
# based on +self+ and the +patchset+ will be created. See Diff::LCS#patch.
-
# Attempts to autodiscover the direction of the patch.
-
1
def patch(patchset)
-
Diff::LCS.patch(self, patchset)
-
end
-
1
alias_method :unpatch, :patch
-
-
# Attempts to patch +self+ with the provided +patchset+. A new sequence
-
# based on +self+ and the +patchset+ will be created. See Diff::LCS#patch.
-
# Does no patch direction autodiscovery.
-
1
def patch!(patchset)
-
Diff::LCS.patch!(self, patchset)
-
end
-
-
# Attempts to unpatch +self+ with the provided +patchset+. A new sequence
-
# based on +self+ and the +patchset+ will be created. See Diff::LCS#unpatch.
-
# Does no patch direction autodiscovery.
-
1
def unpatch!(patchset)
-
Diff::LCS.unpatch!(self, patchset)
-
end
-
-
# Attempts to patch +self+ with the provided +patchset+, using #patch!. If
-
# the sequence this is used on supports #replace, the value of +self+ will
-
# be replaced. See Diff::LCS#patch. Does no patch direction autodiscovery.
-
1
def patch_me(patchset)
-
if respond_to? :replace
-
replace(patch!(patchset))
-
else
-
patch!(patchset)
-
end
-
end
-
-
# Attempts to unpatch +self+ with the provided +patchset+, using
-
# #unpatch!. If the sequence this is used on supports #replace, the value
-
# of +self+ will be replaced. See Diff::LCS#unpatch. Does no patch direction
-
# autodiscovery.
-
1
def unpatch_me(patchset)
-
if respond_to? :replace
-
replace(unpatch!(patchset))
-
else
-
unpatch!(patchset)
-
end
-
end
-
end
-
-
1
class << Diff::LCS
-
1
def lcs(seq1, seq2, &block) #:yields seq1[i] for each matched:
-
matches = Diff::LCS::Internals.lcs(seq1, seq2)
-
ret = []
-
string = seq1.kind_of? String
-
matches.each_with_index do |e, i|
-
unless matches[i].nil?
-
v = string ? seq1[i, 1] : seq1[i]
-
v = block[v] if block
-
ret << v
-
end
-
end
-
ret
-
end
-
1
alias_method :LCS, :lcs
-
-
# #diff computes the smallest set of additions and deletions necessary to
-
# turn the first sequence into the second, and returns a description of
-
# these changes.
-
#
-
# See Diff::LCS::DiffCallbacks for the default behaviour. An alternate
-
# behaviour may be implemented with Diff::LCS::ContextDiffCallbacks. If a
-
# Class argument is provided for +callbacks+, #diff will attempt to
-
# initialise it. If the +callbacks+ object (possibly initialised) responds
-
# to #finish, it will be called.
-
1
def diff(seq1, seq2, callbacks = nil, &block) # :yields diff changes:
-
diff_traversal(:diff, seq1, seq2, callbacks || Diff::LCS::DiffCallbacks,
-
&block)
-
end
-
-
# #sdiff computes all necessary components to show two sequences and their
-
# minimized differences side by side, just like the Unix utility
-
# <em>sdiff</em> does:
-
#
-
# old < -
-
# same same
-
# before | after
-
# - > new
-
#
-
# See Diff::LCS::SDiffCallbacks for the default behaviour. An alternate
-
# behaviour may be implemented with Diff::LCS::ContextDiffCallbacks. If a
-
# Class argument is provided for +callbacks+, #diff will attempt to
-
# initialise it. If the +callbacks+ object (possibly initialised) responds
-
# to #finish, it will be called.
-
1
def sdiff(seq1, seq2, callbacks = nil, &block) #:yields diff changes:
-
diff_traversal(:sdiff, seq1, seq2, callbacks || Diff::LCS::SDiffCallbacks,
-
&block)
-
end
-
-
# #traverse_sequences is the most general facility provided by this
-
# module; #diff and #lcs are implemented as calls to it.
-
#
-
# The arguments to #traverse_sequences are the two sequences to traverse,
-
# and a callback object, like this:
-
#
-
# traverse_sequences(seq1, seq2, Diff::LCS::ContextDiffCallbacks.new)
-
#
-
# == Callback Methods
-
#
-
# Optional callback methods are <em>emphasized</em>.
-
#
-
# callbacks#match:: Called when +a+ and +b+ are pointing to
-
# common elements in +A+ and +B+.
-
# callbacks#discard_a:: Called when +a+ is pointing to an
-
# element not in +B+.
-
# callbacks#discard_b:: Called when +b+ is pointing to an
-
# element not in +A+.
-
# <em>callbacks#finished_a</em>:: Called when +a+ has reached the end of
-
# sequence +A+.
-
# <em>callbacks#finished_b</em>:: Called when +b+ has reached the end of
-
# sequence +B+.
-
#
-
# == Algorithm
-
#
-
# a---+
-
# v
-
# A = a b c e h j l m n p
-
# B = b c d e f j k l m r s t
-
# ^
-
# b---+
-
#
-
# If there are two arrows (+a+ and +b+) pointing to elements of sequences
-
# +A+ and +B+, the arrows will initially point to the first elements of
-
# their respective sequences. #traverse_sequences will advance the arrows
-
# through the sequences one element at a time, calling a method on the
-
# user-specified callback object before each advance. It will advance the
-
# arrows in such a way that if there are elements <tt>A[i]</tt> and
-
# <tt>B[j]</tt> which are both equal and part of the longest common
-
# subsequence, there will be some moment during the execution of
-
# #traverse_sequences when arrow +a+ is pointing to <tt>A[i]</tt> and
-
# arrow +b+ is pointing to <tt>B[j]</tt>. When this happens,
-
# #traverse_sequences will call <tt>callbacks#match</tt> and then it will
-
# advance both arrows.
-
#
-
# Otherwise, one of the arrows is pointing to an element of its sequence
-
# that is not part of the longest common subsequence. #traverse_sequences
-
# will advance that arrow and will call <tt>callbacks#discard_a</tt> or
-
# <tt>callbacks#discard_b</tt>, depending on which arrow it advanced. If
-
# both arrows point to elements that are not part of the longest common
-
# subsequence, then #traverse_sequences will advance one of them and call
-
# the appropriate callback, but it is not specified which it will call.
-
#
-
# The methods for <tt>callbacks#match</tt>, <tt>callbacks#discard_a</tt>,
-
# and <tt>callbacks#discard_b</tt> are invoked with an event comprising
-
# the action ("=", "+", or "-", respectively), the indicies +i+ and +j+,
-
# and the elements <tt>A[i]</tt> and <tt>B[j]</tt>. Return values are
-
# discarded by #traverse_sequences.
-
#
-
# === End of Sequences
-
#
-
# If arrow +a+ reaches the end of its sequence before arrow +b+ does,
-
# #traverse_sequence will try to call <tt>callbacks#finished_a</tt> with
-
# the last index and element of +A+ (<tt>A[-1]</tt>) and the current index
-
# and element of +B+ (<tt>B[j]</tt>). If <tt>callbacks#finished_a</tt>
-
# does not exist, then <tt>callbacks#discard_b</tt> will be called on each
-
# element of +B+ until the end of the sequence is reached (the call will
-
# be done with <tt>A[-1]</tt> and <tt>B[j]</tt> for each element).
-
#
-
# If +b+ reaches the end of +B+ before +a+ reaches the end of +A+,
-
# <tt>callbacks#finished_b</tt> will be called with the current index and
-
# element of +A+ (<tt>A[i]</tt>) and the last index and element of +B+
-
# (<tt>A[-1]</tt>). Again, if <tt>callbacks#finished_b</tt> does not exist
-
# on the callback object, then <tt>callbacks#discard_a</tt> will be called
-
# on each element of +A+ until the end of the sequence is reached
-
# (<tt>A[i]</tt> and <tt>B[-1]</tt>).
-
#
-
# There is a chance that one additional <tt>callbacks#discard_a</tt> or
-
# <tt>callbacks#discard_b</tt> will be called after the end of the
-
# sequence is reached, if +a+ has not yet reached the end of +A+ or +b+
-
# has not yet reached the end of +B+.
-
1
def traverse_sequences(seq1, seq2, callbacks = Diff::LCS::SequenceCallbacks, &block) #:yields change events:
-
callbacks ||= Diff::LCS::SequenceCallbacks
-
matches = Diff::LCS::Internals.lcs(seq1, seq2)
-
-
run_finished_a = run_finished_b = false
-
string = seq1.kind_of?(String)
-
-
a_size = seq1.size
-
b_size = seq2.size
-
ai = bj = 0
-
-
(0..matches.size).each do |i|
-
b_line = matches[i]
-
-
ax = string ? seq1[i, 1] : seq1[i]
-
bx = string ? seq2[bj, 1] : seq2[bj]
-
-
if b_line.nil?
-
unless ax.nil? or (string and ax.empty?)
-
event = Diff::LCS::ContextChange.new('-', i, ax, bj, bx)
-
event = yield event if block_given?
-
callbacks.discard_a(event)
-
end
-
else
-
loop do
-
break unless bj < b_line
-
bx = string ? seq2[bj, 1] : seq2[bj]
-
event = Diff::LCS::ContextChange.new('+', i, ax, bj, bx)
-
event = yield event if block_given?
-
callbacks.discard_b(event)
-
bj += 1
-
end
-
bx = string ? seq2[bj, 1] : seq2[bj]
-
event = Diff::LCS::ContextChange.new('=', i, ax, bj, bx)
-
event = yield event if block_given?
-
callbacks.match(event)
-
bj += 1
-
end
-
ai = i
-
end
-
ai += 1
-
-
# The last entry (if any) processed was a match. +ai+ and +bj+ point
-
# just past the last matching lines in their sequences.
-
while (ai < a_size) or (bj < b_size)
-
# last A?
-
if ai == a_size and bj < b_size
-
if callbacks.respond_to?(:finished_a) and not run_finished_a
-
ax = string ? seq1[-1, 1] : seq1[-1]
-
bx = string ? seq2[bj, 1] : seq2[bj]
-
event = Diff::LCS::ContextChange.new('>', (a_size - 1), ax, bj, bx)
-
event = yield event if block_given?
-
callbacks.finished_a(event)
-
run_finished_a = true
-
else
-
ax = string ? seq1[ai, 1] : seq1[ai]
-
loop do
-
bx = string ? seq2[bj, 1] : seq2[bj]
-
event = Diff::LCS::ContextChange.new('+', ai, ax, bj, bx)
-
event = yield event if block_given?
-
callbacks.discard_b(event)
-
bj += 1
-
break unless bj < b_size
-
end
-
end
-
end
-
-
# last B?
-
if bj == b_size and ai < a_size
-
if callbacks.respond_to?(:finished_b) and not run_finished_b
-
ax = string ? seq1[ai, 1] : seq1[ai]
-
bx = string ? seq2[-1, 1] : seq2[-1]
-
event = Diff::LCS::ContextChange.new('<', ai, ax, (b_size - 1), bx)
-
event = yield event if block_given?
-
callbacks.finished_b(event)
-
run_finished_b = true
-
else
-
bx = string ? seq2[bj, 1] : seq2[bj]
-
loop do
-
ax = string ? seq1[ai, 1] : seq1[ai]
-
event = Diff::LCS::ContextChange.new('-', ai, ax, bj, bx)
-
event = yield event if block_given?
-
callbacks.discard_a(event)
-
ai += 1
-
break unless bj < b_size
-
end
-
end
-
end
-
-
if ai < a_size
-
ax = string ? seq1[ai, 1] : seq1[ai]
-
bx = string ? seq2[bj, 1] : seq2[bj]
-
event = Diff::LCS::ContextChange.new('-', ai, ax, bj, bx)
-
event = yield event if block_given?
-
callbacks.discard_a(event)
-
ai += 1
-
end
-
-
if bj < b_size
-
ax = string ? seq1[ai, 1] : seq1[ai]
-
bx = string ? seq2[bj, 1] : seq2[bj]
-
event = Diff::LCS::ContextChange.new('+', ai, ax, bj, bx)
-
event = yield event if block_given?
-
callbacks.discard_b(event)
-
bj += 1
-
end
-
end
-
end
-
-
# #traverse_balanced is an alternative to #traverse_sequences. It uses a
-
# different algorithm to iterate through the entries in the computed
-
# longest common subsequence. Instead of viewing the changes as insertions
-
# or deletions from one of the sequences, #traverse_balanced will report
-
# <em>changes</em> between the sequences.
-
#
-
# The arguments to #traverse_balanced are the two sequences to traverse
-
# and a callback object, like this:
-
#
-
# traverse_balanced(seq1, seq2, Diff::LCS::ContextDiffCallbacks.new)
-
#
-
# #sdiff is implemented with #traverse_balanced.
-
#
-
# == Callback Methods
-
#
-
# Optional callback methods are <em>emphasized</em>.
-
#
-
# callbacks#match:: Called when +a+ and +b+ are pointing to
-
# common elements in +A+ and +B+.
-
# callbacks#discard_a:: Called when +a+ is pointing to an
-
# element not in +B+.
-
# callbacks#discard_b:: Called when +b+ is pointing to an
-
# element not in +A+.
-
# <em>callbacks#change</em>:: Called when +a+ and +b+ are pointing to
-
# the same relative position, but
-
# <tt>A[a]</tt> and <tt>B[b]</tt> are not
-
# the same; a <em>change</em> has
-
# occurred.
-
#
-
# #traverse_balanced might be a bit slower than #traverse_sequences,
-
# noticable only while processing huge amounts of data.
-
#
-
# == Algorithm
-
#
-
# a---+
-
# v
-
# A = a b c e h j l m n p
-
# B = b c d e f j k l m r s t
-
# ^
-
# b---+
-
#
-
# === Matches
-
#
-
# If there are two arrows (+a+ and +b+) pointing to elements of sequences
-
# +A+ and +B+, the arrows will initially point to the first elements of
-
# their respective sequences. #traverse_sequences will advance the arrows
-
# through the sequences one element at a time, calling a method on the
-
# user-specified callback object before each advance. It will advance the
-
# arrows in such a way that if there are elements <tt>A[i]</tt> and
-
# <tt>B[j]</tt> which are both equal and part of the longest common
-
# subsequence, there will be some moment during the execution of
-
# #traverse_sequences when arrow +a+ is pointing to <tt>A[i]</tt> and
-
# arrow +b+ is pointing to <tt>B[j]</tt>. When this happens,
-
# #traverse_sequences will call <tt>callbacks#match</tt> and then it will
-
# advance both arrows.
-
#
-
# === Discards
-
#
-
# Otherwise, one of the arrows is pointing to an element of its sequence
-
# that is not part of the longest common subsequence. #traverse_sequences
-
# will advance that arrow and will call <tt>callbacks#discard_a</tt> or
-
# <tt>callbacks#discard_b</tt>, depending on which arrow it advanced.
-
#
-
# === Changes
-
#
-
# If both +a+ and +b+ point to elements that are not part of the longest
-
# common subsequence, then #traverse_sequences will try to call
-
# <tt>callbacks#change</tt> and advance both arrows. If
-
# <tt>callbacks#change</tt> is not implemented, then
-
# <tt>callbacks#discard_a</tt> and <tt>callbacks#discard_b</tt> will be
-
# called in turn.
-
#
-
# The methods for <tt>callbacks#match</tt>, <tt>callbacks#discard_a</tt>,
-
# <tt>callbacks#discard_b</tt>, and <tt>callbacks#change</tt> are invoked
-
# with an event comprising the action ("=", "+", "-", or "!",
-
# respectively), the indicies +i+ and +j+, and the elements
-
# <tt>A[i]</tt> and <tt>B[j]</tt>. Return values are discarded by
-
# #traverse_balanced.
-
#
-
# === Context
-
# Note that +i+ and +j+ may not be the same index position, even if +a+
-
# and +b+ are considered to be pointing to matching or changed elements.
-
1
def traverse_balanced(seq1, seq2, callbacks = Diff::LCS::BalancedCallbacks)
-
matches = Diff::LCS::Internals.lcs(seq1, seq2)
-
a_size = seq1.size
-
b_size = seq2.size
-
ai = bj = mb = 0
-
ma = -1
-
string = seq1.kind_of?(String)
-
-
# Process all the lines in the match vector.
-
loop do
-
# Find next match indices +ma+ and +mb+
-
loop do
-
ma += 1
-
break unless ma < matches.size and matches[ma].nil?
-
end
-
-
break if ma >= matches.size # end of matches?
-
mb = matches[ma]
-
-
# Change(seq2)
-
while (ai < ma) or (bj < mb)
-
ax = string ? seq1[ai, 1] : seq1[ai]
-
bx = string ? seq2[bj, 1] : seq2[bj]
-
-
case [(ai < ma), (bj < mb)]
-
when [true, true]
-
if callbacks.respond_to?(:change)
-
event = Diff::LCS::ContextChange.new('!', ai, ax, bj, bx)
-
event = yield event if block_given?
-
callbacks.change(event)
-
ai += 1
-
bj += 1
-
else
-
event = Diff::LCS::ContextChange.new('-', ai, ax, bj, bx)
-
event = yield event if block_given?
-
callbacks.discard_a(event)
-
ai += 1
-
ax = string ? seq1[ai, 1] : seq1[ai]
-
event = Diff::LCS::ContextChange.new('+', ai, ax, bj, bx)
-
event = yield event if block_given?
-
callbacks.discard_b(event)
-
bj += 1
-
end
-
when [true, false]
-
event = Diff::LCS::ContextChange.new('-', ai, ax, bj, bx)
-
event = yield event if block_given?
-
callbacks.discard_a(event)
-
ai += 1
-
when [false, true]
-
event = Diff::LCS::ContextChange.new('+', ai, ax, bj, bx)
-
event = yield event if block_given?
-
callbacks.discard_b(event)
-
bj += 1
-
end
-
end
-
-
# Match
-
ax = string ? seq1[ai, 1] : seq1[ai]
-
bx = string ? seq2[bj, 1] : seq2[bj]
-
event = Diff::LCS::ContextChange.new('=', ai, ax, bj, bx)
-
event = yield event if block_given?
-
callbacks.match(event)
-
ai += 1
-
bj += 1
-
end
-
-
while (ai < a_size) or (bj < b_size)
-
ax = string ? seq1[ai, 1] : seq1[ai]
-
bx = string ? seq2[bj, 1] : seq2[bj]
-
-
case [(ai < a_size), (bj < b_size)]
-
when [true, true]
-
if callbacks.respond_to?(:change)
-
event = Diff::LCS::ContextChange.new('!', ai, ax, bj, bx)
-
event = yield event if block_given?
-
callbacks.change(event)
-
ai += 1
-
bj += 1
-
else
-
event = Diff::LCS::ContextChange.new('-', ai, ax, bj, bx)
-
event = yield event if block_given?
-
callbacks.discard_a(event)
-
ai += 1
-
ax = string ? seq1[ai, 1] : seq1[ai]
-
event = Diff::LCS::ContextChange.new('+', ai, ax, bj, bx)
-
event = yield event if block_given?
-
callbacks.discard_b(event)
-
bj += 1
-
end
-
when [true, false]
-
event = Diff::LCS::ContextChange.new('-', ai, ax, bj, bx)
-
event = yield event if block_given?
-
callbacks.discard_a(event)
-
ai += 1
-
when [false, true]
-
event = Diff::LCS::ContextChange.new('+', ai, ax, bj, bx)
-
event = yield event if block_given?
-
callbacks.discard_b(event)
-
bj += 1
-
end
-
end
-
end
-
-
1
PATCH_MAP = { #:nodoc:
-
:patch => { '+' => '+', '-' => '-', '!' => '!', '=' => '=' },
-
:unpatch => { '+' => '-', '-' => '+', '!' => '!', '=' => '=' }
-
}
-
-
# Applies a +patchset+ to the sequence +src+ according to the +direction+
-
# (<tt>:patch</tt> or <tt>:unpatch</tt>), producing a new sequence.
-
#
-
# If the +direction+ is not specified, Diff::LCS::patch will attempt to
-
# discover the direction of the +patchset+.
-
#
-
# A +patchset+ can be considered to apply forward (<tt>:patch</tt>) if the
-
# following expression is true:
-
#
-
# patch(s1, diff(s1, s2)) -> s2
-
#
-
# A +patchset+ can be considered to apply backward (<tt>:unpatch</tt>) if
-
# the following expression is true:
-
#
-
# patch(s2, diff(s1, s2)) -> s1
-
#
-
# If the +patchset+ contains no changes, the +src+ value will be returned
-
# as either <tt>src.dup</tt> or +src+. A +patchset+ can be deemed as
-
# having no changes if the following predicate returns true:
-
#
-
# patchset.empty? or
-
# patchset.flatten.all? { |change| change.unchanged? }
-
#
-
# === Patchsets
-
#
-
# A +patchset+ is always an enumerable sequence of changes, hunks of
-
# changes, or a mix of the two. A hunk of changes is an enumerable
-
# sequence of changes:
-
#
-
# [ # patchset
-
# # change
-
# [ # hunk
-
# # change
-
# ]
-
# ]
-
#
-
# The +patch+ method accepts <tt>patchset</tt>s that are enumerable
-
# sequences containing either Diff::LCS::Change objects (or a subclass) or
-
# the array representations of those objects. Prior to application, array
-
# representations of Diff::LCS::Change objects will be reified.
-
1
def patch(src, patchset, direction = nil)
-
# Normalize the patchset.
-
has_changes, patchset = Diff::LCS::Internals.analyze_patchset(patchset)
-
-
if not has_changes
-
return src.dup if src.respond_to? :dup
-
return src
-
end
-
-
string = src.kind_of?(String)
-
# Start with a new empty type of the source's class
-
res = src.class.new
-
-
direction ||= Diff::LCS::Internals.intuit_diff_direction(src, patchset)
-
-
ai = bj = 0
-
-
patch_map = PATCH_MAP[direction]
-
-
patchset.flatten.each do |change|
-
# Both Change and ContextChange support #action
-
action = patch_map[change.action]
-
-
case change
-
when Diff::LCS::ContextChange
-
case direction
-
when :patch
-
el = change.new_element
-
op = change.old_position
-
np = change.new_position
-
when :unpatch
-
el = change.old_element
-
op = change.new_position
-
np = change.old_position
-
end
-
-
case action
-
when '-' # Remove details from the old string
-
while ai < op
-
res << (string ? src[ai, 1] : src[ai])
-
ai += 1
-
bj += 1
-
end
-
ai += 1
-
when '+'
-
while bj < np
-
res << (string ? src[ai, 1] : src[ai])
-
ai += 1
-
bj += 1
-
end
-
-
res << el
-
bj += 1
-
when '='
-
# This only appears in sdiff output with the SDiff callback.
-
# Therefore, we only need to worry about dealing with a single
-
# element.
-
res << el
-
-
ai += 1
-
bj += 1
-
when '!'
-
while ai < op
-
res << (string ? src[ai, 1] : src[ai])
-
ai += 1
-
bj += 1
-
end
-
-
bj += 1
-
ai += 1
-
-
res << el
-
end
-
when Diff::LCS::Change
-
case action
-
when '-'
-
while ai < change.position
-
res << (string ? src[ai, 1] : src[ai])
-
ai += 1
-
bj += 1
-
end
-
ai += 1
-
when '+'
-
while bj < change.position
-
res << (string ? src[ai, 1] : src[ai])
-
ai += 1
-
bj += 1
-
end
-
-
bj += 1
-
-
res << change.element
-
end
-
end
-
end
-
-
while ai < src.size
-
res << (string ? src[ai, 1] : src[ai])
-
ai += 1
-
bj += 1
-
end
-
-
res
-
end
-
-
# Given a set of patchset, convert the current version to the prior
-
# version. Does no auto-discovery.
-
1
def unpatch!(src, patchset)
-
patch(src, patchset, :unpatch)
-
end
-
-
# Given a set of patchset, convert the current version to the next
-
# version. Does no auto-discovery.
-
1
def patch!(src, patchset)
-
patch(src, patchset, :patch)
-
end
-
end
-
# -*- ruby encoding: utf-8 -*-
-
-
# A block is an operation removing, adding, or changing a group of items.
-
# Basically, this is just a list of changes, where each change adds or
-
# deletes a single item. Used by bin/ldiff.
-
1
class Diff::LCS::Block
-
1
attr_reader :changes, :insert, :remove
-
-
1
def initialize(chunk)
-
@changes = []
-
@insert = []
-
@remove = []
-
-
chunk.each do |item|
-
@changes << item
-
@remove << item if item.deleting?
-
@insert << item if item.adding?
-
end
-
end
-
-
1
def diff_size
-
@insert.size - @remove.size
-
end
-
-
1
def op
-
case [@remove.empty?, @insert.empty?]
-
when [false, false]
-
'!'
-
when [false, true]
-
'-'
-
when [true, false]
-
'+'
-
else # [true, true]
-
'^'
-
end
-
end
-
end
-
# -*- ruby encoding: utf-8 -*-
-
-
1
require 'diff/lcs/change'
-
-
1
module Diff::LCS
-
# This callback object implements the default set of callback events,
-
# which only returns the event itself. Note that #finished_a and
-
# #finished_b are not implemented -- I haven't yet figured out where they
-
# would be useful.
-
#
-
# Note that this is intended to be called as is, e.g.,
-
#
-
# Diff::LCS.LCS(seq1, seq2, Diff::LCS::DefaultCallbacks)
-
1
class DefaultCallbacks
-
1
class << self
-
# Called when two items match.
-
1
def match(event)
-
event
-
end
-
# Called when the old value is discarded in favour of the new value.
-
1
def discard_a(event)
-
event
-
end
-
# Called when the new value is discarded in favour of the old value.
-
1
def discard_b(event)
-
event
-
end
-
# Called when both the old and new values have changed.
-
1
def change(event)
-
event
-
end
-
-
1
private :new
-
end
-
end
-
-
# An alias for DefaultCallbacks that is used in
-
# Diff::LCS#traverse_sequences.
-
#
-
# Diff::LCS.LCS(seq1, seq2, Diff::LCS::SequenceCallbacks)
-
1
SequenceCallbacks = DefaultCallbacks
-
-
# An alias for DefaultCallbacks that is used in
-
# Diff::LCS#traverse_balanced.
-
#
-
# Diff::LCS.LCS(seq1, seq2, Diff::LCS::BalancedCallbacks)
-
1
BalancedCallbacks = DefaultCallbacks
-
-
1
def self.callbacks_for(callbacks)
-
callbacks.new rescue callbacks
-
end
-
end
-
-
# This will produce a compound array of simple diff change objects. Each
-
# element in the #diffs array is a +hunk+ or +hunk+ array, where each
-
# element in each +hunk+ array is a single Change object representing the
-
# addition or removal of a single element from one of the two tested
-
# sequences. The +hunk+ provides the full context for the changes.
-
#
-
# diffs = Diff::LCS.diff(seq1, seq2)
-
# # This example shows a simplified array format.
-
# # [ [ [ '-', 0, 'a' ] ], # 1
-
# # [ [ '+', 2, 'd' ] ], # 2
-
# # [ [ '-', 4, 'h' ], # 3
-
# # [ '+', 4, 'f' ] ],
-
# # [ [ '+', 6, 'k' ] ], # 4
-
# # [ [ '-', 8, 'n' ], # 5
-
# # [ '-', 9, 'p' ],
-
# # [ '+', 9, 'r' ],
-
# # [ '+', 10, 's' ],
-
# # [ '+', 11, 't' ] ] ]
-
#
-
# There are five hunks here. The first hunk says that the +a+ at position 0
-
# of the first sequence should be deleted (<tt>'-'</tt>). The second hunk
-
# says that the +d+ at position 2 of the second sequence should be inserted
-
# (<tt>'+'</tt>). The third hunk says that the +h+ at position 4 of the
-
# first sequence should be removed and replaced with the +f+ from position 4
-
# of the second sequence. The other two hunks are described similarly.
-
#
-
# === Use
-
#
-
# This callback object must be initialised and is used by the Diff::LCS#diff
-
# method.
-
#
-
# cbo = Diff::LCS::DiffCallbacks.new
-
# Diff::LCS.LCS(seq1, seq2, cbo)
-
# cbo.finish
-
#
-
# Note that the call to #finish is absolutely necessary, or the last set of
-
# changes will not be visible. Alternatively, can be used as:
-
#
-
# cbo = Diff::LCS::DiffCallbacks.new { |tcbo| Diff::LCS.LCS(seq1, seq2, tcbo) }
-
#
-
# The necessary #finish call will be made.
-
#
-
# === Simplified Array Format
-
#
-
# The simplified array format used in the example above can be obtained
-
# with:
-
#
-
# require 'pp'
-
# pp diffs.map { |e| e.map { |f| f.to_a } }
-
1
class Diff::LCS::DiffCallbacks
-
# Returns the difference set collected during the diff process.
-
1
attr_reader :diffs
-
-
1
def initialize # :yields self:
-
@hunk = []
-
@diffs = []
-
-
if block_given?
-
begin
-
yield self
-
ensure
-
self.finish
-
end
-
end
-
end
-
-
# Finalizes the diff process. If an unprocessed hunk still exists, then it
-
# is appended to the diff list.
-
1
def finish
-
finish_hunk
-
end
-
-
1
def match(event)
-
finish_hunk
-
end
-
-
1
def discard_a(event)
-
@hunk << Diff::LCS::Change.new('-', event.old_position, event.old_element)
-
end
-
-
1
def discard_b(event)
-
@hunk << Diff::LCS::Change.new('+', event.new_position, event.new_element)
-
end
-
-
1
def finish_hunk
-
@diffs << @hunk unless @hunk.empty?
-
@hunk = []
-
end
-
1
private :finish_hunk
-
end
-
-
# This will produce a compound array of contextual diff change objects. Each
-
# element in the #diffs array is a "hunk" array, where each element in each
-
# "hunk" array is a single change. Each change is a Diff::LCS::ContextChange
-
# that contains both the old index and new index values for the change. The
-
# "hunk" provides the full context for the changes. Both old and new objects
-
# will be presented for changed objects. +nil+ will be substituted for a
-
# discarded object.
-
#
-
# seq1 = %w(a b c e h j l m n p)
-
# seq2 = %w(b c d e f j k l m r s t)
-
#
-
# diffs = Diff::LCS.diff(seq1, seq2, Diff::LCS::ContextDiffCallbacks)
-
# # This example shows a simplified array format.
-
# # [ [ [ '-', [ 0, 'a' ], [ 0, nil ] ] ], # 1
-
# # [ [ '+', [ 3, nil ], [ 2, 'd' ] ] ], # 2
-
# # [ [ '-', [ 4, 'h' ], [ 4, nil ] ], # 3
-
# # [ '+', [ 5, nil ], [ 4, 'f' ] ] ],
-
# # [ [ '+', [ 6, nil ], [ 6, 'k' ] ] ], # 4
-
# # [ [ '-', [ 8, 'n' ], [ 9, nil ] ], # 5
-
# # [ '+', [ 9, nil ], [ 9, 'r' ] ],
-
# # [ '-', [ 9, 'p' ], [ 10, nil ] ],
-
# # [ '+', [ 10, nil ], [ 10, 's' ] ],
-
# # [ '+', [ 10, nil ], [ 11, 't' ] ] ] ]
-
#
-
# The five hunks shown are comprised of individual changes; if there is a
-
# related set of changes, they are still shown individually.
-
#
-
# This callback can also be used with Diff::LCS#sdiff, which will produce
-
# results like:
-
#
-
# diffs = Diff::LCS.sdiff(seq1, seq2, Diff::LCS::ContextCallbacks)
-
# # This example shows a simplified array format.
-
# # [ [ [ "-", [ 0, "a" ], [ 0, nil ] ] ], # 1
-
# # [ [ "+", [ 3, nil ], [ 2, "d" ] ] ], # 2
-
# # [ [ "!", [ 4, "h" ], [ 4, "f" ] ] ], # 3
-
# # [ [ "+", [ 6, nil ], [ 6, "k" ] ] ], # 4
-
# # [ [ "!", [ 8, "n" ], [ 9, "r" ] ], # 5
-
# # [ "!", [ 9, "p" ], [ 10, "s" ] ],
-
# # [ "+", [ 10, nil ], [ 11, "t" ] ] ] ]
-
#
-
# The five hunks are still present, but are significantly shorter in total
-
# presentation, because changed items are shown as changes ("!") instead of
-
# potentially "mismatched" pairs of additions and deletions.
-
#
-
# The result of this operation is similar to that of
-
# Diff::LCS::SDiffCallbacks. They may be compared as:
-
#
-
# s = Diff::LCS.sdiff(seq1, seq2).reject { |e| e.action == "=" }
-
# c = Diff::LCS.sdiff(seq1, seq2, Diff::LCS::ContextDiffCallbacks).flatten
-
#
-
# s == c # -> true
-
#
-
# === Use
-
#
-
# This callback object must be initialised and can be used by the
-
# Diff::LCS#diff or Diff::LCS#sdiff methods.
-
#
-
# cbo = Diff::LCS::ContextDiffCallbacks.new
-
# Diff::LCS.LCS(seq1, seq2, cbo)
-
# cbo.finish
-
#
-
# Note that the call to #finish is absolutely necessary, or the last set of
-
# changes will not be visible. Alternatively, can be used as:
-
#
-
# cbo = Diff::LCS::ContextDiffCallbacks.new { |tcbo| Diff::LCS.LCS(seq1, seq2, tcbo) }
-
#
-
# The necessary #finish call will be made.
-
#
-
# === Simplified Array Format
-
#
-
# The simplified array format used in the example above can be obtained
-
# with:
-
#
-
# require 'pp'
-
# pp diffs.map { |e| e.map { |f| f.to_a } }
-
1
class Diff::LCS::ContextDiffCallbacks < Diff::LCS::DiffCallbacks
-
1
def discard_a(event)
-
@hunk << Diff::LCS::ContextChange.simplify(event)
-
end
-
-
1
def discard_b(event)
-
@hunk << Diff::LCS::ContextChange.simplify(event)
-
end
-
-
1
def change(event)
-
@hunk << Diff::LCS::ContextChange.simplify(event)
-
end
-
end
-
-
# This will produce a simple array of diff change objects. Each element in
-
# the #diffs array is a single ContextChange. In the set of #diffs provided
-
# by SDiffCallbacks, both old and new objects will be presented for both
-
# changed <strong>and unchanged</strong> objects. +nil+ will be substituted
-
# for a discarded object.
-
#
-
# The diffset produced by this callback, when provided to Diff::LCS#sdiff,
-
# will compute and display the necessary components to show two sequences
-
# and their minimized differences side by side, just like the Unix utility
-
# +sdiff+.
-
#
-
# same same
-
# before | after
-
# old < -
-
# - > new
-
#
-
# seq1 = %w(a b c e h j l m n p)
-
# seq2 = %w(b c d e f j k l m r s t)
-
#
-
# diffs = Diff::LCS.sdiff(seq1, seq2)
-
# # This example shows a simplified array format.
-
# # [ [ "-", [ 0, "a"], [ 0, nil ] ],
-
# # [ "=", [ 1, "b"], [ 0, "b" ] ],
-
# # [ "=", [ 2, "c"], [ 1, "c" ] ],
-
# # [ "+", [ 3, nil], [ 2, "d" ] ],
-
# # [ "=", [ 3, "e"], [ 3, "e" ] ],
-
# # [ "!", [ 4, "h"], [ 4, "f" ] ],
-
# # [ "=", [ 5, "j"], [ 5, "j" ] ],
-
# # [ "+", [ 6, nil], [ 6, "k" ] ],
-
# # [ "=", [ 6, "l"], [ 7, "l" ] ],
-
# # [ "=", [ 7, "m"], [ 8, "m" ] ],
-
# # [ "!", [ 8, "n"], [ 9, "r" ] ],
-
# # [ "!", [ 9, "p"], [ 10, "s" ] ],
-
# # [ "+", [ 10, nil], [ 11, "t" ] ] ]
-
#
-
# The result of this operation is similar to that of
-
# Diff::LCS::ContextDiffCallbacks. They may be compared as:
-
#
-
# s = Diff::LCS.sdiff(seq1, seq2).reject { |e| e.action == "=" }
-
# c = Diff::LCS.sdiff(seq1, seq2, Diff::LCS::ContextDiffCallbacks).flatten
-
#
-
# s == c # -> true
-
#
-
# === Use
-
#
-
# This callback object must be initialised and is used by the Diff::LCS#sdiff
-
# method.
-
#
-
# cbo = Diff::LCS::SDiffCallbacks.new
-
# Diff::LCS.LCS(seq1, seq2, cbo)
-
#
-
# As with the other initialisable callback objects,
-
# Diff::LCS::SDiffCallbacks can be initialised with a block. As there is no
-
# "fininishing" to be done, this has no effect on the state of the object.
-
#
-
# cbo = Diff::LCS::SDiffCallbacks.new { |tcbo| Diff::LCS.LCS(seq1, seq2, tcbo) }
-
#
-
# === Simplified Array Format
-
#
-
# The simplified array format used in the example above can be obtained
-
# with:
-
#
-
# require 'pp'
-
# pp diffs.map { |e| e.to_a }
-
1
class Diff::LCS::SDiffCallbacks
-
# Returns the difference set collected during the diff process.
-
1
attr_reader :diffs
-
-
1
def initialize #:yields self:
-
@diffs = []
-
yield self if block_given?
-
end
-
-
1
def match(event)
-
@diffs << Diff::LCS::ContextChange.simplify(event)
-
end
-
-
1
def discard_a(event)
-
@diffs << Diff::LCS::ContextChange.simplify(event)
-
end
-
-
1
def discard_b(event)
-
@diffs << Diff::LCS::ContextChange.simplify(event)
-
end
-
-
1
def change(event)
-
@diffs << Diff::LCS::ContextChange.simplify(event)
-
end
-
end
-
# -*- ruby encoding: utf-8 -*-
-
-
# Represents a simplistic (non-contextual) change. Represents the removal or
-
# addition of an element from either the old or the new sequenced
-
# enumerable.
-
1
class Diff::LCS::Change
-
# The only actions valid for changes are '+' (add), '-' (delete), '='
-
# (no change), '!' (changed), '<' (tail changes from first sequence), or
-
# '>' (tail changes from second sequence). The last two ('<>') are only
-
# found with Diff::LCS::diff and Diff::LCS::sdiff.
-
1
VALID_ACTIONS = %W(+ - = ! > <)
-
-
1
def self.valid_action?(action)
-
VALID_ACTIONS.include? action
-
end
-
-
# Returns the action this Change represents.
-
1
attr_reader :action
-
-
# Returns the position of the Change.
-
1
attr_reader :position
-
# Returns the sequence element of the Change.
-
1
attr_reader :element
-
-
1
def initialize(*args)
-
@action, @position, @element = *args
-
-
unless Diff::LCS::Change.valid_action?(@action)
-
raise "Invalid Change Action '#{@action}'"
-
end
-
raise "Invalid Position Type" unless @position.kind_of? Fixnum
-
end
-
-
1
def inspect
-
to_a.inspect
-
end
-
-
1
def to_a
-
[ @action, @position, @element ]
-
end
-
-
1
def self.from_a(arr)
-
arr = arr.flatten(1)
-
case arr.size
-
when 5
-
Diff::LCS::ContextChange.new(*(arr[0...5]))
-
when 3
-
Diff::LCS::Change.new(*(arr[0...3]))
-
else
-
raise "Invalid change array format provided."
-
end
-
end
-
-
1
include Comparable
-
-
1
def ==(other)
-
(self.action == other.action) and
-
(self.position == other.position) and
-
(self.element == other.element)
-
end
-
-
1
def <=>(other)
-
r = self.action <=> other.action
-
r = self.position <=> other.position if r.zero?
-
r = self.element <=> other.element if r.zero?
-
r
-
end
-
-
1
def adding?
-
@action == '+'
-
end
-
-
1
def deleting?
-
@action == '-'
-
end
-
-
1
def unchanged?
-
@action == '='
-
end
-
-
1
def changed?
-
@action == '!'
-
end
-
-
1
def finished_a?
-
@action == '>'
-
end
-
-
1
def finished_b?
-
@action == '<'
-
end
-
end
-
-
# Represents a contextual change. Contains the position and values of the
-
# elements in the old and the new sequenced enumerables as well as the action
-
# taken.
-
1
class Diff::LCS::ContextChange < Diff::LCS::Change
-
# We don't need these two values.
-
1
undef :position
-
1
undef :element
-
-
# Returns the old position being changed.
-
1
attr_reader :old_position
-
# Returns the new position being changed.
-
1
attr_reader :new_position
-
# Returns the old element being changed.
-
1
attr_reader :old_element
-
# Returns the new element being changed.
-
1
attr_reader :new_element
-
-
1
def initialize(*args)
-
@action, @old_position, @old_element, @new_position, @new_element = *args
-
-
unless Diff::LCS::Change.valid_action?(@action)
-
raise "Invalid Change Action '#{@action}'"
-
end
-
unless @old_position.nil? or @old_position.kind_of? Fixnum
-
raise "Invalid (Old) Position Type"
-
end
-
unless @new_position.nil? or @new_position.kind_of? Fixnum
-
raise "Invalid (New) Position Type"
-
end
-
end
-
-
1
def to_a
-
[ @action,
-
[ @old_position, @old_element ],
-
[ @new_position, @new_element ]
-
]
-
end
-
-
1
def inspect(*args)
-
to_a.inspect
-
end
-
-
1
def self.from_a(arr)
-
Diff::LCS::Change.from_a(arr)
-
end
-
-
# Simplifies a context change for use in some diff callbacks. '<' actions
-
# are converted to '-' and '>' actions are converted to '+'.
-
1
def self.simplify(event)
-
ea = event.to_a
-
-
case ea[0]
-
when '-'
-
ea[2][1] = nil
-
when '<'
-
ea[0] = '-'
-
ea[2][1] = nil
-
when '+'
-
ea[1][1] = nil
-
when '>'
-
ea[0] = '+'
-
ea[1][1] = nil
-
end
-
-
Diff::LCS::ContextChange.from_a(ea)
-
end
-
-
1
def ==(other)
-
(@action == other.action) and
-
(@old_position == other.old_position) and
-
(@new_position == other.new_position) and
-
(@old_element == other.old_element) and
-
(@new_element == other.new_element)
-
end
-
-
1
def <=>(other)
-
r = @action <=> other.action
-
r = @old_position <=> other.old_position if r.zero?
-
r = @new_position <=> other.new_position if r.zero?
-
r = @old_element <=> other.old_element if r.zero?
-
r = @new_element <=> other.new_element if r.zero?
-
r
-
end
-
end
-
# -*- ruby encoding: utf-8 -*-
-
-
1
require 'diff/lcs/block'
-
-
# A Hunk is a group of Blocks which overlap because of the context
-
# surrounding each block. (So if we're not using context, every hunk will
-
# contain one block.) Used in the diff program (bin/diff).
-
1
class Diff::LCS::Hunk
-
# Create a hunk using references to both the old and new data, as well as
-
# the piece of data.
-
1
def initialize(data_old, data_new, piece, flag_context, file_length_difference)
-
# At first, a hunk will have just one Block in it
-
@blocks = [ Diff::LCS::Block.new(piece) ]
-
if String.method_defined?(:encoding)
-
@preferred_data_encoding = data_old.fetch(0, data_new.fetch(0,'') ).encoding
-
end
-
@data_old = data_old
-
@data_new = data_new
-
-
before = after = file_length_difference
-
after += @blocks[0].diff_size
-
@file_length_difference = after # The caller must get this manually
-
-
# Save the start & end of each array. If the array doesn't exist (e.g.,
-
# we're only adding items in this block), then figure out the line
-
# number based on the line number of the other file and the current
-
# difference in file lengths.
-
if @blocks[0].remove.empty?
-
a1 = a2 = nil
-
else
-
a1 = @blocks[0].remove[0].position
-
a2 = @blocks[0].remove[-1].position
-
end
-
-
if @blocks[0].insert.empty?
-
b1 = b2 = nil
-
else
-
b1 = @blocks[0].insert[0].position
-
b2 = @blocks[0].insert[-1].position
-
end
-
-
@start_old = a1 || (b1 - before)
-
@start_new = b1 || (a1 + before)
-
@end_old = a2 || (b2 - after)
-
@end_new = b2 || (a2 + after)
-
-
self.flag_context = flag_context
-
end
-
-
1
attr_reader :blocks
-
1
attr_reader :start_old, :start_new
-
1
attr_reader :end_old, :end_new
-
1
attr_reader :file_length_difference
-
-
# Change the "start" and "end" fields to note that context should be added
-
# to this hunk.
-
1
attr_accessor :flag_context
-
1
undef :flag_context=;
-
1
def flag_context=(context) #:nodoc:
-
return if context.nil? or context.zero?
-
-
add_start = (context > @start_old) ? @start_old : context
-
@start_old -= add_start
-
@start_new -= add_start
-
-
if (@end_old + context) > @data_old.size
-
add_end = @data_old.size - @end_old
-
else
-
add_end = context
-
end
-
@end_old += add_end
-
@end_new += add_end
-
end
-
-
# Merges this hunk and the provided hunk together if they overlap. Returns
-
# a truthy value so that if there is no overlap, you can know the merge
-
# was skipped.
-
1
def merge(hunk)
-
if overlaps?(hunk)
-
@start_old = hunk.start_old
-
@start_new = hunk.start_new
-
blocks.unshift(*hunk.blocks)
-
else
-
nil
-
end
-
end
-
1
alias_method :unshift, :merge
-
-
# Determines whether there is an overlap between this hunk and the
-
# provided hunk. This will be true if the difference between the two hunks
-
# start or end positions is within one position of each other.
-
1
def overlaps?(hunk)
-
hunk and (((@start_old - hunk.end_old) <= 1) or
-
((@start_new - hunk.end_new) <= 1))
-
end
-
-
# Returns a diff string based on a format.
-
1
def diff(format)
-
case format
-
when :old
-
old_diff
-
when :unified
-
unified_diff
-
when :context
-
context_diff
-
when :ed
-
self
-
when :reverse_ed, :ed_finish
-
ed_diff(format)
-
else
-
raise "Unknown diff format #{format}."
-
end
-
end
-
-
# Note that an old diff can't have any context. Therefore, we know that
-
# there's only one block in the hunk.
-
1
def old_diff
-
warn "Expecting only one block in an old diff hunk!" if @blocks.size > 1
-
op_act = { "+" => 'a', "-" => 'd', "!" => "c" }
-
-
block = @blocks[0]
-
-
# Calculate item number range. Old diff range is just like a context
-
# diff range, except the ranges are on one line with the action between
-
# them.
-
s = encode("#{context_range(:old)}#{op_act[block.op]}#{context_range(:new)}\n")
-
# If removing anything, just print out all the remove lines in the hunk
-
# which is just all the remove lines in the block.
-
@data_old[@start_old .. @end_old].each { |e| s << encode("< ") + e + encode("\n") } unless block.remove.empty?
-
s << encode("---\n") if block.op == "!"
-
@data_new[@start_new .. @end_new].each { |e| s << encode("> ") + e + encode("\n") } unless block.insert.empty?
-
s
-
end
-
1
private :old_diff
-
-
1
def unified_diff
-
# Calculate item number range.
-
s = encode("@@ -#{unified_range(:old)} +#{unified_range(:new)} @@\n")
-
-
# Outlist starts containing the hunk of the old file. Removing an item
-
# just means putting a '-' in front of it. Inserting an item requires
-
# getting it from the new file and splicing it in. We splice in
-
# +num_added+ items. Remove blocks use +num_added+ because splicing
-
# changed the length of outlist.
-
#
-
# We remove +num_removed+ items. Insert blocks use +num_removed+
-
# because their item numbers -- corresponding to positions in the NEW
-
# file -- don't take removed items into account.
-
lo, hi, num_added, num_removed = @start_old, @end_old, 0, 0
-
-
outlist = @data_old[lo .. hi].map { |e| e.insert(0, encode(' ')) }
-
-
@blocks.each do |block|
-
block.remove.each do |item|
-
op = item.action.to_s # -
-
offset = item.position - lo + num_added
-
outlist[offset][0, 1] = encode(op)
-
num_removed += 1
-
end
-
block.insert.each do |item|
-
op = item.action.to_s # +
-
offset = item.position - @start_new + num_removed
-
outlist[offset, 0] = encode(op) + @data_new[item.position]
-
num_added += 1
-
end
-
end
-
-
s << outlist.join(encode("\n"))
-
end
-
1
private :unified_diff
-
-
1
def context_diff
-
s = encode("***************\n")
-
s << encode("*** #{context_range(:old)} ****\n")
-
r = context_range(:new)
-
-
# Print out file 1 part for each block in context diff format if there
-
# are any blocks that remove items
-
lo, hi = @start_old, @end_old
-
removes = @blocks.select { |e| not e.remove.empty? }
-
if removes
-
outlist = @data_old[lo .. hi].map { |e| e.insert(0, encode(' ')) }
-
-
removes.each do |block|
-
block.remove.each do |item|
-
outlist[item.position - lo][0, 1] = encode(block.op) # - or !
-
end
-
end
-
s << outlist.join("\n")
-
end
-
-
s << encode("\n--- #{r} ----\n")
-
lo, hi = @start_new, @end_new
-
inserts = @blocks.select { |e| not e.insert.empty? }
-
if inserts
-
outlist = @data_new[lo .. hi].collect { |e| e.insert(0, encode(' ')) }
-
inserts.each do |block|
-
block.insert.each do |item|
-
outlist[item.position - lo][0, 1] = encode(block.op) # + or !
-
end
-
end
-
s << outlist.join("\n")
-
end
-
s
-
end
-
1
private :context_diff
-
-
1
def ed_diff(format)
-
op_act = { "+" => 'a', "-" => 'd', "!" => "c" }
-
warn "Expecting only one block in an old diff hunk!" if @blocks.size > 1
-
-
if format == :reverse_ed
-
s = encode("#{op_act[@blocks[0].op]}#{context_range(:old)}\n")
-
else
-
s = encode("#{context_range(:old, ' ')}#{op_act[@blocks[0].op]}\n")
-
end
-
-
unless @blocks[0].insert.empty?
-
@data_new[@start_new .. @end_new].each { |e| s << e + encode("\n") }
-
s << encode(".\n")
-
end
-
s
-
end
-
1
private :ed_diff
-
-
# Generate a range of item numbers to print. Only print 1 number if the
-
# range has only one item in it. Otherwise, it's 'start,end'
-
1
def context_range(mode, op = ',')
-
case mode
-
when :old
-
s, e = (@start_old + 1), (@end_old + 1)
-
when :new
-
s, e = (@start_new + 1), (@end_new + 1)
-
end
-
-
(s < e) ? "#{s}#{op}#{e}" : "#{e}"
-
end
-
1
private :context_range
-
-
# Generate a range of item numbers to print for unified diff. Print number
-
# where block starts, followed by number of lines in the block
-
# (don't print number of lines if it's 1)
-
1
def unified_range(mode)
-
case mode
-
when :old
-
s, e = (@start_old + 1), (@end_old + 1)
-
when :new
-
s, e = (@start_new + 1), (@end_new + 1)
-
end
-
-
length = e - s + 1
-
first = (length < 2) ? e : s # "strange, but correct"
-
(length == 1) ? "#{first}" : "#{first},#{length}"
-
end
-
1
private :unified_range
-
-
1
if String.method_defined?(:encoding)
-
1
def encode(literal, target_encoding = @preferred_data_encoding)
-
literal.encode target_encoding
-
end
-
-
1
def encode_as(string, *args)
-
args.map { |arg| arg.encode(string.encoding) }
-
end
-
else
-
def encode(literal, target_encoding = nil)
-
literal
-
end
-
def encode_as(string, *args)
-
args
-
end
-
end
-
-
1
private :encode
-
1
private :encode_as
-
end
-
# -*- ruby encoding: utf-8 -*-
-
-
1
class << Diff::LCS
-
1
def diff_traversal(method, seq1, seq2, callbacks, &block)
-
callbacks = callbacks_for(callbacks)
-
case method
-
when :diff
-
traverse_sequences(seq1, seq2, callbacks)
-
when :sdiff
-
traverse_balanced(seq1, seq2, callbacks)
-
end
-
callbacks.finish if callbacks.respond_to? :finish
-
-
if block
-
callbacks.diffs.map do |hunk|
-
if hunk.kind_of? Array
-
hunk.map { |hunk_block| block[hunk_block] }
-
else
-
block[hunk]
-
end
-
end
-
else
-
callbacks.diffs
-
end
-
end
-
1
private :diff_traversal
-
end
-
-
1
module Diff::LCS::Internals # :nodoc:
-
end
-
-
1
class << Diff::LCS::Internals
-
# Compute the longest common subsequence between the sequenced
-
# Enumerables +a+ and +b+. The result is an array whose contents is such
-
# that
-
#
-
# result = Diff::LCS::Internals.lcs(a, b)
-
# result.each_with_index do |e, i|
-
# assert_equal(a[i], b[e]) unless e.nil?
-
# end
-
1
def lcs(a, b)
-
a_start = b_start = 0
-
a_finish = a.size - 1
-
b_finish = b.size - 1
-
vector = []
-
-
# Prune off any common elements at the beginning...
-
while ((a_start <= a_finish) and (b_start <= b_finish) and
-
(a[a_start] == b[b_start]))
-
vector[a_start] = b_start
-
a_start += 1
-
b_start += 1
-
end
-
b_start = a_start
-
-
# Now the end...
-
while ((a_start <= a_finish) and (b_start <= b_finish) and
-
(a[a_finish] == b[b_finish]))
-
vector[a_finish] = b_finish
-
a_finish -= 1
-
b_finish -= 1
-
end
-
-
# Now, compute the equivalence classes of positions of elements.
-
b_matches = position_hash(b, b_start..b_finish)
-
-
thresh = []
-
links = []
-
string = a.kind_of?(String)
-
-
(a_start .. a_finish).each do |i|
-
ai = string ? a[i, 1] : a[i]
-
bm = b_matches[ai]
-
k = nil
-
bm.reverse_each do |j|
-
if k and (thresh[k] > j) and (thresh[k - 1] < j)
-
thresh[k] = j
-
else
-
k = replace_next_larger(thresh, j, k)
-
end
-
links[k] = [ (k > 0) ? links[k - 1] : nil, i, j ] unless k.nil?
-
end
-
end
-
-
unless thresh.empty?
-
link = links[thresh.size - 1]
-
while not link.nil?
-
vector[link[1]] = link[2]
-
link = link[0]
-
end
-
end
-
-
vector
-
end
-
-
# This method will analyze the provided patchset to provide a
-
# single-pass normalization (conversion of the array form of
-
# Diff::LCS::Change objects to the object form of same) and detection of
-
# whether the patchset represents changes to be made.
-
1
def analyze_patchset(patchset, depth = 0)
-
raise "Patchset too complex" if depth > 1
-
-
has_changes = false
-
-
# Format:
-
# [ # patchset
-
# # hunk (change)
-
# [ # hunk
-
# # change
-
# ]
-
# ]
-
-
patchset = patchset.map do |hunk|
-
case hunk
-
when Diff::LCS::Change
-
has_changes ||= !hunk.unchanged?
-
hunk
-
when Array
-
# Detect if the 'hunk' is actually an array-format
-
# Change object.
-
if Diff::LCS::Change.valid_action? hunk[0]
-
hunk = Diff::LCS::Change.from_a(hunk)
-
has_changes ||= !hunk.unchanged?
-
hunk
-
else
-
with_changes, hunk = analyze_patchset(hunk, depth + 1)
-
has_changes ||= with_changes
-
hunk.flatten
-
end
-
else
-
raise ArgumentError, "Cannot normalise a hunk of class #{hunk.class}."
-
end
-
end
-
-
[ has_changes, patchset.flatten(1) ]
-
end
-
-
# Examine the patchset and the source to see in which direction the
-
# patch should be applied.
-
#
-
# WARNING: By default, this examines the whole patch, so this could take
-
# some time. This also works better with Diff::LCS::ContextChange or
-
# Diff::LCS::Change as its source, as an array will cause the creation
-
# of one of the above.
-
#
-
# Note: This will be deprecated as a public function in a future release.
-
1
def intuit_diff_direction(src, patchset, limit = nil)
-
string = src.kind_of?(String)
-
count = left_match = left_miss = right_match = right_miss = 0
-
-
patchset.each do |change|
-
count += 1
-
-
case change
-
when Diff::LCS::ContextChange
-
le = string ? src[change.old_position, 1] : src[change.old_position]
-
re = string ? src[change.new_position, 1] : src[change.new_position]
-
-
case change.action
-
when '-' # Remove details from the old string
-
if le == change.old_element
-
left_match += 1
-
else
-
left_miss += 1
-
end
-
when '+'
-
if re == change.new_element
-
right_match += 1
-
else
-
right_miss += 1
-
end
-
when '='
-
left_miss += 1 if le != change.old_element
-
right_miss += 1 if re != change.new_element
-
when '!'
-
if le == change.old_element
-
left_match += 1
-
else
-
if re == change.new_element
-
right_match += 1
-
else
-
left_miss += 1
-
right_miss += 1
-
end
-
end
-
end
-
when Diff::LCS::Change
-
# With a simplistic change, we can't tell the difference between
-
# the left and right on '!' actions, so we ignore those. On '='
-
# actions, if there's a miss, we miss both left and right.
-
element = string ? src[change.position, 1] : src[change.position]
-
-
case change.action
-
when '-'
-
if element == change.element
-
left_match += 1
-
else
-
left_miss += 1
-
end
-
when '+'
-
if element == change.element
-
right_match += 1
-
else
-
right_miss += 1
-
end
-
when '='
-
if element != change.element
-
left_miss += 1
-
right_miss += 1
-
end
-
end
-
end
-
-
break if (not limit.nil?) && (count > limit)
-
end
-
-
no_left = (left_match == 0) && (left_miss > 0)
-
no_right = (right_match == 0) && (right_miss > 0)
-
-
case [no_left, no_right]
-
when [false, true]
-
:patch
-
when [true, false]
-
:unpatch
-
else
-
case left_match <=> right_match
-
when 1
-
:patch
-
when -1
-
:unpatch
-
else
-
raise "The provided patchset does not appear to apply to the provided value as either source or destination value."
-
end
-
end
-
end
-
-
# Find the place at which +value+ would normally be inserted into the
-
# Enumerable. If that place is already occupied by +value+, do nothing
-
# and return +nil+. If the place does not exist (i.e., it is off the end
-
# of the Enumerable), add it to the end. Otherwise, replace the element
-
# at that point with +value+. It is assumed that the Enumerable's values
-
# are numeric.
-
#
-
# This operation preserves the sort order.
-
1
def replace_next_larger(enum, value, last_index = nil)
-
# Off the end?
-
if enum.empty? or (value > enum[-1])
-
enum << value
-
return enum.size - 1
-
end
-
-
# Binary search for the insertion point
-
last_index ||= enum.size
-
first_index = 0
-
while (first_index <= last_index)
-
i = (first_index + last_index) >> 1
-
-
found = enum[i]
-
-
if value == found
-
return nil
-
elsif value > found
-
first_index = i + 1
-
else
-
last_index = i - 1
-
end
-
end
-
-
# The insertion point is in first_index; overwrite the next larger
-
# value.
-
enum[first_index] = value
-
return first_index
-
end
-
1
private :replace_next_larger
-
-
# If +vector+ maps the matching elements of another collection onto this
-
# Enumerable, compute the inverse of +vector+ that maps this Enumerable
-
# onto the collection. (Currently unused.)
-
1
def inverse_vector(a, vector)
-
inverse = a.dup
-
(0...vector.size).each do |i|
-
inverse[vector[i]] = i unless vector[i].nil?
-
end
-
inverse
-
end
-
1
private :inverse_vector
-
-
# Returns a hash mapping each element of an Enumerable to the set of
-
# positions it occupies in the Enumerable, optionally restricted to the
-
# elements specified in the range of indexes specified by +interval+.
-
1
def position_hash(enum, interval)
-
string = enum.kind_of?(String)
-
hash = Hash.new { |h, k| h[k] = [] }
-
interval.each do |i|
-
k = string ? enum[i, 1] : enum[i]
-
hash[k] << i
-
end
-
hash
-
end
-
1
private :position_hash
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
##
-
## an implementation of eRuby
-
##
-
## ex.
-
## input = <<'END'
-
## <ul>
-
## <% for item in @list %>
-
## <li><%= item %>
-
## <%== item %></li>
-
## <% end %>
-
## </ul>
-
## END
-
## list = ['<aaa>', 'b&b', '"ccc"']
-
## eruby = Erubis::Eruby.new(input)
-
## puts "--- code ---"
-
## puts eruby.src
-
## puts "--- result ---"
-
## context = Erubis::Context.new() # or new(:list=>list)
-
## context[:list] = list
-
## puts eruby.evaluate(context)
-
##
-
## result:
-
## --- source ---
-
## _buf = ''; _buf << '<ul>
-
## '; for item in @list
-
## _buf << ' <li>'; _buf << ( item ).to_s; _buf << '
-
## '; _buf << ' '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</li>
-
## '; end
-
## _buf << '</ul>
-
## ';
-
## _buf.to_s
-
## --- result ---
-
## <ul>
-
## <li><aaa>
-
## <aaa></li>
-
## <li>b&b
-
## b&b</li>
-
## <li>"ccc"
-
## "ccc"</li>
-
## </ul>
-
##
-
-
-
1
module Erubis
-
1
VERSION = ('$Release: 2.7.0 $' =~ /([.\d]+)/) && $1
-
end
-
-
1
require 'erubis/engine'
-
#require 'erubis/generator'
-
#require 'erubis/converter'
-
#require 'erubis/evaluator'
-
#require 'erubis/error'
-
#require 'erubis/context'
-
#requier 'erubis/util'
-
1
require 'erubis/helper'
-
1
require 'erubis/enhancer'
-
#require 'erubis/tiny'
-
1
require 'erubis/engine/eruby'
-
#require 'erubis/engine/enhanced' # enhanced eruby engines
-
#require 'erubis/engine/optimized' # generates optimized ruby code
-
#require 'erubis/engine/ephp'
-
#require 'erubis/engine/ec'
-
#require 'erubis/engine/ejava'
-
#require 'erubis/engine/escheme'
-
#require 'erubis/engine/eperl'
-
#require 'erubis/engine/ejavascript'
-
-
1
require 'erubis/local-setting'
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
-
1
module Erubis
-
-
-
##
-
## context object for Engine#evaluate
-
##
-
## ex.
-
## template = <<'END'
-
## Hello <%= @user %>!
-
## <% for item in @list %>
-
## - <%= item %>
-
## <% end %>
-
## END
-
##
-
## context = Erubis::Context.new(:user=>'World', :list=>['a','b','c'])
-
## # or
-
## # context = Erubis::Context.new
-
## # context[:user] = 'World'
-
## # context[:list] = ['a', 'b', 'c']
-
##
-
## eruby = Erubis::Eruby.new(template)
-
## print eruby.evaluate(context)
-
##
-
1
class Context
-
1
include Enumerable
-
-
1
def initialize(hash=nil)
-
hash.each do |name, value|
-
self[name] = value
-
end if hash
-
end
-
-
1
def [](key)
-
return instance_variable_get("@#{key}")
-
end
-
-
1
def []=(key, value)
-
return instance_variable_set("@#{key}", value)
-
end
-
-
1
def keys
-
return instance_variables.collect { |name| name[1..-1] }
-
end
-
-
1
def each
-
instance_variables.each do |name|
-
key = name[1..-1]
-
value = instance_variable_get(name)
-
yield(key, value)
-
end
-
end
-
-
1
def to_hash
-
hash = {}
-
self.keys.each { |key| hash[key] = self[key] }
-
return hash
-
end
-
-
1
def update(context_or_hash)
-
arg = context_or_hash
-
if arg.is_a?(Hash)
-
arg.each do |key, val|
-
self[key] = val
-
end
-
else
-
arg.instance_variables.each do |varname|
-
key = varname[1..-1]
-
val = arg.instance_variable_get(varname)
-
self[key] = val
-
end
-
end
-
end
-
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
1
require 'erubis/util'
-
-
1
module Erubis
-
-
-
##
-
## convert
-
##
-
1
module Converter
-
-
1
attr_accessor :preamble, :postamble, :escape
-
-
1
def self.supported_properties # :nodoc:
-
return [
-
[:preamble, nil, "preamble (no preamble when false)"],
-
[:postamble, nil, "postamble (no postamble when false)"],
-
[:escape, nil, "escape expression or not in default"],
-
]
-
end
-
-
1
def init_converter(properties={})
-
@preamble = properties[:preamble]
-
@postamble = properties[:postamble]
-
@escape = properties[:escape]
-
end
-
-
## convert input string into target language
-
1
def convert(input)
-
codebuf = "" # or []
-
@preamble.nil? ? add_preamble(codebuf) : (@preamble && (codebuf << @preamble))
-
convert_input(codebuf, input)
-
@postamble.nil? ? add_postamble(codebuf) : (@postamble && (codebuf << @postamble))
-
@_proc = nil # clear cached proc object
-
return codebuf # or codebuf.join()
-
end
-
-
1
protected
-
-
##
-
## detect spaces at beginning of line
-
##
-
1
def detect_spaces_at_bol(text, is_bol)
-
lspace = nil
-
if text.empty?
-
lspace = "" if is_bol
-
elsif text[-1] == ?\n
-
lspace = ""
-
else
-
rindex = text.rindex(?\n)
-
if rindex
-
s = text[rindex+1..-1]
-
if s =~ /\A[ \t]*\z/
-
lspace = s
-
#text = text[0..rindex]
-
text[rindex+1..-1] = ''
-
end
-
else
-
if is_bol && text =~ /\A[ \t]*\z/
-
#lspace = text
-
#text = nil
-
lspace = text.dup
-
text[0..-1] = ''
-
end
-
end
-
end
-
return lspace
-
end
-
-
##
-
## (abstract) convert input to code
-
##
-
1
def convert_input(codebuf, input)
-
not_implemented
-
end
-
-
end
-
-
-
1
module Basic
-
end
-
-
-
##
-
## basic converter which supports '<% ... %>' notation.
-
##
-
1
module Basic::Converter
-
1
include Erubis::Converter
-
-
1
def self.supported_properties # :nodoc:
-
return [
-
[:pattern, '<% %>', "embed pattern"],
-
[:trim, true, "trim spaces around <% ... %>"],
-
]
-
end
-
-
1
attr_accessor :pattern, :trim
-
-
1
def init_converter(properties={})
-
super(properties)
-
@pattern = properties[:pattern]
-
@trim = properties[:trim] != false
-
end
-
-
1
protected
-
-
## return regexp of pattern to parse eRuby script
-
1
def pattern_regexp(pattern)
-
1
@prefix, @postfix = pattern.split() # '<% %>' => '<%', '%>'
-
#return /(.*?)(^[ \t]*)?#{@prefix}(=+|\#)?(.*?)-?#{@postfix}([ \t]*\r?\n)?/m
-
#return /(^[ \t]*)?#{@prefix}(=+|\#)?(.*?)-?#{@postfix}([ \t]*\r?\n)?/m
-
1
return /#{@prefix}(=+|-|\#|%)?(.*?)([-=])?#{@postfix}([ \t]*\r?\n)?/m
-
end
-
1
module_function :pattern_regexp
-
-
#DEFAULT_REGEXP = /(.*?)(^[ \t]*)?<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m
-
#DEFAULT_REGEXP = /(^[ \t]*)?<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m
-
#DEFAULT_REGEXP = /<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m
-
1
DEFAULT_REGEXP = pattern_regexp('<% %>')
-
-
1
public
-
-
1
def convert_input(src, input)
-
pat = @pattern
-
regexp = pat.nil? || pat == '<% %>' ? DEFAULT_REGEXP : pattern_regexp(pat)
-
pos = 0
-
is_bol = true # is beginning of line
-
input.scan(regexp) do |indicator, code, tailch, rspace|
-
match = Regexp.last_match()
-
len = match.begin(0) - pos
-
text = input[pos, len]
-
pos = match.end(0)
-
ch = indicator ? indicator[0] : nil
-
lspace = ch == ?= ? nil : detect_spaces_at_bol(text, is_bol)
-
is_bol = rspace ? true : false
-
add_text(src, text) if text && !text.empty?
-
## * when '<%= %>', do nothing
-
## * when '<% %>' or '<%# %>', delete spaces iff only spaces are around '<% %>'
-
if ch == ?= # <%= %>
-
rspace = nil if tailch && !tailch.empty?
-
add_text(src, lspace) if lspace
-
add_expr(src, code, indicator)
-
add_text(src, rspace) if rspace
-
elsif ch == ?\# # <%# %>
-
n = code.count("\n") + (rspace ? 1 : 0)
-
if @trim && lspace && rspace
-
add_stmt(src, "\n" * n)
-
else
-
add_text(src, lspace) if lspace
-
add_stmt(src, "\n" * n)
-
add_text(src, rspace) if rspace
-
end
-
elsif ch == ?% # <%% %>
-
s = "#{lspace}#{@prefix||='<%'}#{code}#{tailch}#{@postfix||='%>'}#{rspace}"
-
add_text(src, s)
-
else # <% %>
-
if @trim && lspace && rspace
-
add_stmt(src, "#{lspace}#{code}#{rspace}")
-
else
-
add_text(src, lspace) if lspace
-
add_stmt(src, code)
-
add_text(src, rspace) if rspace
-
end
-
end
-
end
-
#rest = $' || input # ruby1.8
-
rest = pos == 0 ? input : input[pos..-1] # ruby1.9
-
add_text(src, rest)
-
end
-
-
## add expression code to src
-
1
def add_expr(src, code, indicator)
-
case indicator
-
when '='
-
@escape ? add_expr_escaped(src, code) : add_expr_literal(src, code)
-
when '=='
-
@escape ? add_expr_literal(src, code) : add_expr_escaped(src, code)
-
when '==='
-
add_expr_debug(src, code)
-
end
-
end
-
-
end
-
-
-
1
module PI
-
end
-
-
##
-
## Processing Instructions (PI) converter for XML.
-
## this class converts '<?rb ... ?>' and '${...}' notation.
-
##
-
1
module PI::Converter
-
1
include Erubis::Converter
-
-
1
def self.desc # :nodoc:
-
"use processing instructions (PI) instead of '<% %>'"
-
end
-
-
1
def self.supported_properties # :nodoc:
-
return [
-
[:trim, true, "trim spaces around <% ... %>"],
-
[:pi, 'rb', "PI (Processing Instrunctions) name"],
-
[:embchar, '@', "char for embedded expression pattern('@{...}@')"],
-
[:pattern, '<% %>', "embed pattern"],
-
]
-
end
-
-
1
attr_accessor :pi, :prefix
-
-
1
def init_converter(properties={})
-
super(properties)
-
@trim = properties.fetch(:trim, true)
-
@pi = properties[:pi] if properties[:pi]
-
@embchar = properties[:embchar] || '@'
-
@pattern = properties[:pattern]
-
@pattern = '<% %>' if @pattern.nil? #|| @pattern == true
-
end
-
-
1
def convert(input)
-
code = super(input)
-
return @header || @footer ? "#{@header}#{code}#{@footer}" : code
-
end
-
-
1
protected
-
-
1
def convert_input(codebuf, input)
-
unless @regexp
-
@pi ||= 'e'
-
ch = Regexp.escape(@embchar)
-
if @pattern
-
left, right = @pattern.split(' ')
-
@regexp = /<\?#{@pi}(?:-(\w+))?(\s.*?)\?>([ \t]*\r?\n)?|#{ch}(!*)?\{(.*?)\}#{ch}|#{left}(=+)(.*?)#{right}/m
-
else
-
@regexp = /<\?#{@pi}(?:-(\w+))?(\s.*?)\?>([ \t]*\r?\n)?|#{ch}(!*)?\{(.*?)\}#{ch}/m
-
end
-
end
-
#
-
is_bol = true
-
pos = 0
-
input.scan(@regexp) do |pi_arg, stmt, rspace,
-
indicator1, expr1, indicator2, expr2|
-
match = Regexp.last_match
-
len = match.begin(0) - pos
-
text = input[pos, len]
-
pos = match.end(0)
-
lspace = stmt ? detect_spaces_at_bol(text, is_bol) : nil
-
is_bol = stmt && rspace ? true : false
-
add_text(codebuf, text) # unless text.empty?
-
#
-
if stmt
-
if @trim && lspace && rspace
-
add_pi_stmt(codebuf, "#{lspace}#{stmt}#{rspace}", pi_arg)
-
else
-
add_text(codebuf, lspace) if lspace
-
add_pi_stmt(codebuf, stmt, pi_arg)
-
add_text(codebuf, rspace) if rspace
-
end
-
else
-
add_pi_expr(codebuf, expr1 || expr2, indicator1 || indicator2)
-
end
-
end
-
#rest = $' || input # ruby1.8
-
rest = pos == 0 ? input : input[pos..-1] # ruby1.9
-
add_text(codebuf, rest)
-
end
-
-
#--
-
#def convert_input(codebuf, input)
-
# parse_stmts(codebuf, input)
-
# #parse_stmts2(codebuf, input)
-
#end
-
#
-
#def parse_stmts(codebuf, input)
-
# #regexp = pattern_regexp(@pattern)
-
# @pi ||= 'e'
-
# @stmt_pattern ||= /<\?#{@pi}(?:-(\w+))?(\s.*?)\?>([ \t]*\r?\n)?/m
-
# is_bol = true
-
# pos = 0
-
# input.scan(@stmt_pattern) do |pi_arg, code, rspace|
-
# match = Regexp.last_match
-
# len = match.begin(0) - pos
-
# text = input[pos, len]
-
# pos = match.end(0)
-
# lspace = detect_spaces_at_bol(text, is_bol)
-
# is_bol = rspace ? true : false
-
# parse_exprs(codebuf, text) # unless text.empty?
-
# if @trim && lspace && rspace
-
# add_pi_stmt(codebuf, "#{lspace}#{code}#{rspace}", pi_arg)
-
# else
-
# add_text(codebuf, lspace)
-
# add_pi_stmt(codebuf, code, pi_arg)
-
# add_text(codebuf, rspace)
-
# end
-
# end
-
# rest = $' || input
-
# parse_exprs(codebuf, rest)
-
#end
-
#
-
#def parse_exprs(codebuf, input)
-
# unless @expr_pattern
-
# ch = Regexp.escape(@embchar)
-
# if @pattern
-
# left, right = @pattern.split(' ')
-
# @expr_pattern = /#{ch}(!*)?\{(.*?)\}#{ch}|#{left}(=+)(.*?)#{right}/
-
# else
-
# @expr_pattern = /#{ch}(!*)?\{(.*?)\}#{ch}/
-
# end
-
# end
-
# pos = 0
-
# input.scan(@expr_pattern) do |indicator1, code1, indicator2, code2|
-
# indicator = indicator1 || indicator2
-
# code = code1 || code2
-
# match = Regexp.last_match
-
# len = match.begin(0) - pos
-
# text = input[pos, len]
-
# pos = match.end(0)
-
# add_text(codebuf, text) # unless text.empty?
-
# add_pi_expr(codebuf, code, indicator)
-
# end
-
# rest = $' || input
-
# add_text(codebuf, rest)
-
#end
-
#++
-
-
1
def add_pi_stmt(codebuf, code, pi_arg) # :nodoc:
-
case pi_arg
-
when nil ; add_stmt(codebuf, code)
-
when 'header' ; @header = code
-
when 'footer' ; @footer = code
-
when 'comment'; add_stmt(codebuf, "\n" * code.count("\n"))
-
when 'value' ; add_expr_literal(codebuf, code)
-
else ; add_stmt(codebuf, code)
-
end
-
end
-
-
1
def add_pi_expr(codebuf, code, indicator) # :nodoc:
-
case indicator
-
when nil, '', '==' # @{...}@ or <%== ... %>
-
@escape == false ? add_expr_literal(codebuf, code) : add_expr_escaped(codebuf, code)
-
when '!', '=' # @!{...}@ or <%= ... %>
-
@escape == false ? add_expr_escaped(codebuf, code) : add_expr_literal(codebuf, code)
-
when '!!', '===' # @!!{...}@ or <%=== ... %>
-
add_expr_debug(codebuf, code)
-
else
-
# ignore
-
end
-
end
-
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
-
1
require 'erubis/generator'
-
1
require 'erubis/converter'
-
1
require 'erubis/evaluator'
-
1
require 'erubis/context'
-
-
-
1
module Erubis
-
-
-
##
-
## (abstract) abstract engine class.
-
## subclass must include evaluator and converter module.
-
##
-
1
class Engine
-
#include Evaluator
-
#include Converter
-
#include Generator
-
-
1
def initialize(input=nil, properties={})
-
#@input = input
-
init_generator(properties)
-
init_converter(properties)
-
init_evaluator(properties)
-
@src = convert(input) if input
-
end
-
-
-
##
-
## convert input string and set it to @src
-
##
-
1
def convert!(input)
-
@src = convert(input)
-
end
-
-
-
##
-
## load file, write cache file, and return engine object.
-
## this method create code cache file automatically.
-
## cachefile name can be specified with properties[:cachename],
-
## or filname + 'cache' is used as default.
-
##
-
1
def self.load_file(filename, properties={})
-
cachename = properties[:cachename] || (filename + '.cache')
-
properties[:filename] = filename
-
timestamp = File.mtime(filename)
-
if test(?f, cachename) && timestamp == File.mtime(cachename)
-
engine = self.new(nil, properties)
-
engine.src = File.read(cachename)
-
else
-
input = File.open(filename, 'rb') {|f| f.read }
-
engine = self.new(input, properties)
-
tmpname = cachename + rand().to_s[1,8]
-
File.open(tmpname, 'wb') {|f| f.write(engine.src) }
-
File.rename(tmpname, cachename)
-
File.utime(timestamp, timestamp, cachename)
-
end
-
engine.src.untaint # ok?
-
return engine
-
end
-
-
-
##
-
## helper method to convert and evaluate input text with context object.
-
## context may be Binding, Hash, or Object.
-
##
-
1
def process(input, context=nil, filename=nil)
-
code = convert(input)
-
filename ||= '(erubis)'
-
if context.is_a?(Binding)
-
return eval(code, context, filename)
-
else
-
context = Context.new(context) if context.is_a?(Hash)
-
return context.instance_eval(code, filename)
-
end
-
end
-
-
-
##
-
## helper method evaluate Proc object with contect object.
-
## context may be Binding, Hash, or Object.
-
##
-
1
def process_proc(proc_obj, context=nil, filename=nil)
-
if context.is_a?(Binding)
-
filename ||= '(erubis)'
-
return eval(proc_obj, context, filename)
-
else
-
context = Context.new(context) if context.is_a?(Hash)
-
return context.instance_eval(&proc_obj)
-
end
-
end
-
-
-
end # end of class Engine
-
-
-
##
-
## (abstract) base engine class for Eruby, Eperl, Ejava, and so on.
-
## subclass must include generator.
-
##
-
1
class Basic::Engine < Engine
-
1
include Evaluator
-
1
include Basic::Converter
-
1
include Generator
-
end
-
-
-
1
class PI::Engine < Engine
-
1
include Evaluator
-
1
include PI::Converter
-
1
include Generator
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
-
1
module Erubis
-
-
-
##
-
## switch '<%= ... %>' to escaped and '<%== ... %>' to unescaped
-
##
-
## ex.
-
## class XmlEruby < Eruby
-
## include EscapeEnhancer
-
## end
-
##
-
## this is language-indenedent.
-
##
-
1
module EscapeEnhancer
-
-
1
def self.desc # :nodoc:
-
"switch '<%= %>' to escaped and '<%== %>' to unescaped"
-
end
-
-
#--
-
#def self.included(klass)
-
# klass.class_eval <<-END
-
# alias _add_expr_literal add_expr_literal
-
# alias _add_expr_escaped add_expr_escaped
-
# alias add_expr_literal _add_expr_escaped
-
# alias add_expr_escaped _add_expr_literal
-
# END
-
#end
-
#++
-
-
1
def add_expr(src, code, indicator)
-
case indicator
-
when '='
-
@escape ? add_expr_literal(src, code) : add_expr_escaped(src, code)
-
when '=='
-
@escape ? add_expr_escaped(src, code) : add_expr_literal(src, code)
-
when '==='
-
add_expr_debug(src, code)
-
end
-
end
-
-
end
-
-
-
#--
-
## (obsolete)
-
#module FastEnhancer
-
#end
-
#++
-
-
-
##
-
## use $stdout instead of string
-
##
-
## this is only for Eruby.
-
##
-
1
module StdoutEnhancer
-
-
1
def self.desc # :nodoc:
-
"use $stdout instead of array buffer or string buffer"
-
end
-
-
1
def add_preamble(src)
-
src << "#{@bufvar} = $stdout;"
-
end
-
-
1
def add_postamble(src)
-
src << "\n''\n"
-
end
-
-
end
-
-
-
##
-
## use print statement instead of '_buf << ...'
-
##
-
## this is only for Eruby.
-
##
-
1
module PrintOutEnhancer
-
-
1
def self.desc # :nodoc:
-
"use print statement instead of '_buf << ...'"
-
end
-
-
1
def add_preamble(src)
-
end
-
-
1
def add_text(src, text)
-
src << " print '#{escape_text(text)}';" unless text.empty?
-
end
-
-
1
def add_expr_literal(src, code)
-
src << " print((#{code}).to_s);"
-
end
-
-
1
def add_expr_escaped(src, code)
-
src << " print #{escaped_expr(code)};"
-
end
-
-
1
def add_postamble(src)
-
src << "\n" unless src[-1] == ?\n
-
end
-
-
end
-
-
-
##
-
## enable print function
-
##
-
## Notice: use Eruby#evaluate() and don't use Eruby#result()
-
## to be enable print function.
-
##
-
## this is only for Eruby.
-
##
-
1
module PrintEnabledEnhancer
-
-
1
def self.desc # :nodoc:
-
"enable to use print function in '<% %>'"
-
end
-
-
1
def add_preamble(src)
-
src << "@_buf = "
-
super
-
end
-
-
1
def print(*args)
-
args.each do |arg|
-
@_buf << arg.to_s
-
end
-
end
-
-
1
def evaluate(context=nil)
-
_src = @src
-
if context.is_a?(Hash)
-
context.each do |key, val| instance_variable_set("@#{key}", val) end
-
elsif context
-
context.instance_variables.each do |name|
-
instance_variable_set(name, context.instance_variable_get(name))
-
end
-
end
-
return instance_eval(_src, (@filename || '(erubis)'))
-
end
-
-
end
-
-
-
##
-
## return array instead of string
-
##
-
## this is only for Eruby.
-
##
-
1
module ArrayEnhancer
-
-
1
def self.desc # :nodoc:
-
"return array instead of string"
-
end
-
-
1
def add_preamble(src)
-
src << "#{@bufvar} = [];"
-
end
-
-
1
def add_postamble(src)
-
src << "\n" unless src[-1] == ?\n
-
src << "#{@bufvar}\n"
-
end
-
-
end
-
-
-
##
-
## use an Array object as buffer (included in Eruby by default)
-
##
-
## this is only for Eruby.
-
##
-
1
module ArrayBufferEnhancer
-
-
1
def self.desc # :nodoc:
-
"use an Array object for buffering (included in Eruby class)"
-
end
-
-
1
def add_preamble(src)
-
src << "_buf = [];"
-
end
-
-
1
def add_postamble(src)
-
src << "\n" unless src[-1] == ?\n
-
src << "_buf.join\n"
-
end
-
-
end
-
-
-
##
-
## use String class for buffering
-
##
-
## this is only for Eruby.
-
##
-
1
module StringBufferEnhancer
-
-
1
def self.desc # :nodoc:
-
"use a String object for buffering"
-
end
-
-
1
def add_preamble(src)
-
src << "#{@bufvar} = '';"
-
end
-
-
1
def add_postamble(src)
-
src << "\n" unless src[-1] == ?\n
-
src << "#{@bufvar}.to_s\n"
-
end
-
-
end
-
-
-
##
-
## use StringIO class for buffering
-
##
-
## this is only for Eruby.
-
##
-
1
module StringIOEnhancer # :nodoc:
-
-
1
def self.desc # :nodoc:
-
"use a StringIO object for buffering"
-
end
-
-
1
def add_preamble(src)
-
src << "#{@bufvar} = StringIO.new;"
-
end
-
-
1
def add_postamble(src)
-
src << "\n" unless src[-1] == ?\n
-
src << "#{@bufvar}.string\n"
-
end
-
-
end
-
-
-
##
-
## set buffer variable name to '_erbout' as well as '_buf'
-
##
-
## this is only for Eruby.
-
##
-
1
module ErboutEnhancer
-
-
1
def self.desc # :nodoc:
-
"set '_erbout = _buf = \"\";' to be compatible with ERB."
-
end
-
-
1
def add_preamble(src)
-
src << "_erbout = #{@bufvar} = '';"
-
end
-
-
1
def add_postamble(src)
-
src << "\n" unless src[-1] == ?\n
-
src << "#{@bufvar}.to_s\n"
-
end
-
-
end
-
-
-
##
-
## remove text and leave code, especially useful when debugging.
-
##
-
## ex.
-
## $ erubis -s -E NoText file.eruby | more
-
##
-
## this is language independent.
-
##
-
1
module NoTextEnhancer
-
-
1
def self.desc # :nodoc:
-
"remove text and leave code (useful when debugging)"
-
end
-
-
1
def add_text(src, text)
-
src << ("\n" * text.count("\n"))
-
if text[-1] != ?\n
-
text =~ /^(.*?)\z/
-
src << (' ' * $1.length)
-
end
-
end
-
-
end
-
-
-
##
-
## remove code and leave text, especially useful when validating HTML tags.
-
##
-
## ex.
-
## $ erubis -s -E NoCode file.eruby | tidy -errors
-
##
-
## this is language independent.
-
##
-
1
module NoCodeEnhancer
-
-
1
def self.desc # :nodoc:
-
"remove code and leave text (useful when validating HTML)"
-
end
-
-
1
def add_preamble(src)
-
end
-
-
1
def add_postamble(src)
-
end
-
-
1
def add_text(src, text)
-
src << text
-
end
-
-
1
def add_expr(src, code, indicator)
-
src << "\n" * code.count("\n")
-
end
-
-
1
def add_stmt(src, code)
-
src << "\n" * code.count("\n")
-
end
-
-
end
-
-
-
##
-
## get convert faster, but spaces around '<%...%>' are not trimmed.
-
##
-
## this is language-independent.
-
##
-
1
module SimplifyEnhancer
-
-
1
def self.desc # :nodoc:
-
"get convert faster but leave spaces around '<% %>'"
-
end
-
-
#DEFAULT_REGEXP = /(^[ \t]*)?<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m
-
1
SIMPLE_REGEXP = /<%(=+|\#)?(.*?)-?%>/m
-
-
1
def convert(input)
-
src = ""
-
add_preamble(src)
-
#regexp = pattern_regexp(@pattern)
-
pos = 0
-
input.scan(SIMPLE_REGEXP) do |indicator, code|
-
match = Regexp.last_match
-
index = match.begin(0)
-
text = input[pos, index - pos]
-
pos = match.end(0)
-
add_text(src, text)
-
if !indicator # <% %>
-
add_stmt(src, code)
-
elsif indicator[0] == ?\# # <%# %>
-
n = code.count("\n")
-
add_stmt(src, "\n" * n)
-
else # <%= %>
-
add_expr(src, code, indicator)
-
end
-
end
-
#rest = $' || input # ruby1.8
-
rest = pos == 0 ? input : input[pos..-1] # ruby1.9
-
add_text(src, rest)
-
add_postamble(src)
-
return src
-
end
-
-
end
-
-
-
##
-
## enable to use other embedded expression pattern (default is '\[= =\]').
-
##
-
## notice! this is an experimental. spec may change in the future.
-
##
-
## ex.
-
## input = <<END
-
## <% for item in list %>
-
## <%= item %> : <%== item %>
-
## [= item =] : [== item =]
-
## <% end %>
-
## END
-
##
-
## class BiPatternEruby
-
## include BiPatternEnhancer
-
## end
-
## eruby = BiPatternEruby.new(input, :bipattern=>'\[= =\]')
-
## list = ['<a>', 'b&b', '"c"']
-
## print eruby.result(binding())
-
##
-
## ## output
-
## <a> : <a>
-
## <a> : <a>
-
## b&b : b&b
-
## b&b : b&b
-
## "c" : "c"
-
## "c" : "c"
-
##
-
## this is language independent.
-
##
-
1
module BiPatternEnhancer
-
-
1
def self.desc # :nodoc:
-
"another embedded expression pattern (default '\[= =\]')."
-
end
-
-
1
def initialize(input, properties={})
-
self.bipattern = properties[:bipattern] # or '\$\{ \}'
-
super
-
end
-
-
## when pat is nil then '\[= =\]' is used
-
1
def bipattern=(pat) # :nodoc:
-
@bipattern = pat || '\[= =\]'
-
pre, post = @bipattern.split()
-
@bipattern_regexp = /(.*?)#{pre}(=*)(.*?)#{post}/m
-
end
-
-
1
def add_text(src, text)
-
return unless text
-
m = nil
-
text.scan(@bipattern_regexp) do |txt, indicator, code|
-
m = Regexp.last_match
-
super(src, txt)
-
add_expr(src, code, '=' + indicator)
-
end
-
#rest = $' || text # ruby1.8
-
rest = m ? text[m.end(0)..-1] : text # ruby1.9
-
super(src, rest)
-
end
-
-
end
-
-
-
##
-
## regards lines starting with '^[ \t]*%' as program code
-
##
-
## in addition you can specify prefix character (default '%')
-
##
-
## this is language-independent.
-
##
-
1
module PrefixedLineEnhancer
-
-
1
def self.desc # :nodoc:
-
"regard lines matched to '^[ \t]*%' as program code"
-
end
-
-
1
def init_generator(properties={})
-
super
-
@prefixchar = properties[:prefixchar]
-
end
-
-
1
def add_text(src, text)
-
unless @prefixrexp
-
@prefixchar ||= '%'
-
@prefixrexp = Regexp.compile("^([ \\t]*)\\#{@prefixchar}(.*?\\r?\\n)")
-
end
-
pos = 0
-
text2 = ''
-
text.scan(@prefixrexp) do
-
space = $1
-
line = $2
-
space, line = '', $1 unless $2
-
match = Regexp.last_match
-
len = match.begin(0) - pos
-
str = text[pos, len]
-
pos = match.end(0)
-
if text2.empty?
-
text2 = str
-
else
-
text2 << str
-
end
-
if line[0, 1] == @prefixchar
-
text2 << space << line
-
else
-
super(src, text2)
-
text2 = ''
-
add_stmt(src, space + line)
-
end
-
end
-
#rest = pos == 0 ? text : $' # ruby1.8
-
rest = pos == 0 ? text : text[pos..-1] # ruby1.9
-
unless text2.empty?
-
text2 << rest if rest
-
rest = text2
-
end
-
super(src, rest)
-
end
-
-
end
-
-
-
##
-
## regards lines starting with '%' as program code
-
##
-
## this is for compatibility to eruby and ERB.
-
##
-
## this is language-independent.
-
##
-
1
module PercentLineEnhancer
-
1
include PrefixedLineEnhancer
-
-
1
def self.desc # :nodoc:
-
"regard lines starting with '%' as program code"
-
end
-
-
#--
-
#def init_generator(properties={})
-
# super
-
# @prefixchar = '%'
-
# @prefixrexp = /^\%(.*?\r?\n)/
-
#end
-
#++
-
-
1
def add_text(src, text)
-
unless @prefixrexp
-
@prefixchar = '%'
-
@prefixrexp = /^\%(.*?\r?\n)/
-
end
-
super(src, text)
-
end
-
-
end
-
-
-
##
-
## [experimental] allow header and footer in eRuby script
-
##
-
## ex.
-
## ====================
-
## ## without header and footer
-
## $ cat ex1.eruby
-
## <% def list_items(list) %>
-
## <% for item in list %>
-
## <li><%= item %></li>
-
## <% end %>
-
## <% end %>
-
##
-
## $ erubis -s ex1.eruby
-
## _buf = []; def list_items(list)
-
## ; for item in list
-
## ; _buf << '<li>'; _buf << ( item ).to_s; _buf << '</li>
-
## '; end
-
## ; end
-
## ;
-
## _buf.join
-
##
-
## ## with header and footer
-
## $ cat ex2.eruby
-
## <!--#header:
-
## def list_items(list)
-
## #-->
-
## <% for item in list %>
-
## <li><%= item %></li>
-
## <% end %>
-
## <!--#footer:
-
## end
-
## #-->
-
##
-
## $ erubis -s -c HeaderFooterEruby ex4.eruby
-
##
-
## def list_items(list)
-
## _buf = []; _buf << '
-
## '; for item in list
-
## ; _buf << '<li>'; _buf << ( item ).to_s; _buf << '</li>
-
## '; end
-
## ; _buf << '
-
## ';
-
## _buf.join
-
## end
-
##
-
## ====================
-
##
-
## this is language-independent.
-
##
-
1
module HeaderFooterEnhancer
-
-
1
def self.desc # :nodoc:
-
"allow header/footer in document (ex. '<!--#header: #-->')"
-
end
-
-
1
HEADER_FOOTER_PATTERN = /(.*?)(^[ \t]*)?<!--\#(\w+):(.*?)\#-->([ \t]*\r?\n)?/m
-
-
1
def add_text(src, text)
-
m = nil
-
text.scan(HEADER_FOOTER_PATTERN) do |txt, lspace, word, content, rspace|
-
m = Regexp.last_match
-
flag_trim = @trim && lspace && rspace
-
super(src, txt)
-
content = "#{lspace}#{content}#{rspace}" if flag_trim
-
super(src, lspace) if !flag_trim && lspace
-
instance_variable_set("@#{word}", content)
-
super(src, rspace) if !flag_trim && rspace
-
end
-
#rest = $' || text # ruby1.8
-
rest = m ? text[m.end(0)..-1] : text # ruby1.9
-
super(src, rest)
-
end
-
-
1
attr_accessor :header, :footer
-
-
1
def convert(input)
-
source = super
-
return @src = "#{@header}#{source}#{@footer}"
-
end
-
-
end
-
-
-
##
-
## delete indentation of HTML.
-
##
-
## this is language-independent.
-
##
-
1
module DeleteIndentEnhancer
-
-
1
def self.desc # :nodoc:
-
"delete indentation of HTML."
-
end
-
-
1
def convert_input(src, input)
-
input = input.gsub(/^[ \t]+</, '<')
-
super(src, input)
-
end
-
-
end
-
-
-
##
-
## convert "<h1><%=title%></h1>" into "_buf << %Q`<h1>#{title}</h1>`"
-
##
-
## this is only for Eruby.
-
##
-
1
module InterpolationEnhancer
-
-
1
def self.desc # :nodoc:
-
"convert '<p><%=text%></p>' into '_buf << %Q`<p>\#{text}</p>`'"
-
end
-
-
1
def convert_input(src, input)
-
pat = @pattern
-
regexp = pat.nil? || pat == '<% %>' ? Basic::Converter::DEFAULT_REGEXP : pattern_regexp(pat)
-
pos = 0
-
is_bol = true # is beginning of line
-
str = ''
-
input.scan(regexp) do |indicator, code, tailch, rspace|
-
match = Regexp.last_match()
-
len = match.begin(0) - pos
-
text = input[pos, len]
-
pos = match.end(0)
-
ch = indicator ? indicator[0] : nil
-
lspace = ch == ?= ? nil : detect_spaces_at_bol(text, is_bol)
-
is_bol = rspace ? true : false
-
_add_text_to_str(str, text)
-
## * when '<%= %>', do nothing
-
## * when '<% %>' or '<%# %>', delete spaces iff only spaces are around '<% %>'
-
if ch == ?= # <%= %>
-
rspace = nil if tailch && !tailch.empty?
-
str << lspace if lspace
-
add_expr(str, code, indicator)
-
str << rspace if rspace
-
elsif ch == ?\# # <%# %>
-
n = code.count("\n") + (rspace ? 1 : 0)
-
if @trim && lspace && rspace
-
add_text(src, str)
-
str = ''
-
add_stmt(src, "\n" * n)
-
else
-
str << lspace if lspace
-
add_text(src, str)
-
str = ''
-
add_stmt(src, "\n" * n)
-
str << rspace if rspace
-
end
-
else # <% %>
-
if @trim && lspace && rspace
-
add_text(src, str)
-
str = ''
-
add_stmt(src, "#{lspace}#{code}#{rspace}")
-
else
-
str << lspace if lspace
-
add_text(src, str)
-
str = ''
-
add_stmt(src, code)
-
str << rspace if rspace
-
end
-
end
-
end
-
#rest = $' || input # ruby1.8
-
rest = pos == 0 ? input : input[pos..-1] # ruby1.9
-
_add_text_to_str(str, rest)
-
add_text(src, str)
-
end
-
-
1
def add_text(src, text)
-
return if !text || text.empty?
-
#src << " _buf << %Q`" << text << "`;"
-
if text[-1] == ?\n
-
text[-1] = "\\n"
-
src << " #{@bufvar} << %Q`#{text}`\n"
-
else
-
src << " #{@bufvar} << %Q`#{text}`;"
-
end
-
end
-
-
1
def _add_text_to_str(str, text)
-
return if !text || text.empty?
-
str << text.gsub(/[`\#\\]/, '\\\\\&')
-
end
-
-
1
def add_expr_escaped(str, code)
-
str << "\#{#{escaped_expr(code)}}"
-
end
-
-
1
def add_expr_literal(str, code)
-
str << "\#{#{code}}"
-
end
-
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
1
module Erubis
-
-
-
##
-
## base error class
-
##
-
1
class ErubisError < StandardError
-
end
-
-
-
##
-
## raised when method or function is not supported
-
##
-
1
class NotSupportedError < ErubisError
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
1
require 'erubis/error'
-
1
require 'erubis/context'
-
-
-
1
module Erubis
-
-
1
EMPTY_BINDING = binding()
-
-
-
##
-
## evaluate code
-
##
-
1
module Evaluator
-
-
1
def self.supported_properties # :nodoc:
-
return []
-
end
-
-
1
attr_accessor :src, :filename
-
-
1
def init_evaluator(properties)
-
@filename = properties[:filename]
-
end
-
-
1
def result(*args)
-
raise NotSupportedError.new("evaluation of code except Ruby is not supported.")
-
end
-
-
1
def evaluate(*args)
-
raise NotSupportedError.new("evaluation of code except Ruby is not supported.")
-
end
-
-
end
-
-
-
##
-
## evaluator for Ruby
-
##
-
1
module RubyEvaluator
-
1
include Evaluator
-
-
1
def self.supported_properties # :nodoc:
-
list = Evaluator.supported_properties
-
return list
-
end
-
-
## eval(@src) with binding object
-
1
def result(_binding_or_hash=TOPLEVEL_BINDING)
-
_arg = _binding_or_hash
-
if _arg.is_a?(Hash)
-
_b = binding()
-
eval _arg.collect{|k,v| "#{k} = _arg[#{k.inspect}]; "}.join, _b
-
elsif _arg.is_a?(Binding)
-
_b = _arg
-
elsif _arg.nil?
-
_b = binding()
-
else
-
raise ArgumentError.new("#{self.class.name}#result(): argument should be Binding or Hash but passed #{_arg.class.name} object.")
-
end
-
return eval(@src, _b, (@filename || '(erubis'))
-
end
-
-
## invoke context.instance_eval(@src)
-
1
def evaluate(_context=Context.new)
-
_context = Context.new(_context) if _context.is_a?(Hash)
-
#return _context.instance_eval(@src, @filename || '(erubis)')
-
#@_proc ||= eval("proc { #{@src} }", Erubis::EMPTY_BINDING, @filename || '(erubis)')
-
@_proc ||= eval("proc { #{@src} }", binding(), @filename || '(erubis)')
-
return _context.instance_eval(&@_proc)
-
end
-
-
## if object is an Class or Module then define instance method to it,
-
## else define singleton method to it.
-
1
def def_method(object, method_name, filename=nil)
-
m = object.is_a?(Module) ? :module_eval : :instance_eval
-
object.__send__(m, "def #{method_name}; #{@src}; end", filename || @filename || '(erubis)')
-
end
-
-
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
1
require 'erubis/util'
-
-
1
module Erubis
-
-
-
##
-
## code generator, called by Converter module
-
##
-
1
module Generator
-
-
1
def self.supported_properties() # :nodoc:
-
return [
-
[:escapefunc, nil, "escape function name"],
-
]
-
end
-
-
1
attr_accessor :escapefunc
-
-
1
def init_generator(properties={})
-
@escapefunc = properties[:escapefunc]
-
end
-
-
-
## (abstract) escape text string
-
##
-
## ex.
-
## def escape_text(text)
-
## return text.dump
-
## # or return "'" + text.gsub(/['\\]/, '\\\\\&') + "'"
-
## end
-
1
def escape_text(text)
-
not_implemented
-
end
-
-
## return escaped expression code (ex. 'h(...)' or 'htmlspecialchars(...)')
-
1
def escaped_expr(code)
-
code.strip!
-
return "#{@escapefunc}(#{code})"
-
end
-
-
## (abstract) add @preamble to src
-
1
def add_preamble(src)
-
not_implemented
-
end
-
-
## (abstract) add text string to src
-
1
def add_text(src, text)
-
not_implemented
-
end
-
-
## (abstract) add statement code to src
-
1
def add_stmt(src, code)
-
not_implemented
-
end
-
-
## (abstract) add expression literal code to src. this is called by add_expr().
-
1
def add_expr_literal(src, code)
-
not_implemented
-
end
-
-
## (abstract) add escaped expression code to src. this is called by add_expr().
-
1
def add_expr_escaped(src, code)
-
not_implemented
-
end
-
-
## (abstract) add expression code to src for debug. this is called by add_expr().
-
1
def add_expr_debug(src, code)
-
not_implemented
-
end
-
-
## (abstract) add @postamble to src
-
1
def add_postamble(src)
-
not_implemented
-
end
-
-
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
-
1
module Erubis
-
-
##
-
## helper for xml
-
##
-
1
module XmlHelper
-
-
1
module_function
-
-
1
ESCAPE_TABLE = {
-
'&' => '&',
-
'<' => '<',
-
'>' => '>',
-
'"' => '"',
-
"'" => ''',
-
}
-
-
1
def escape_xml(value)
-
value.to_s.gsub(/[&<>"]/) { |s| ESCAPE_TABLE[s] } # or /[&<>"']/
-
#value.to_s.gsub(/[&<>"]/) { ESCAPE_TABLE[$&] }
-
end
-
-
1
def escape_xml2(value)
-
return value.to_s.gsub(/\&/,'&').gsub(/</,'<').gsub(/>/,'>').gsub(/"/,'"')
-
end
-
-
1
alias h escape_xml
-
1
alias html_escape escape_xml
-
-
1
def url_encode(str)
-
return str.gsub(/[^-_.a-zA-Z0-9]+/) { |s|
-
s.unpack('C*').collect { |i| "%%%02X" % i }.join
-
}
-
end
-
-
1
alias u url_encode
-
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
##
-
## you can add site-local settings here.
-
## this files is required by erubis.rb
-
##
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
1
module Kernel
-
-
##
-
## raise NotImplementedError
-
##
-
1
def not_implemented #:doc:
-
backtrace = caller()
-
method_name = (backtrace.shift =~ /`(\w+)'$/) && $1
-
mesg = "class #{self.class.name} must implement abstract method '#{method_name}()'."
-
#mesg = "#{self.class.name}##{method_name}() is not implemented."
-
err = NotImplementedError.new mesg
-
err.set_backtrace backtrace
-
raise err
-
end
-
1
private :not_implemented
-
-
end
-
1
require "execjs/module"
-
1
require "execjs/runtimes"
-
-
1
module ExecJS
-
1
self.runtime ||= Runtimes.autodetect
-
end
-
1
require "execjs/runtime"
-
-
1
module ExecJS
-
1
class DisabledRuntime < Runtime
-
1
def name
-
"Disabled"
-
end
-
-
1
def exec(source)
-
raise Error, "ExecJS disabled"
-
end
-
-
1
def eval(source)
-
raise Error, "ExecJS disabled"
-
end
-
-
1
def compile(source)
-
raise Error, "ExecJS disabled"
-
end
-
-
1
def deprecated?
-
true
-
end
-
-
1
def available?
-
true
-
end
-
end
-
end
-
1
module ExecJS
-
# Encodes strings as UTF-8
-
1
module Encoding
-
1
if RUBY_ENGINE == 'jruby' || RUBY_ENGINE == 'rbx'
-
# workaround for jruby bug http://jira.codehaus.org/browse/JRUBY-6588
-
# workaround for rbx bug https://github.com/rubinius/rubinius/issues/1729
-
def encode(string)
-
if string.encoding.name == 'ASCII-8BIT'
-
data = string.dup
-
data.force_encoding('UTF-8')
-
-
unless data.valid_encoding?
-
raise ::Encoding::UndefinedConversionError, "Could not encode ASCII-8BIT data #{string.dump} as UTF-8"
-
end
-
else
-
data = string.encode('UTF-8')
-
end
-
data
-
end
-
else
-
1
def encode(string)
-
string.encode('UTF-8')
-
end
-
end
-
end
-
end
-
1
require "tmpdir"
-
1
require "execjs/runtime"
-
-
1
module ExecJS
-
1
class ExternalRuntime < Runtime
-
1
class Context < Runtime::Context
-
1
def initialize(runtime, source = "")
-
source = encode(source)
-
-
@runtime = runtime
-
@source = source
-
end
-
-
1
def eval(source, options = {})
-
source = encode(source)
-
-
if /\S/ =~ source
-
exec("return eval(#{::JSON.generate("(#{source})", quirks_mode: true)})")
-
end
-
end
-
-
1
def exec(source, options = {})
-
source = encode(source)
-
source = "#{@source}\n#{source}" if @source
-
source = @runtime.compile_source(source)
-
-
tmpfile = write_to_tempfile(source)
-
begin
-
extract_result(@runtime.exec_runtime(tmpfile.path))
-
ensure
-
File.unlink(tmpfile)
-
end
-
end
-
-
1
def call(identifier, *args)
-
eval "#{identifier}.apply(this, #{::JSON.generate(args)})"
-
end
-
-
1
protected
-
# See Tempfile.create on Ruby 2.1
-
1
def create_tempfile(basename)
-
tmpfile = nil
-
Dir::Tmpname.create(basename) do |tmpname|
-
mode = File::WRONLY | File::CREAT | File::EXCL
-
tmpfile = File.open(tmpname, mode, 0600)
-
end
-
tmpfile
-
end
-
-
1
def write_to_tempfile(contents)
-
tmpfile = create_tempfile(['execjs', 'js'])
-
tmpfile.write(contents)
-
tmpfile.close
-
tmpfile
-
end
-
-
1
def extract_result(output)
-
status, value = output.empty? ? [] : ::JSON.parse(output, create_additions: false)
-
if status == "ok"
-
value
-
elsif value =~ /SyntaxError:/
-
raise RuntimeError, value
-
else
-
raise ProgramError, value
-
end
-
end
-
end
-
-
1
attr_reader :name
-
-
1
def initialize(options)
-
4
@name = options[:name]
-
4
@command = options[:command]
-
4
@runner_path = options[:runner_path]
-
4
@encoding = options[:encoding]
-
4
@deprecated = !!options[:deprecated]
-
4
@binary = nil
-
-
4
@popen_options = {}
-
4
@popen_options[:external_encoding] = @encoding if @encoding
-
4
@popen_options[:internal_encoding] = ::Encoding.default_internal || 'UTF-8'
-
-
4
if @runner_path
-
4
instance_eval generate_compile_method(@runner_path)
-
end
-
end
-
-
1
def available?
-
require 'json'
-
binary ? true : false
-
end
-
-
1
def deprecated?
-
4
@deprecated
-
end
-
-
1
private
-
1
def binary
-
@binary ||= which(@command)
-
end
-
-
1
def locate_executable(cmd)
-
if ExecJS.windows? && File.extname(cmd) == ""
-
cmd << ".exe"
-
end
-
-
if File.executable? cmd
-
cmd
-
else
-
path = ENV['PATH'].split(File::PATH_SEPARATOR).find { |p|
-
full_path = File.join(p, cmd)
-
File.executable?(full_path) && File.file?(full_path)
-
}
-
path && File.expand_path(cmd, path)
-
end
-
end
-
-
1
protected
-
1
def generate_compile_method(path)
-
<<-RUBY
-
def compile_source(source)
-
<<-RUNNER
-
4
#{IO.read(path)}
-
RUNNER
-
end
-
RUBY
-
end
-
-
1
def json2_source
-
@json2_source ||= IO.read(ExecJS.root + "/support/json2.js")
-
end
-
-
1
def encode_source(source)
-
encoded_source = encode_unicode_codepoints(source)
-
::JSON.generate("(function(){ #{encoded_source} })()", quirks_mode: true)
-
end
-
-
1
def encode_unicode_codepoints(str)
-
str.gsub(/[\u0080-\uffff]/) do |ch|
-
"\\u%04x" % ch.codepoints.to_a
-
end
-
end
-
-
1
def exec_runtime(filename)
-
io = IO.popen(binary.split(' ') << filename, @popen_options.merge({err: [:child, :out]}))
-
output = io.read
-
io.close
-
-
if $?.success?
-
output
-
else
-
raise RuntimeError, output
-
end
-
end
-
# Internally exposed for Context.
-
1
public :exec_runtime
-
-
1
def which(command)
-
Array(command).find do |name|
-
name, args = name.split(/\s+/, 2)
-
path = locate_executable(name)
-
-
next unless path
-
-
args ? "#{path} #{args}" : path
-
end
-
end
-
end
-
end
-
1
require "execjs/runtime"
-
-
1
module ExecJS
-
1
class JohnsonRuntime < Runtime
-
1
class Context < Runtime::Context
-
1
def initialize(runtime, source = "")
-
source = encode(source)
-
-
@runtime = Johnson::Runtime.new
-
@runtime.evaluate(source)
-
end
-
-
1
def exec(source, options = {})
-
source = encode(source)
-
-
if /\S/ =~ source
-
eval "(function(){#{source}})()", options
-
end
-
end
-
-
1
def eval(source, options = {})
-
source = encode(source)
-
-
if /\S/ =~ source
-
unbox @runtime.evaluate("(#{source})")
-
end
-
rescue Johnson::Error => e
-
if syntax_error?(e)
-
raise RuntimeError, e.message
-
else
-
raise ProgramError, e.message
-
end
-
end
-
-
1
def call(properties, *args)
-
unbox @runtime.evaluate(properties).call(*args)
-
rescue Johnson::Error => e
-
if syntax_error?(e)
-
raise RuntimeError, e.message
-
else
-
raise ProgramError, e.message
-
end
-
end
-
-
1
def unbox(value)
-
case
-
when function?(value)
-
nil
-
when string?(value)
-
value.force_encoding('UTF-8')
-
when array?(value)
-
value.map { |v| unbox(v) }
-
when object?(value)
-
value.inject({}) do |vs, (k, v)|
-
vs[k] = unbox(v) unless function?(v)
-
vs
-
end
-
else
-
value
-
end
-
end
-
-
1
private
-
1
def syntax_error?(error)
-
error.message =~ /^syntax error at /
-
end
-
-
1
def function?(value)
-
value.respond_to?(:function?) && value.function?
-
end
-
-
1
def string?(value)
-
value.is_a?(String)
-
end
-
-
1
def array?(value)
-
array_test.call(value)
-
end
-
-
1
def object?(value)
-
value.respond_to?(:inject)
-
end
-
-
1
def array_test
-
@array_test ||= @runtime.evaluate("(function(a) {return a instanceof [].constructor})")
-
end
-
end
-
-
1
def name
-
"Johnson (SpiderMonkey)"
-
end
-
-
1
def available?
-
require "johnson"
-
true
-
rescue LoadError
-
false
-
end
-
-
1
def deprecated?
-
1
true
-
end
-
end
-
end
-
1
require "execjs/version"
-
1
require "rbconfig"
-
-
1
module ExecJS
-
1
class Error < ::StandardError; end
-
1
class RuntimeError < Error; end
-
1
class ProgramError < Error; end
-
1
class RuntimeUnavailable < RuntimeError; end
-
-
1
class << self
-
1
attr_reader :runtime
-
-
1
def runtime=(runtime)
-
1
raise RuntimeUnavailable, "#{runtime.name} is unavailable on this system" unless runtime.available?
-
1
@runtime = runtime
-
end
-
-
1
def exec(source)
-
runtime.exec(source)
-
end
-
-
1
def eval(source)
-
runtime.eval(source)
-
end
-
-
1
def compile(source)
-
runtime.compile(source)
-
end
-
-
1
def root
-
4
@root ||= File.expand_path("..", __FILE__)
-
end
-
-
1
def windows?
-
@windows ||= RbConfig::CONFIG["host_os"] =~ /mswin|mingw/
-
end
-
end
-
end
-
1
require "execjs/runtime"
-
-
1
module ExecJS
-
1
class MustangRuntime < Runtime
-
1
class Context < Runtime::Context
-
1
def initialize(runtime, source = "")
-
source = encode(source)
-
-
@v8_context = ::Mustang::Context.new
-
@v8_context.eval(source)
-
end
-
-
1
def exec(source, options = {})
-
source = encode(source)
-
-
if /\S/ =~ source
-
eval "(function(){#{source}})()", options
-
end
-
end
-
-
1
def eval(source, options = {})
-
source = encode(source)
-
-
if /\S/ =~ source
-
unbox @v8_context.eval("(#{source})")
-
end
-
end
-
-
1
def call(properties, *args)
-
unbox @v8_context.eval(properties).call(*args)
-
rescue NoMethodError => e
-
raise ProgramError, e.message
-
end
-
-
1
def unbox(value)
-
case value
-
when Mustang::V8::Array
-
value.map { |v| unbox(v) }
-
when Mustang::V8::Boolean
-
value.to_bool
-
when Mustang::V8::NullClass, Mustang::V8::UndefinedClass
-
nil
-
when Mustang::V8::Function
-
nil
-
when Mustang::V8::SyntaxError
-
raise RuntimeError, value.message
-
when Mustang::V8::Error
-
raise ProgramError, value.message
-
when Mustang::V8::Object
-
value.inject({}) { |h, (k, v)|
-
v = unbox(v)
-
h[k] = v if v
-
h
-
}
-
else
-
value.respond_to?(:delegate) ? value.delegate : value
-
end
-
end
-
end
-
-
1
def name
-
"Mustang (V8)"
-
end
-
-
1
def available?
-
require "mustang"
-
true
-
rescue LoadError
-
false
-
end
-
-
1
def deprecated?
-
1
true
-
end
-
end
-
end
-
1
require "execjs/runtime"
-
-
1
module ExecJS
-
1
class RubyRacerRuntime < Runtime
-
1
class Context < Runtime::Context
-
1
def initialize(runtime, source = "")
-
source = encode(source)
-
-
lock do
-
@v8_context = ::V8::Context.new
-
@v8_context.eval(source)
-
end
-
end
-
-
1
def exec(source, options = {})
-
source = encode(source)
-
-
if /\S/ =~ source
-
eval "(function(){#{source}})()", options
-
end
-
end
-
-
1
def eval(source, options = {})
-
source = encode(source)
-
-
if /\S/ =~ source
-
lock do
-
begin
-
unbox @v8_context.eval("(#{source})")
-
rescue ::V8::JSError => e
-
if e.value["name"] == "SyntaxError"
-
raise RuntimeError, e.value.to_s
-
else
-
raise ProgramError, e.value.to_s
-
end
-
end
-
end
-
end
-
end
-
-
1
def call(properties, *args)
-
lock do
-
begin
-
unbox @v8_context.eval(properties).call(*args)
-
rescue ::V8::JSError => e
-
if e.value["name"] == "SyntaxError"
-
raise RuntimeError, e.value.to_s
-
else
-
raise ProgramError, e.value.to_s
-
end
-
end
-
end
-
end
-
-
1
def unbox(value)
-
case value
-
when ::V8::Function
-
nil
-
when ::V8::Array
-
value.map { |v| unbox(v) }
-
when ::V8::Object
-
value.inject({}) do |vs, (k, v)|
-
vs[k] = unbox(v) unless v.is_a?(::V8::Function)
-
vs
-
end
-
when String
-
value.force_encoding('UTF-8')
-
else
-
value
-
end
-
end
-
-
1
private
-
1
def lock
-
result, exception = nil, nil
-
V8::C::Locker() do
-
begin
-
result = yield
-
rescue Exception => e
-
exception = e
-
end
-
end
-
-
if exception
-
raise exception
-
else
-
result
-
end
-
end
-
end
-
-
1
def name
-
"therubyracer (V8)"
-
end
-
-
1
def available?
-
2
require "v8"
-
2
true
-
rescue LoadError
-
false
-
end
-
end
-
end
-
1
require "execjs/runtime"
-
-
1
module ExecJS
-
1
class RubyRhinoRuntime < Runtime
-
1
class Context < Runtime::Context
-
1
def initialize(runtime, source = "")
-
source = encode(source)
-
-
@rhino_context = ::Rhino::Context.new
-
fix_memory_limit! @rhino_context
-
@rhino_context.eval(source)
-
end
-
-
1
def exec(source, options = {})
-
source = encode(source)
-
-
if /\S/ =~ source
-
eval "(function(){#{source}})()", options
-
end
-
end
-
-
1
def eval(source, options = {})
-
source = encode(source)
-
-
if /\S/ =~ source
-
unbox @rhino_context.eval("(#{source})")
-
end
-
rescue ::Rhino::JSError => e
-
if e.message =~ /^syntax error/
-
raise RuntimeError, e.message
-
else
-
raise ProgramError, e.message
-
end
-
end
-
-
1
def call(properties, *args)
-
unbox @rhino_context.eval(properties).call(*args)
-
rescue ::Rhino::JSError => e
-
if e.message == "syntax error"
-
raise RuntimeError, e.message
-
else
-
raise ProgramError, e.message
-
end
-
end
-
-
1
def unbox(value)
-
case value = ::Rhino::to_ruby(value)
-
when Java::OrgMozillaJavascript::NativeFunction
-
nil
-
when Java::OrgMozillaJavascript::NativeObject
-
value.inject({}) do |vs, (k, v)|
-
case v
-
when Java::OrgMozillaJavascript::NativeFunction, ::Rhino::JS::Function
-
nil
-
else
-
vs[k] = unbox(v)
-
end
-
vs
-
end
-
when Array
-
value.map { |v| unbox(v) }
-
else
-
value
-
end
-
end
-
-
1
private
-
# Disables bytecode compiling which limits you to 64K scripts
-
1
def fix_memory_limit!(context)
-
if context.respond_to?(:optimization_level=)
-
context.optimization_level = -1
-
else
-
context.instance_eval { @native.setOptimizationLevel(-1) }
-
end
-
end
-
end
-
-
1
def name
-
"therubyrhino (Rhino)"
-
end
-
-
1
def available?
-
require "rhino"
-
true
-
rescue LoadError
-
false
-
end
-
end
-
end
-
1
require "execjs/encoding"
-
-
1
module ExecJS
-
# Abstract base class for runtimes
-
1
class Runtime
-
1
class Context
-
1
include Encoding
-
-
1
def initialize(runtime, source = "")
-
end
-
-
1
def exec(source, options = {})
-
raise NotImplementedError
-
end
-
-
1
def eval(source, options = {})
-
raise NotImplementedError
-
end
-
-
1
def call(properties, *args)
-
raise NotImplementedError
-
end
-
end
-
-
1
def name
-
raise NotImplementedError
-
end
-
-
1
def context_class
-
self.class::Context
-
end
-
-
1
def exec(source)
-
context = context_class.new(self)
-
context.exec(source)
-
end
-
-
1
def eval(source)
-
context = context_class.new(self)
-
context.eval(source)
-
end
-
-
1
def compile(source)
-
context_class.new(self, source)
-
end
-
-
1
def deprecated?
-
2
false
-
end
-
-
1
def available?
-
raise NotImplementedError
-
end
-
end
-
end
-
1
require "execjs/module"
-
1
require "execjs/disabled_runtime"
-
1
require "execjs/external_runtime"
-
1
require "execjs/johnson_runtime"
-
1
require "execjs/mustang_runtime"
-
1
require "execjs/ruby_racer_runtime"
-
1
require "execjs/ruby_rhino_runtime"
-
-
1
module ExecJS
-
1
module Runtimes
-
1
Disabled = DisabledRuntime.new
-
-
1
RubyRacer = RubyRacerRuntime.new
-
-
1
RubyRhino = RubyRhinoRuntime.new
-
-
1
Johnson = JohnsonRuntime.new
-
-
1
Mustang = MustangRuntime.new
-
-
1
Node = ExternalRuntime.new(
-
name: "Node.js (V8)",
-
command: ["nodejs", "node"],
-
runner_path: ExecJS.root + "/support/node_runner.js",
-
encoding: 'UTF-8'
-
)
-
-
1
JavaScriptCore = ExternalRuntime.new(
-
name: "JavaScriptCore",
-
command: "/System/Library/Frameworks/JavaScriptCore.framework/Versions/A/Resources/jsc",
-
runner_path: ExecJS.root + "/support/jsc_runner.js"
-
)
-
-
1
SpiderMonkey = Spidermonkey = ExternalRuntime.new(
-
name: "SpiderMonkey",
-
command: "js",
-
runner_path: ExecJS.root + "/support/spidermonkey_runner.js",
-
deprecated: true
-
)
-
-
1
JScript = ExternalRuntime.new(
-
name: "JScript",
-
command: "cscript //E:jscript //Nologo //U",
-
runner_path: ExecJS.root + "/support/jscript_runner.js",
-
encoding: 'UTF-16LE' # CScript with //U returns UTF-16LE
-
)
-
-
-
1
def self.autodetect
-
1
from_environment || best_available ||
-
raise(RuntimeUnavailable, "Could not find a JavaScript runtime. " +
-
"See https://github.com/sstephenson/execjs for a list of available runtimes.")
-
end
-
-
1
def self.best_available
-
1
runtimes.reject(&:deprecated?).find(&:available?)
-
end
-
-
1
def self.from_environment
-
1
if name = ENV["EXECJS_RUNTIME"]
-
if runtime = const_get(name)
-
if runtime.available?
-
runtime if runtime.available?
-
else
-
raise RuntimeUnavailable, "#{runtime.name} runtime is not available on this system"
-
end
-
elsif !name.empty?
-
raise RuntimeUnavailable, "#{name} runtime is not defined"
-
end
-
end
-
end
-
-
1
def self.names
-
@names ||= constants.inject({}) { |h, name| h.merge(const_get(name) => name) }.values
-
end
-
-
1
def self.runtimes
-
@runtimes ||= [
-
RubyRacer,
-
RubyRhino,
-
Johnson,
-
Mustang,
-
Node,
-
JavaScriptCore,
-
SpiderMonkey,
-
JScript
-
1
]
-
end
-
end
-
-
1
def self.runtimes
-
Runtimes.runtimes
-
end
-
end
-
1
module ExecJS
-
1
VERSION = "2.2.1"
-
end
-
1
require 'set'
-
1
require 'active_support/core_ext/module/delegation'
-
1
require 'active_support/deprecation'
-
1
require 'active_support/notifications'
-
-
1
require 'factory_girl/definition_hierarchy'
-
1
require 'factory_girl/configuration'
-
1
require 'factory_girl/errors'
-
1
require 'factory_girl/factory_runner'
-
1
require 'factory_girl/strategy_syntax_method_registrar'
-
1
require 'factory_girl/strategy_calculator'
-
1
require 'factory_girl/strategy/build'
-
1
require 'factory_girl/strategy/create'
-
1
require 'factory_girl/strategy/attributes_for'
-
1
require 'factory_girl/strategy/stub'
-
1
require 'factory_girl/strategy/null'
-
1
require 'factory_girl/registry'
-
1
require 'factory_girl/null_factory'
-
1
require 'factory_girl/null_object'
-
1
require 'factory_girl/evaluation'
-
1
require 'factory_girl/factory'
-
1
require 'factory_girl/attribute_assigner'
-
1
require 'factory_girl/evaluator'
-
1
require 'factory_girl/evaluator_class_definer'
-
1
require 'factory_girl/attribute'
-
1
require 'factory_girl/callback'
-
1
require 'factory_girl/callbacks_observer'
-
1
require 'factory_girl/declaration_list'
-
1
require 'factory_girl/declaration'
-
1
require 'factory_girl/sequence'
-
1
require 'factory_girl/attribute_list'
-
1
require 'factory_girl/trait'
-
1
require 'factory_girl/aliases'
-
1
require 'factory_girl/definition'
-
1
require 'factory_girl/definition_proxy'
-
1
require 'factory_girl/syntax'
-
1
require 'factory_girl/syntax_runner'
-
1
require 'factory_girl/find_definitions'
-
1
require 'factory_girl/reload'
-
1
require 'factory_girl/decorator'
-
1
require 'factory_girl/decorator/attribute_hash'
-
1
require 'factory_girl/decorator/class_key_hash'
-
1
require 'factory_girl/decorator/disallows_duplicates_registry'
-
1
require 'factory_girl/decorator/invocation_tracker'
-
1
require 'factory_girl/decorator/new_constructor'
-
1
require 'factory_girl/version'
-
-
1
module FactoryGirl
-
1
def self.configuration
-
9
@configuration ||= Configuration.new
-
end
-
-
1
def self.reset_configuration
-
@configuration = nil
-
end
-
-
1
def self.lint
-
invalid_factories = FactoryGirl.factories.select do |factory|
-
built_factory = FactoryGirl.build(factory.name)
-
-
if built_factory.respond_to?(:valid?)
-
!built_factory.valid?
-
end
-
end
-
-
if invalid_factories.any?
-
error_message = <<-ERROR_MESSAGE.strip
-
The following factories are invalid:
-
-
#{invalid_factories.map {|factory| "* #{factory.name}" }.join("\n")}
-
ERROR_MESSAGE
-
-
raise InvalidFactoryError, error_message
-
end
-
end
-
-
1
class << self
-
1
delegate :factories, :sequences, :traits, :callbacks, :strategies, :callback_names,
-
:to_create, :skip_create, :initialize_with, :constructor, :duplicate_attribute_assignment_from_initialize_with,
-
:duplicate_attribute_assignment_from_initialize_with=, to: :configuration
-
end
-
-
1
def self.register_factory(factory)
-
factory.names.each do |name|
-
factories.register(name, factory)
-
end
-
factory
-
end
-
-
1
def self.factory_by_name(name)
-
factories.find(name)
-
end
-
-
1
def self.register_sequence(sequence)
-
sequence.names.each do |name|
-
sequences.register(name, sequence)
-
end
-
sequence
-
end
-
-
1
def self.sequence_by_name(name)
-
sequences.find(name)
-
end
-
-
1
def self.register_trait(trait)
-
trait.names.each do |name|
-
traits.register(name, trait)
-
end
-
trait
-
end
-
-
1
def self.trait_by_name(name)
-
traits.find(name)
-
end
-
-
1
def self.register_strategy(strategy_name, strategy_class)
-
5
strategies.register(strategy_name, strategy_class)
-
5
StrategySyntaxMethodRegistrar.new(strategy_name).define_strategy_methods
-
end
-
-
1
def self.strategy_by_name(name)
-
strategies.find(name)
-
end
-
-
1
def self.register_default_strategies
-
1
register_strategy(:build, FactoryGirl::Strategy::Build)
-
1
register_strategy(:create, FactoryGirl::Strategy::Create)
-
1
register_strategy(:attributes_for, FactoryGirl::Strategy::AttributesFor)
-
1
register_strategy(:build_stubbed, FactoryGirl::Strategy::Stub)
-
1
register_strategy(:null, FactoryGirl::Strategy::Null)
-
end
-
-
1
def self.register_default_callbacks
-
1
register_callback(:after_build)
-
1
register_callback(:after_create)
-
1
register_callback(:after_stub)
-
1
register_callback(:before_create)
-
end
-
-
1
def self.register_callback(name)
-
4
name = name.to_sym
-
4
callback_names << name
-
end
-
end
-
-
1
FactoryGirl.register_default_strategies
-
1
FactoryGirl.register_default_callbacks
-
1
module FactoryGirl
-
1
class << self
-
1
attr_accessor :aliases
-
end
-
-
1
self.aliases = [
-
[/(.+)_id/, '\1'],
-
[/(.*)/, '\1_id']
-
]
-
-
1
def self.aliases_for(attribute)
-
aliases.map do |(pattern, replace)|
-
if pattern.match(attribute.to_s)
-
attribute.to_s.sub(pattern, replace).to_sym
-
end
-
end.compact << attribute
-
end
-
end
-
1
require 'factory_girl/attribute/static'
-
1
require 'factory_girl/attribute/dynamic'
-
1
require 'factory_girl/attribute/association'
-
1
require 'factory_girl/attribute/sequence'
-
-
1
module FactoryGirl
-
# @api private
-
1
class Attribute
-
1
attr_reader :name, :ignored
-
-
1
def initialize(name, ignored)
-
@name = name.to_sym
-
@ignored = ignored
-
ensure_non_attribute_writer!
-
end
-
-
1
def to_proc
-
-> { }
-
end
-
-
1
def association?
-
false
-
end
-
-
1
def alias_for?(attr)
-
FactoryGirl.aliases_for(attr).include?(name)
-
end
-
-
1
private
-
-
1
def ensure_non_attribute_writer!
-
NonAttributeWriterValidator.new(@name).validate!
-
end
-
-
1
class NonAttributeWriterValidator
-
1
def initialize(method_name)
-
@method_name = method_name.to_s
-
@method_name_setter_match = @method_name.match(/(.*)=$/)
-
end
-
-
1
def validate!
-
if method_is_writer?
-
raise AttributeDefinitionError, error_message
-
end
-
end
-
-
1
private
-
-
1
def method_is_writer?
-
!!@method_name_setter_match
-
end
-
-
1
def attribute_name
-
@method_name_setter_match[1]
-
end
-
-
1
def error_message
-
"factory_girl uses '#{attribute_name} value' syntax rather than '#{attribute_name} = value'"
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Attribute
-
# @api private
-
1
class Association < Attribute
-
1
attr_reader :factory
-
-
1
def initialize(name, factory, overrides)
-
super(name, false)
-
@factory = factory
-
@overrides = overrides
-
end
-
-
1
def to_proc
-
factory = @factory
-
overrides = @overrides
-
traits_and_overrides = [factory, overrides].flatten
-
factory_name = traits_and_overrides.shift
-
-
-> { association(factory_name, *traits_and_overrides) }
-
end
-
-
1
def association?
-
true
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Attribute
-
# @api private
-
1
class Dynamic < Attribute
-
1
def initialize(name, ignored, block)
-
super(name, ignored)
-
@block = block
-
end
-
-
1
def to_proc
-
block = @block
-
-
-> {
-
value = block.arity == 1 ? instance_exec(self, &block) : instance_exec(&block)
-
raise SequenceAbuseError if FactoryGirl::Sequence === value
-
value
-
}
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Attribute
-
# @api private
-
1
class Sequence < Attribute
-
1
def initialize(name, sequence, ignored)
-
super(name, ignored)
-
@sequence = sequence
-
end
-
-
1
def to_proc
-
sequence = @sequence
-
-> { FactoryGirl.generate(sequence) }
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Attribute
-
# @api private
-
1
class Static < Attribute
-
1
def initialize(name, value, ignored)
-
super(name, ignored)
-
@value = value
-
end
-
-
1
def to_proc
-
value = @value
-
-> { value }
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
# @api private
-
1
class AttributeAssigner
-
1
def initialize(evaluator, build_class, &instance_builder)
-
@build_class = build_class
-
@instance_builder = instance_builder
-
@evaluator = evaluator
-
@attribute_list = evaluator.class.attribute_list
-
@attribute_names_assigned = []
-
end
-
-
1
def object
-
@evaluator.instance = build_class_instance
-
build_class_instance.tap do |instance|
-
attributes_to_set_on_instance.each do |attribute|
-
instance.send("#{attribute}=", get(attribute))
-
@attribute_names_assigned << attribute
-
end
-
end
-
end
-
-
1
def hash
-
@evaluator.instance = build_hash
-
-
attributes_to_set_on_hash.inject({}) do |result, attribute|
-
result[attribute] = get(attribute)
-
result
-
end
-
end
-
-
1
private
-
-
1
def method_tracking_evaluator
-
@method_tracking_evaluator ||= Decorator::AttributeHash.new(decorated_evaluator, attribute_names_to_assign)
-
end
-
-
1
def decorated_evaluator
-
Decorator::InvocationTracker.new(
-
Decorator::NewConstructor.new(@evaluator, @build_class)
-
)
-
end
-
-
1
def methods_invoked_on_evaluator
-
method_tracking_evaluator.__invoked_methods__
-
end
-
-
1
def build_class_instance
-
@build_class_instance ||= method_tracking_evaluator.instance_exec(&@instance_builder)
-
end
-
-
1
def build_hash
-
@build_hash ||= NullObject.new(hash_instance_methods_to_respond_to)
-
end
-
-
1
def get(attribute_name)
-
@evaluator.send(attribute_name)
-
end
-
-
1
def attributes_to_set_on_instance
-
(attribute_names_to_assign - @attribute_names_assigned - methods_invoked_on_evaluator).uniq
-
end
-
-
1
def attributes_to_set_on_hash
-
attribute_names_to_assign - association_names
-
end
-
-
1
def attribute_names_to_assign
-
@attribute_names_to_assign ||= non_ignored_attribute_names + override_names - ignored_attribute_names - alias_names_to_ignore
-
end
-
-
1
def non_ignored_attribute_names
-
@attribute_list.non_ignored.names
-
end
-
-
1
def ignored_attribute_names
-
@attribute_list.ignored.names
-
end
-
-
1
def association_names
-
@attribute_list.associations.names
-
end
-
-
1
def override_names
-
@evaluator.__override_names__
-
end
-
-
1
def hash_instance_methods_to_respond_to
-
@attribute_list.names + override_names + @build_class.instance_methods
-
end
-
-
1
def alias_names_to_ignore
-
@attribute_list.non_ignored.map do |attribute|
-
override_names.map { |override| attribute.name if attribute.alias_for?(override) && attribute.name != override && !ignored_attribute_names.include?(override) }
-
end.flatten.compact
-
end
-
end
-
end
-
1
module FactoryGirl
-
# @api private
-
1
class AttributeList
-
1
include Enumerable
-
-
1
def initialize(name = nil, attributes = [])
-
@name = name
-
@attributes = attributes
-
end
-
-
1
def define_attribute(attribute)
-
ensure_attribute_not_self_referencing! attribute
-
ensure_attribute_not_defined! attribute
-
-
add_attribute attribute
-
end
-
-
1
def each(&block)
-
@attributes.each(&block)
-
end
-
-
1
def names
-
map(&:name)
-
end
-
-
1
def associations
-
AttributeList.new(@name, select(&:association?))
-
end
-
-
1
def ignored
-
AttributeList.new(@name, select(&:ignored))
-
end
-
-
1
def non_ignored
-
AttributeList.new(@name, reject(&:ignored))
-
end
-
-
1
def apply_attributes(attributes_to_apply)
-
attributes_to_apply.each { |attribute| add_attribute(attribute) }
-
end
-
-
1
private
-
-
1
def add_attribute(attribute)
-
@attributes << attribute
-
attribute
-
end
-
-
1
def ensure_attribute_not_defined!(attribute)
-
if attribute_defined?(attribute.name)
-
raise AttributeDefinitionError, "Attribute already defined: #{attribute.name}"
-
end
-
end
-
-
1
def ensure_attribute_not_self_referencing!(attribute)
-
if attribute.respond_to?(:factory) && attribute.factory == @name
-
raise AssociationDefinitionError, "Self-referencing association '#{attribute.name}' in '#{attribute.factory}'"
-
end
-
end
-
-
1
def attribute_defined?(attribute_name)
-
@attributes.any? do |attribute|
-
attribute.name == attribute_name
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Callback
-
1
attr_reader :name
-
-
1
def initialize(name, block)
-
@name = name.to_sym
-
@block = block
-
ensure_valid_callback_name!
-
end
-
-
1
def run(instance, evaluator)
-
case block.arity
-
when 1, -1 then syntax_runner.instance_exec(instance, &block)
-
when 2 then syntax_runner.instance_exec(instance, evaluator, &block)
-
else syntax_runner.instance_exec(&block)
-
end
-
end
-
-
1
def ==(other)
-
name == other.name &&
-
block == other.block
-
end
-
-
1
protected
-
1
attr_reader :block
-
-
1
private
-
-
1
def ensure_valid_callback_name!
-
unless FactoryGirl.callback_names.include?(name)
-
raise InvalidCallbackNameError, "#{name} is not a valid callback name. " +
-
"Valid callback names are #{FactoryGirl.callback_names.inspect}"
-
end
-
end
-
-
1
def syntax_runner
-
@syntax_runner ||= SyntaxRunner.new
-
end
-
end
-
end
-
1
module FactoryGirl
-
# @api private
-
1
class CallbacksObserver
-
1
def initialize(callbacks, evaluator)
-
@callbacks = callbacks
-
@evaluator = evaluator
-
end
-
-
1
def update(name, result_instance)
-
callbacks_by_name(name).each do |callback|
-
callback.run(result_instance, @evaluator)
-
end
-
end
-
-
1
private
-
-
1
def callbacks_by_name(name)
-
@callbacks.select { |callback| callback.name == name }
-
end
-
end
-
end
-
1
module FactoryGirl
-
# @api private
-
1
class Configuration
-
1
attr_reader :factories, :sequences, :traits, :strategies, :callback_names
-
-
1
def initialize
-
1
@factories = Decorator::DisallowsDuplicatesRegistry.new(Registry.new('Factory'))
-
1
@sequences = Decorator::DisallowsDuplicatesRegistry.new(Registry.new('Sequence'))
-
1
@traits = Decorator::DisallowsDuplicatesRegistry.new(Registry.new('Trait'))
-
1
@strategies = Registry.new('Strategy')
-
1
@callback_names = Set.new
-
1
@definition = Definition.new
-
-
1
to_create { |instance| instance.save! }
-
1
initialize_with { new }
-
end
-
-
1
delegate :to_create, :skip_create, :constructor, :before, :after,
-
:callback, :callbacks, to: :@definition
-
-
1
def initialize_with(&block)
-
1
@definition.define_constructor(&block)
-
end
-
-
1
def duplicate_attribute_assignment_from_initialize_with
-
false
-
end
-
-
1
def duplicate_attribute_assignment_from_initialize_with=(value)
-
ActiveSupport::Deprecation.warn 'Assignment of duplicate_attribute_assignment_from_initialize_with is unnecessary as this is now default behavior in FactoryGirl 4.0; this line can be removed', caller
-
end
-
end
-
end
-
1
require 'factory_girl/declaration/static'
-
1
require 'factory_girl/declaration/dynamic'
-
1
require 'factory_girl/declaration/association'
-
1
require 'factory_girl/declaration/implicit'
-
-
1
module FactoryGirl
-
# @api private
-
1
class Declaration
-
1
attr_reader :name
-
-
1
def initialize(name, ignored = false)
-
@name = name
-
@ignored = ignored
-
end
-
-
1
def to_attributes
-
build
-
end
-
-
1
protected
-
1
attr_reader :ignored
-
end
-
end
-
1
module FactoryGirl
-
1
class Declaration
-
# @api private
-
1
class Association < Declaration
-
1
def initialize(name, *options)
-
super(name, false)
-
@options = options.dup
-
@overrides = options.extract_options!
-
@traits = options
-
end
-
-
1
def ==(other)
-
name == other.name &&
-
options == other.options
-
end
-
-
1
protected
-
1
attr_reader :options
-
-
1
private
-
-
1
def build
-
factory_name = @overrides[:factory] || name
-
[Attribute::Association.new(name, factory_name, [@traits, @overrides.except(:factory)].flatten)]
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Declaration
-
# @api private
-
1
class Dynamic < Declaration
-
1
def initialize(name, ignored = false, block = nil)
-
super(name, ignored)
-
@block = block
-
end
-
-
1
def ==(other)
-
name == other.name &&
-
ignored == other.ignored &&
-
block == other.block
-
end
-
-
1
protected
-
1
attr_reader :block
-
-
1
private
-
-
1
def build
-
[Attribute::Dynamic.new(name, @ignored, @block)]
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Declaration
-
# @api private
-
1
class Implicit < Declaration
-
1
def initialize(name, factory = nil, ignored = false)
-
super(name, ignored)
-
@factory = factory
-
end
-
-
1
def ==(other)
-
name == other.name &&
-
factory == other.factory &&
-
ignored == other.ignored
-
end
-
-
1
protected
-
1
attr_reader :factory
-
-
1
private
-
-
1
def build
-
if FactoryGirl.factories.registered?(name)
-
[Attribute::Association.new(name, name, {})]
-
elsif FactoryGirl.sequences.registered?(name)
-
[Attribute::Sequence.new(name, name, @ignored)]
-
else
-
@factory.inherit_traits([name])
-
[]
-
end
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Declaration
-
# @api private
-
1
class Static < Declaration
-
1
def initialize(name, value, ignored = false)
-
super(name, ignored)
-
@value = value
-
end
-
-
1
def ==(other)
-
name == other.name &&
-
value == other.value &&
-
ignored == other.ignored
-
end
-
-
1
protected
-
1
attr_reader :value
-
-
1
private
-
-
1
def build
-
[Attribute::Static.new(name, @value, @ignored)]
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
# @api private
-
1
class DeclarationList
-
1
include Enumerable
-
-
1
def initialize(name = nil)
-
1
@declarations = []
-
1
@name = name
-
1
@overridable = false
-
end
-
-
1
def declare_attribute(declaration)
-
delete_declaration(declaration) if overridable?
-
-
@declarations << declaration
-
declaration
-
end
-
-
1
def overridable
-
@overridable = true
-
end
-
-
1
def attributes
-
@attributes ||= AttributeList.new(@name).tap do |list|
-
to_attributes.each do |attribute|
-
list.define_attribute(attribute)
-
end
-
end
-
end
-
-
1
def each(&block)
-
@declarations.each(&block)
-
end
-
-
1
private
-
-
1
def delete_declaration(declaration)
-
@declarations.delete_if { |decl| decl.name == declaration.name }
-
end
-
-
1
def to_attributes
-
@declarations.inject([]) { |result, declaration| result += declaration.to_attributes }
-
end
-
-
1
def overridable?
-
@overridable
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Decorator < BasicObject
-
1
undef_method :==
-
-
1
def initialize(component)
-
7
@component = component
-
end
-
-
1
def method_missing(name, *args, &block)
-
@component.send(name, *args, &block)
-
end
-
-
1
def send(symbol, *args)
-
__send__(symbol, *args)
-
end
-
-
1
def self.const_missing(name)
-
::Object.const_get(name)
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Decorator
-
1
class AttributeHash < Decorator
-
1
def initialize(component, attributes = [])
-
super(component)
-
@attributes = attributes
-
end
-
-
1
def attributes
-
@attributes.inject({}) do |result, attribute_name|
-
result[attribute_name] = send(attribute_name)
-
result
-
end
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Decorator
-
1
class ClassKeyHash < Decorator
-
1
def [](key)
-
@component[symbolized_key key]
-
end
-
-
1
def []=(key, value)
-
5
@component[symbolized_key key] = value
-
end
-
-
1
def key?(key)
-
@component.key? symbolized_key(key)
-
end
-
-
1
private
-
-
1
def symbolized_key(key)
-
5
if key.respond_to?(:to_sym)
-
5
key.to_sym
-
else
-
key.to_s.underscore.to_sym
-
end
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Decorator
-
1
class DisallowsDuplicatesRegistry < Decorator
-
1
def register(name, item)
-
if registered?(name)
-
raise DuplicateDefinitionError, "#{@component.name} already registered: #{name}"
-
else
-
@component.register(name, item)
-
end
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Decorator
-
1
class InvocationTracker < Decorator
-
1
def initialize(component)
-
super
-
@invoked_methods = []
-
end
-
-
1
def method_missing(name, *args, &block)
-
@invoked_methods << name
-
super
-
end
-
-
1
def __invoked_methods__
-
@invoked_methods.uniq
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Decorator
-
1
class NewConstructor < Decorator
-
1
def initialize(component, build_class)
-
super(component)
-
@build_class = build_class
-
end
-
-
1
delegate :new, to: :@build_class
-
end
-
end
-
end
-
1
module FactoryGirl
-
# @api private
-
1
class Definition
-
1
attr_reader :defined_traits, :declarations
-
-
1
def initialize(name = nil, base_traits = [])
-
1
@declarations = DeclarationList.new(name)
-
1
@callbacks = []
-
1
@defined_traits = Set.new
-
1
@to_create = nil
-
1
@base_traits = base_traits
-
1
@additional_traits = []
-
1
@constructor = nil
-
1
@attributes = nil
-
1
@compiled = false
-
end
-
-
1
delegate :declare_attribute, to: :declarations
-
-
1
def attributes
-
@attributes ||= AttributeList.new.tap do |attribute_list|
-
attribute_lists = aggregate_from_traits_and_self(:attributes) { declarations.attributes }
-
attribute_lists.each do |attributes|
-
attribute_list.apply_attributes attributes
-
end
-
end
-
end
-
-
1
def to_create(&block)
-
1
if block_given?
-
1
@to_create = block
-
else
-
aggregate_from_traits_and_self(:to_create) { @to_create }.last
-
end
-
end
-
-
1
def constructor
-
aggregate_from_traits_and_self(:constructor) { @constructor }.last
-
end
-
-
1
def callbacks
-
aggregate_from_traits_and_self(:callbacks) { @callbacks }
-
end
-
-
1
def compile
-
unless @compiled
-
declarations.attributes
-
-
defined_traits.each do |defined_trait|
-
base_traits.each { |bt| bt.define_trait defined_trait }
-
additional_traits.each { |bt| bt.define_trait defined_trait }
-
end
-
-
@compiled = true
-
end
-
end
-
-
1
def overridable
-
declarations.overridable
-
self
-
end
-
-
1
def inherit_traits(new_traits)
-
@base_traits += new_traits
-
end
-
-
1
def append_traits(new_traits)
-
@additional_traits += new_traits
-
end
-
-
1
def add_callback(callback)
-
@callbacks << callback
-
end
-
-
1
def skip_create
-
@to_create = ->(instance) { }
-
end
-
-
1
def define_trait(trait)
-
@defined_traits.add(trait)
-
end
-
-
1
def define_constructor(&block)
-
1
@constructor = block
-
end
-
-
1
def before(*names, &block)
-
callback(*names.map { |name| "before_#{name}" }, &block)
-
end
-
-
1
def after(*names, &block)
-
callback(*names.map { |name| "after_#{name}" }, &block)
-
end
-
-
1
def callback(*names, &block)
-
names.each do |name|
-
FactoryGirl.register_callback(name)
-
add_callback(Callback.new(name, block))
-
end
-
end
-
-
1
private
-
-
1
def base_traits
-
@base_traits.map { |name| trait_by_name(name) }
-
end
-
-
1
def additional_traits
-
@additional_traits.map { |name| trait_by_name(name) }
-
end
-
-
1
def trait_by_name(name)
-
trait_for(name) || FactoryGirl.trait_by_name(name)
-
end
-
-
1
def trait_for(name)
-
defined_traits.detect { |trait| trait.name == name }
-
end
-
-
1
def initialize_copy(source)
-
super
-
@attributes = nil
-
@compiled = false
-
end
-
-
1
def aggregate_from_traits_and_self(method_name, &block)
-
compile
-
[].tap do |list|
-
base_traits.each do |trait|
-
list << trait.send(method_name)
-
end
-
-
list << instance_exec(&block)
-
-
additional_traits.each do |trait|
-
list << trait.send(method_name)
-
end
-
end.flatten.compact
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class DefinitionHierarchy
-
1
def callbacks
-
FactoryGirl.callbacks
-
end
-
-
1
def constructor
-
FactoryGirl.constructor
-
end
-
-
1
def to_create
-
FactoryGirl.to_create
-
end
-
-
1
def self.build_from_definition(definition)
-
build_to_create(&definition.to_create)
-
build_constructor(&definition.constructor)
-
add_callbacks definition.callbacks
-
end
-
-
1
def self.add_callbacks(callbacks)
-
if callbacks.any?
-
define_method :callbacks do
-
super() + callbacks
-
end
-
end
-
end
-
1
private_class_method :add_callbacks
-
-
1
def self.build_constructor(&block)
-
if block
-
define_method(:constructor) do
-
block
-
end
-
end
-
end
-
1
private_class_method :build_constructor
-
-
1
def self.build_to_create(&block)
-
if block
-
define_method(:to_create) do
-
block
-
end
-
end
-
end
-
1
private_class_method :build_to_create
-
end
-
end
-
1
module FactoryGirl
-
1
class DefinitionProxy
-
1
UNPROXIED_METHODS = %w(__send__ __id__ nil? send object_id extend instance_eval initialize block_given? raise caller method)
-
-
1
(instance_methods + private_instance_methods).each do |method|
-
178
undef_method(method) unless UNPROXIED_METHODS.include?(method.to_s)
-
end
-
-
1
delegate :before, :after, :callback, to: :@definition
-
-
1
attr_reader :child_factories
-
-
1
def initialize(definition, ignore = false)
-
@definition = definition
-
@ignore = ignore
-
@child_factories = []
-
end
-
-
1
def singleton_method_added(name)
-
message = "Defining methods in blocks (trait or factory) is not supported (#{name})"
-
raise FactoryGirl::MethodDefinitionError, message
-
end
-
-
# Adds an attribute that should be assigned on generated instances for this
-
# factory.
-
#
-
# This method should be called with either a value or block, but not both. If
-
# called with a block, the attribute will be generated "lazily," whenever an
-
# instance is generated. Lazy attribute blocks will not be called if that
-
# attribute is overridden for a specific instance.
-
#
-
# When defining lazy attributes, an instance of FactoryGirl::Strategy will
-
# be yielded, allowing associations to be built using the correct build
-
# strategy.
-
#
-
# Arguments:
-
# * name: +Symbol+ or +String+
-
# The name of this attribute. This will be assigned using "name=" for
-
# generated instances.
-
# * value: +Object+
-
# If no block is given, this value will be used for this attribute.
-
1
def add_attribute(name, value = nil, &block)
-
raise AttributeDefinitionError, 'Both value and block given' if value && block_given?
-
-
declaration = if block_given?
-
Declaration::Dynamic.new(name, @ignore, block)
-
else
-
Declaration::Static.new(name, value, @ignore)
-
end
-
-
@definition.declare_attribute(declaration)
-
end
-
-
1
def ignore(&block)
-
proxy = DefinitionProxy.new(@definition, true)
-
proxy.instance_eval(&block)
-
end
-
-
# Calls add_attribute using the missing method name as the name of the
-
# attribute, so that:
-
#
-
# factory :user do
-
# name 'Billy Idol'
-
# end
-
#
-
# and:
-
#
-
# factory :user do
-
# add_attribute :name, 'Billy Idol'
-
# end
-
#
-
# are equivalent.
-
#
-
# If no argument or block is given, factory_girl will look for a sequence
-
# or association with the same name. This means that:
-
#
-
# factory :user do
-
# email { create(:email) }
-
# association :account
-
# end
-
#
-
# and:
-
#
-
# factory :user do
-
# email
-
# account
-
# end
-
#
-
# are equivalent.
-
1
def method_missing(name, *args, &block)
-
if args.empty? && block.nil?
-
@definition.declare_attribute(Declaration::Implicit.new(name, @definition, @ignore))
-
elsif args.first.respond_to?(:has_key?) && args.first.has_key?(:factory)
-
association(name, *args)
-
else
-
add_attribute(name, *args, &block)
-
end
-
end
-
-
# Adds an attribute that will have unique values generated by a sequence with
-
# a specified format.
-
#
-
# The result of:
-
# factory :user do
-
# sequence(:email) { |n| "person#{n}@example.com" }
-
# end
-
#
-
# Is equal to:
-
# sequence(:email) { |n| "person#{n}@example.com" }
-
#
-
# factory :user do
-
# email { FactoryGirl.create(:email) }
-
# end
-
#
-
# Except that no globally available sequence will be defined.
-
1
def sequence(name, *args, &block)
-
sequence = Sequence.new(name, *args, &block)
-
add_attribute(name) { increment_sequence(sequence) }
-
end
-
-
# Adds an attribute that builds an association. The associated instance will
-
# be built using the same build strategy as the parent instance.
-
#
-
# Example:
-
# factory :user do
-
# name 'Joey'
-
# end
-
#
-
# factory :post do
-
# association :author, factory: :user
-
# end
-
#
-
# Arguments:
-
# * name: +Symbol+
-
# The name of this attribute.
-
# * options: +Hash+
-
#
-
# Options:
-
# * factory: +Symbol+ or +String+
-
# The name of the factory to use when building the associated instance.
-
# If no name is given, the name of the attribute is assumed to be the
-
# name of the factory. For example, a "user" association will by
-
# default use the "user" factory.
-
1
def association(name, *options)
-
@definition.declare_attribute(Declaration::Association.new(name, *options))
-
end
-
-
1
def to_create(&block)
-
@definition.to_create(&block)
-
end
-
-
1
def skip_create
-
@definition.skip_create
-
end
-
-
1
def factory(name, options = {}, &block)
-
@child_factories << [name, options, block]
-
end
-
-
1
def trait(name, &block)
-
@definition.define_trait(Trait.new(name, &block))
-
end
-
-
1
def initialize_with(&block)
-
@definition.define_constructor(&block)
-
end
-
end
-
end
-
1
module FactoryGirl
-
# Raised when a factory is defined that attempts to instantiate itself.
-
1
class AssociationDefinitionError < RuntimeError; end
-
-
# Raised when a callback is defined that has an invalid name
-
1
class InvalidCallbackNameError < RuntimeError; end
-
-
# Raised when a factory is defined with the same name as a previously-defined factory.
-
1
class DuplicateDefinitionError < RuntimeError; end
-
-
# Raised when attempting to register a sequence from a dynamic attribute block
-
1
class SequenceAbuseError < RuntimeError; end
-
-
# Raised when defining an invalid attribute:
-
# * Defining an attribute which has a name ending in "="
-
# * Defining an attribute with both a static and lazy value
-
# * Defining an attribute twice in the same factory
-
1
class AttributeDefinitionError < RuntimeError; end
-
-
# Raised when a method is defined in a factory or trait with arguments
-
1
class MethodDefinitionError < RuntimeError; end
-
-
# Raised when any factory is considered invalid
-
1
class InvalidFactoryError < RuntimeError; end
-
end
-
1
require 'observer'
-
-
1
module FactoryGirl
-
1
class Evaluation
-
1
include Observable
-
-
1
def initialize(attribute_assigner, to_create)
-
@attribute_assigner = attribute_assigner
-
@to_create = to_create
-
end
-
-
1
delegate :object, :hash, to: :@attribute_assigner
-
-
1
def create(result_instance)
-
@to_create[result_instance]
-
end
-
-
1
def notify(name, result_instance)
-
changed
-
notify_observers(name, result_instance)
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/class/attribute'
-
-
1
module FactoryGirl
-
# @api private
-
1
class Evaluator
-
1
class_attribute :attribute_lists
-
-
1
private_instance_methods.each do |method|
-
81
undef_method(method) unless method =~ /^__|initialize/
-
end
-
-
1
def initialize(build_strategy, overrides = {})
-
@build_strategy = build_strategy
-
@overrides = overrides
-
@cached_attributes = overrides
-
@instance = nil
-
-
@overrides.each do |name, value|
-
singleton_class.define_attribute(name) { value }
-
end
-
end
-
-
1
def association(factory_name, *traits_and_overrides)
-
overrides = traits_and_overrides.extract_options!
-
strategy_override = overrides.fetch(:strategy) { :create }
-
-
traits_and_overrides += [overrides.except(:strategy)]
-
-
runner = FactoryRunner.new(factory_name, strategy_override, traits_and_overrides)
-
@build_strategy.association(runner)
-
end
-
-
1
def instance=(object_instance)
-
@instance = object_instance
-
end
-
-
1
def method_missing(method_name, *args, &block)
-
if @instance.respond_to?(method_name)
-
@instance.send(method_name, *args, &block)
-
else
-
SyntaxRunner.new.send(method_name, *args, &block)
-
end
-
end
-
-
1
def respond_to_missing?(method_name, include_private = false)
-
@instance.respond_to?(method_name) || SyntaxRunner.new.respond_to?(method_name)
-
end
-
-
1
def __override_names__
-
@overrides.keys
-
end
-
-
1
def increment_sequence(sequence)
-
sequence.next(self)
-
end
-
-
1
def self.attribute_list
-
AttributeList.new.tap do |list|
-
attribute_lists.each do |attribute_list|
-
list.apply_attributes attribute_list.to_a
-
end
-
end
-
end
-
-
1
def self.define_attribute(name, &block)
-
define_method(name) do
-
if @cached_attributes.key?(name)
-
@cached_attributes[name]
-
else
-
@cached_attributes[name] = instance_exec(&block)
-
end
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
# @api private
-
1
class EvaluatorClassDefiner
-
1
def initialize(attributes, parent_class)
-
@parent_class = parent_class
-
@attributes = attributes
-
-
attributes.each do |attribute|
-
evaluator_class.define_attribute(attribute.name, &attribute.to_proc)
-
end
-
end
-
-
1
def evaluator_class
-
@evaluator_class ||= Class.new(@parent_class).tap do |klass|
-
klass.attribute_lists ||= []
-
klass.attribute_lists += [@attributes]
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/keys'
-
1
require 'active_support/inflector'
-
-
1
module FactoryGirl
-
# @api private
-
1
class Factory
-
1
attr_reader :name, :definition
-
-
1
def initialize(name, options = {})
-
assert_valid_options(options)
-
@name = name.respond_to?(:to_sym) ? name.to_sym : name.to_s.underscore.to_sym
-
@parent = options[:parent]
-
@aliases = options[:aliases] || []
-
@class_name = options[:class]
-
@definition = Definition.new(@name, options[:traits] || [])
-
@compiled = false
-
end
-
-
1
delegate :add_callback, :declare_attribute, :to_create, :define_trait, :constructor,
-
:defined_traits, :inherit_traits, :append_traits, to: :@definition
-
-
1
def build_class
-
@build_class ||= if class_name.is_a? Class
-
class_name
-
else
-
class_name.to_s.camelize.constantize
-
end
-
end
-
-
1
def run(build_strategy, overrides, &block)
-
block ||= ->(result) { result }
-
compile
-
-
strategy = StrategyCalculator.new(build_strategy).strategy.new
-
-
evaluator = evaluator_class.new(strategy, overrides.symbolize_keys)
-
attribute_assigner = AttributeAssigner.new(evaluator, build_class, &compiled_constructor)
-
-
evaluation = Evaluation.new(attribute_assigner, compiled_to_create)
-
evaluation.add_observer(CallbacksObserver.new(callbacks, evaluator))
-
-
strategy.result(evaluation).tap(&block)
-
end
-
-
1
def human_names
-
names.map { |name| name.to_s.humanize.downcase }
-
end
-
-
1
def associations
-
evaluator_class.attribute_list.associations
-
end
-
-
# Names for this factory, including aliases.
-
#
-
# Example:
-
#
-
# factory :user, aliases: [:author] do
-
# # ...
-
# end
-
#
-
# FactoryGirl.create(:author).class
-
# # => User
-
#
-
# Because an attribute defined without a value or block will build an
-
# association with the same name, this allows associations to be defined
-
# without factories, such as:
-
#
-
# factory :user, aliases: [:author] do
-
# # ...
-
# end
-
#
-
# factory :post do
-
# author
-
# end
-
#
-
# FactoryGirl.create(:post).author.class
-
# # => User
-
1
def names
-
[name] + @aliases
-
end
-
-
1
def compile
-
unless @compiled
-
parent.compile
-
parent.defined_traits.each { |trait| define_trait(trait) }
-
@definition.compile
-
build_hierarchy
-
@compiled = true
-
end
-
end
-
-
1
def with_traits(traits)
-
self.clone.tap do |factory_with_traits|
-
factory_with_traits.append_traits traits
-
end
-
end
-
-
1
protected
-
-
1
def class_name
-
@class_name || parent.class_name || name
-
end
-
-
1
def evaluator_class
-
@evaluator_class ||= EvaluatorClassDefiner.new(attributes, parent.evaluator_class).evaluator_class
-
end
-
-
1
def attributes
-
compile
-
AttributeList.new(@name).tap do |list|
-
list.apply_attributes definition.attributes
-
end
-
end
-
-
1
def hierarchy_class
-
@hierarchy_class ||= Class.new(parent.hierarchy_class)
-
end
-
-
1
def hierarchy_instance
-
@hierarchy_instance ||= hierarchy_class.new
-
end
-
-
1
def build_hierarchy
-
hierarchy_class.build_from_definition definition
-
end
-
-
1
def callbacks
-
hierarchy_instance.callbacks
-
end
-
-
1
def compiled_to_create
-
hierarchy_instance.to_create
-
end
-
-
1
def compiled_constructor
-
hierarchy_instance.constructor
-
end
-
-
1
private
-
-
1
def assert_valid_options(options)
-
options.assert_valid_keys(:class, :parent, :aliases, :traits)
-
end
-
-
1
def parent
-
if @parent
-
FactoryGirl.factory_by_name(@parent)
-
else
-
NullFactory.new
-
end
-
end
-
-
1
def initialize_copy(source)
-
super
-
@definition = @definition.clone
-
@evaluator_class = nil
-
@hierarchy_class = nil
-
@hierarchy_instance = nil
-
@compiled = false
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class FactoryRunner
-
1
def initialize(name, strategy, traits_and_overrides)
-
@name = name
-
@strategy = strategy
-
-
@overrides = traits_and_overrides.extract_options!
-
@traits = traits_and_overrides
-
end
-
-
1
def run(runner_strategy = @strategy, &block)
-
factory = FactoryGirl.factory_by_name(@name)
-
-
factory.compile
-
-
if @traits.any?
-
factory = factory.with_traits(@traits)
-
end
-
-
instrumentation_payload = { name: @name, strategy: runner_strategy }
-
-
ActiveSupport::Notifications.instrument('factory_girl.run_factory', instrumentation_payload) do
-
factory.run(runner_strategy, @overrides, &block)
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class << self
-
# An Array of strings specifying locations that should be searched for
-
# factory definitions. By default, factory_girl will attempt to require
-
# "factories," "test/factories," and "spec/factories." Only the first
-
# existing file will be loaded.
-
1
attr_accessor :definition_file_paths
-
end
-
-
1
self.definition_file_paths = %w(factories test/factories spec/factories)
-
-
1
def self.find_definitions
-
4
absolute_definition_file_paths = definition_file_paths.map { |path| File.expand_path(path) }
-
-
1
absolute_definition_file_paths.uniq.each do |path|
-
3
load("#{path}.rb") if File.exists?("#{path}.rb")
-
-
3
if File.directory? path
-
Dir[File.join(path, '**', '*.rb')].sort.each do |file|
-
load file
-
end
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
# @api private
-
1
class NullFactory
-
1
attr_reader :definition
-
-
1
def initialize
-
@definition = Definition.new(:null_factory)
-
end
-
-
1
delegate :defined_traits, :callbacks, :attributes, :constructor,
-
:to_create, to: :definition
-
-
1
def compile; end
-
1
def class_name; end
-
1
def evaluator_class; FactoryGirl::Evaluator; end
-
1
def hierarchy_class; FactoryGirl::DefinitionHierarchy; end
-
end
-
end
-
1
module FactoryGirl
-
# @api private
-
1
class NullObject < ::BasicObject
-
1
def initialize(methods_to_respond_to)
-
@methods_to_respond_to = methods_to_respond_to.map(&:to_s)
-
end
-
-
1
def method_missing(name, *args, &block)
-
if respond_to?(name)
-
nil
-
else
-
super
-
end
-
end
-
-
1
def respond_to?(method, include_private=false)
-
@methods_to_respond_to.include? method.to_s
-
end
-
-
1
def respond_to_missing?(*args)
-
false
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
class Registry
-
1
include Enumerable
-
-
1
attr_reader :name
-
-
1
def initialize(name)
-
4
@name = name
-
4
@items = Decorator::ClassKeyHash.new({})
-
end
-
-
1
def clear
-
@items.clear
-
end
-
-
1
def each(&block)
-
@items.values.uniq.each(&block)
-
end
-
-
1
def find(name)
-
if registered?(name)
-
@items[name]
-
else
-
raise ArgumentError, "#{@name} not registered: #{name}"
-
end
-
end
-
-
1
alias :[] :find
-
-
1
def register(name, item)
-
5
@items[name] = item
-
end
-
-
1
def registered?(name)
-
@items.key?(name)
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
def self.reload
-
reset_configuration
-
register_default_strategies
-
register_default_callbacks
-
find_definitions
-
end
-
end
-
1
module FactoryGirl
-
-
# Sequences are defined using sequence within a FactoryGirl.define block.
-
# Sequence values are generated using next.
-
# @api private
-
1
class Sequence
-
1
attr_reader :name
-
-
1
def initialize(name, *args, &proc)
-
@name = name
-
@proc = proc
-
-
options = args.extract_options!
-
@value = args.first || 1
-
@aliases = options.fetch(:aliases) { [] }
-
-
if !@value.respond_to?(:peek)
-
@value = EnumeratorAdapter.new(@value)
-
end
-
end
-
-
1
def next(scope = nil)
-
if @proc && scope
-
scope.instance_exec(value, &@proc)
-
elsif @proc
-
@proc.call(value)
-
else
-
value
-
end
-
ensure
-
increment_value
-
end
-
-
1
def names
-
[@name] + @aliases
-
end
-
-
1
private
-
-
1
def value
-
@value.peek
-
end
-
-
1
def increment_value
-
@value.next
-
end
-
-
1
class EnumeratorAdapter
-
1
def initialize(value)
-
@value = value
-
end
-
-
1
def peek
-
@value
-
end
-
-
1
def next
-
@value = @value.next
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
module Strategy
-
1
class AttributesFor
-
1
def association(runner)
-
runner.run(:null)
-
end
-
-
1
def result(evaluation)
-
evaluation.hash
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
module Strategy
-
1
class Build
-
1
def association(runner)
-
runner.run
-
end
-
-
1
def result(evaluation)
-
evaluation.object.tap do |instance|
-
evaluation.notify(:after_build, instance)
-
end
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
module Strategy
-
1
class Create
-
1
def association(runner)
-
runner.run
-
end
-
-
1
def result(evaluation)
-
evaluation.object.tap do |instance|
-
evaluation.notify(:after_build, instance)
-
evaluation.notify(:before_create, instance)
-
evaluation.create(instance)
-
evaluation.notify(:after_create, instance)
-
end
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
module Strategy
-
1
class Null
-
1
def association(runner)
-
end
-
-
1
def result(evaluation)
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
1
module Strategy
-
1
class Stub
-
1
@@next_id = 1000
-
-
1
def association(runner)
-
runner.run(:build_stubbed)
-
end
-
-
1
def result(evaluation)
-
evaluation.object.tap do |instance|
-
stub_database_interaction_on_result(instance)
-
evaluation.notify(:after_stub, instance)
-
end
-
end
-
-
1
private
-
-
1
def next_id
-
@@next_id += 1
-
end
-
-
1
def stub_database_interaction_on_result(result_instance)
-
result_instance.id ||= next_id
-
-
result_instance.instance_eval do
-
def persisted?
-
!new_record?
-
end
-
-
def new_record?
-
id.nil?
-
end
-
-
def save(*args)
-
raise 'stubbed models are not allowed to access the database'
-
end
-
-
def destroy(*args)
-
raise 'stubbed models are not allowed to access the database'
-
end
-
-
def connection
-
raise 'stubbed models are not allowed to access the database'
-
end
-
-
def reload
-
raise 'stubbed models are not allowed to access the database'
-
end
-
-
def update_attribute(*args)
-
raise 'stubbed models are not allowed to access the database'
-
end
-
-
def update_column(*args)
-
raise 'stubbed models are not allowed to access the database'
-
end
-
end
-
-
created_at_missing_default = result_instance.respond_to?(:created_at) && !result_instance.created_at
-
result_instance_missing_created_at = !result_instance.respond_to?(:created_at)
-
-
if created_at_missing_default || result_instance_missing_created_at
-
result_instance.instance_eval do
-
def created_at
-
@created_at ||= Time.now.in_time_zone
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
# @api private
-
1
class StrategyCalculator
-
1
def initialize(name_or_object)
-
@name_or_object = name_or_object
-
end
-
-
1
def strategy
-
if strategy_is_object?
-
@name_or_object
-
else
-
strategy_name_to_object
-
end
-
end
-
-
1
private
-
-
1
def strategy_is_object?
-
@name_or_object.is_a?(Class)
-
end
-
-
1
def strategy_name_to_object
-
FactoryGirl.strategy_by_name(@name_or_object)
-
end
-
end
-
end
-
1
module FactoryGirl
-
# @api private
-
1
class StrategySyntaxMethodRegistrar
-
1
def initialize(strategy_name)
-
5
@strategy_name = strategy_name
-
end
-
-
1
def define_strategy_methods
-
5
define_singular_strategy_method
-
5
define_list_strategy_method
-
5
define_pair_strategy_method
-
end
-
-
1
private
-
-
1
def define_singular_strategy_method
-
5
strategy_name = @strategy_name
-
-
5
define_syntax_method(strategy_name) do |name, *traits_and_overrides, &block|
-
FactoryRunner.new(name, strategy_name, traits_and_overrides).run(&block)
-
end
-
end
-
-
1
def define_list_strategy_method
-
5
strategy_name = @strategy_name
-
-
5
define_syntax_method("#{strategy_name}_list") do |name, amount, *traits_and_overrides, &block|
-
amount.times.map { send(strategy_name, name, *traits_and_overrides, &block) }
-
end
-
end
-
-
1
def define_pair_strategy_method
-
5
strategy_name = @strategy_name
-
-
5
define_syntax_method("#{strategy_name}_pair") do |name, *traits_and_overrides, &block|
-
2.times.map { send(strategy_name, name, *traits_and_overrides, &block) }
-
end
-
end
-
-
1
def define_syntax_method(name, &block)
-
15
FactoryGirl::Syntax::Methods.module_exec do
-
15
define_method(name, &block)
-
end
-
end
-
end
-
end
-
1
require 'factory_girl/syntax/methods'
-
1
require 'factory_girl/syntax/default'
-
-
1
module FactoryGirl
-
1
module Syntax
-
end
-
end
-
1
module FactoryGirl
-
1
module Syntax
-
1
module Default
-
1
include Methods
-
-
1
def define(&block)
-
DSL.run(block)
-
end
-
-
1
def modify(&block)
-
ModifyDSL.run(block)
-
end
-
-
1
class DSL
-
1
def factory(name, options = {}, &block)
-
factory = Factory.new(name, options)
-
proxy = FactoryGirl::DefinitionProxy.new(factory.definition)
-
proxy.instance_eval(&block) if block_given?
-
-
FactoryGirl.register_factory(factory)
-
-
proxy.child_factories.each do |(child_name, child_options, child_block)|
-
parent_factory = child_options.delete(:parent) || name
-
factory(child_name, child_options.merge(parent: parent_factory), &child_block)
-
end
-
end
-
-
1
def sequence(name, *args, &block)
-
FactoryGirl.register_sequence(Sequence.new(name, *args, &block))
-
end
-
-
1
def trait(name, &block)
-
FactoryGirl.register_trait(Trait.new(name, &block))
-
end
-
-
1
def to_create(&block)
-
FactoryGirl.to_create(&block)
-
end
-
-
1
def skip_create
-
FactoryGirl.skip_create
-
end
-
-
1
def initialize_with(&block)
-
FactoryGirl.initialize_with(&block)
-
end
-
-
1
def self.run(block)
-
new.instance_eval(&block)
-
end
-
-
1
delegate :before, :after, :callback, to: :configuration
-
-
1
private
-
-
1
def configuration
-
FactoryGirl.configuration
-
end
-
end
-
-
1
class ModifyDSL
-
1
def factory(name, options = {}, &block)
-
factory = FactoryGirl.factory_by_name(name)
-
proxy = FactoryGirl::DefinitionProxy.new(factory.definition.overridable)
-
proxy.instance_eval(&block)
-
end
-
-
1
def self.run(block)
-
new.instance_eval(&block)
-
end
-
end
-
end
-
end
-
-
1
extend Syntax::Default
-
end
-
1
module FactoryGirl
-
1
module Syntax
-
## This module is a container for all strategy methods provided by
-
## FactoryGirl. This includes all the default strategies provided ({Methods#build},
-
## {Methods#create}, {Methods#build_stubbed}, and {Methods#attributes_for}), as well as
-
## the complementary *_list methods.
-
## @example singular factory execution
-
## # basic use case
-
## build(:completed_order)
-
##
-
## # factory yielding its result to a block
-
## create(:post) do |post|
-
## create(:comment, post: post)
-
## end
-
##
-
## # factory with attribute override
-
## attributes_for(:post, title: "I love Ruby!")
-
##
-
## # factory with traits and attribute override
-
## build_stubbed(:user, :admin, :male, name: "John Doe")
-
##
-
## @example multiple factory execution
-
## # basic use case
-
## build_list(:completed_order, 2)
-
## create_list(:completed_order, 2)
-
##
-
## # factory with attribute override
-
## attributes_for_list(:post, 4, title: "I love Ruby!")
-
##
-
## # factory with traits and attribute override
-
## build_stubbed_list(:user, 15, :admin, :male, name: "John Doe")
-
1
module Methods
-
# @!parse FactoryGirl.register_default_strategies
-
# @!method build(name, *traits_and_overrides, &block)
-
# (see #strategy_method)
-
# Builds a registered factory by name.
-
# @return [Object] instantiated object defined by the factory
-
-
# @!method create(name, *traits_and_overrides, &block)
-
# (see #strategy_method)
-
# Creates a registered factory by name.
-
# @return [Object] instantiated object defined by the factory
-
-
# @!method build_stubbed(name, *traits_and_overrides, &block)
-
# (see #strategy_method)
-
# Builds a stubbed registered factory by name.
-
# @return [Object] instantiated object defined by the factory
-
-
# @!method attributes_for(name, *traits_and_overrides, &block)
-
# (see #strategy_method)
-
# Generates a hash of attributes for a registered factory by name.
-
# @return [Hash] hash of attributes for the factory
-
-
# @!method build_list(name, amount, *traits_and_overrides)
-
# (see #strategy_method_list)
-
# @return [Array] array of built objects defined by the factory
-
-
# @!method create_list(name, amount, *traits_and_overrides)
-
# (see #strategy_method_list)
-
# @return [Array] array of created objects defined by the factory
-
-
# @!method build_stubbed_list(name, amount, *traits_and_overrides)
-
# (see #strategy_method_list)
-
# @return [Array] array of stubbed objects defined by the factory
-
-
# @!method attributes_for_list(name, amount, *traits_and_overrides)
-
# (see #strategy_method_list)
-
# @return [Array<Hash>] array of attribute hashes for the factory
-
-
# @!method strategy_method
-
# @!visibility private
-
# @param [Symbol] name name of the factory to build
-
# @param [Array<Symbol, Symbol, Hash>] traits_and_overrides splat args traits and a hash of overrides
-
# @param [Proc] block block to be executed
-
-
# @!method strategy_method_list
-
# @!visibility private
-
# @param [Symbol] name name of the factory to execute
-
# @param [Integer] amount the number of instances to execute
-
# @param [Array<Symbol, Symbol, Hash>] traits_and_overrides splat args traits and a hash of overrides
-
-
# Generates and returns the next value in a sequence.
-
#
-
# Arguments:
-
# name: (Symbol)
-
# The name of the sequence that a value should be generated for.
-
#
-
# Returns:
-
# The next value in the sequence. (Object)
-
1
def generate(name)
-
FactoryGirl.sequence_by_name(name).next
-
end
-
end
-
end
-
end
-
1
module FactoryGirl
-
# @api private
-
1
class SyntaxRunner
-
1
include Syntax::Methods
-
end
-
end
-
1
module FactoryGirl
-
# @api private
-
1
class Trait
-
1
attr_reader :name, :definition
-
-
1
def initialize(name, &block)
-
@name = name
-
@block = block
-
@definition = Definition.new(@name)
-
-
proxy = FactoryGirl::DefinitionProxy.new(@definition)
-
proxy.instance_eval(&@block) if block_given?
-
end
-
-
1
delegate :add_callback, :declare_attribute, :to_create, :define_trait, :constructor,
-
:callbacks, :attributes, to: :@definition
-
-
1
def names
-
[@name]
-
end
-
-
1
def ==(other)
-
name == other.name &&
-
block == other.block
-
end
-
-
1
protected
-
1
attr_reader :block
-
end
-
end
-
1
module FactoryGirl
-
1
VERSION = '4.4.0'
-
end
-
1
require 'factory_girl_rails/railtie'
-
-
1
module FactoryGirlRails
-
end
-
1
require 'factory_girl_rails/generators/rspec_generator'
-
1
require 'factory_girl_rails/generators/non_rspec_generator'
-
1
require 'factory_girl_rails/generators/null_generator'
-
-
1
module FactoryGirlRails
-
1
class Generator
-
1
def initialize(config)
-
1
@generators = if config.respond_to?(:app_generators)
-
1
config.app_generators
-
else
-
config.generators
-
end
-
end
-
-
1
def run
-
1
generator.new(@generators).run
-
end
-
-
1
def generator
-
1
if factory_girl_disabled?
-
Generators::NullGenerator
-
else
-
1
if test_framework == :rspec
-
1
Generators::RSpecGenerator
-
else
-
Generators::NonRSpecGenerator
-
end
-
end
-
end
-
-
1
def test_framework
-
1
rails_options[:test_framework]
-
end
-
-
1
def factory_girl_disabled?
-
1
rails_options[:factory_girl] == false
-
end
-
-
1
def rails_options
-
2
@generators.options[:rails]
-
end
-
end
-
end
-
1
module FactoryGirlRails
-
1
module Generators
-
1
class NonRSpecGenerator
-
1
def initialize(generators)
-
@generators = generators
-
end
-
-
1
def run
-
@generators.test_framework test_framework, fixture: false, fixture_replacement: :factory_girl
-
end
-
-
1
private
-
-
1
def test_framework
-
@generators.options[:rails][:test_framework]
-
end
-
end
-
end
-
end
-
1
module FactoryGirlRails
-
1
module Generators
-
1
class NullGenerator
-
1
def initialize(generators)
-
end
-
-
1
def run
-
end
-
end
-
end
-
end
-
1
module FactoryGirlRails
-
1
module Generators
-
1
class RSpecGenerator
-
1
def initialize(generators)
-
1
@generators = generators
-
end
-
-
1
def run
-
1
@generators.fixture_replacement fixture_replacement_setting, dir: factory_girl_directory
-
end
-
-
1
private
-
-
1
def fixture_replacement_setting
-
1
@generators.options[:rails][:fixture_replacement] || :factory_girl
-
end
-
-
1
def factory_girl_directory
-
1
@generators.options.fetch(:factory_girl, { dir: 'spec/factories' })[:dir]
-
end
-
end
-
end
-
end
-
1
require 'factory_girl'
-
1
require 'factory_girl_rails/generator'
-
1
require 'rails'
-
-
1
module FactoryGirl
-
1
class Railtie < Rails::Railtie
-
-
1
initializer "factory_girl.set_fixture_replacement" do
-
1
FactoryGirlRails::Generator.new(config).run
-
end
-
-
1
initializer "factory_girl.set_factory_paths" do
-
1
FactoryGirl.definition_file_paths = [
-
Rails.root.join('factories'),
-
Rails.root.join('test', 'factories'),
-
Rails.root.join('spec', 'factories')
-
]
-
end
-
-
1
config.after_initialize do
-
1
FactoryGirl.find_definitions
-
-
1
if defined?(Spring)
-
Spring.after_fork { FactoryGirl.reload }
-
end
-
end
-
end
-
end
-
1
class Array
-
1
unless self.method_defined? :sample
-
def sample(n = nil)
-
#based on code from https://github.com/marcandre/backports
-
size = self.length
-
return self[Kernel.rand(size)] if n.nil?
-
-
n = n.to_int
-
raise ArgumentError, "negative array size" if n < 0
-
-
n = size if n > size
-
-
result = Array.new(self)
-
n.times do |i|
-
r = i + Kernel.rand(size - i)
-
result[i], result[r] = result[r], result[i]
-
end
-
result[n..size] = []
-
result
-
end
-
end
-
end
-
# For Ruby 1.8
-
1
unless :symbol.respond_to?(:downcase)
-
Symbol.class_eval do
-
def downcase
-
to_s.downcase.intern
-
end
-
end
-
end
-
-
# -*- coding: utf-8 -*-
-
1
mydir = File.expand_path(File.dirname(__FILE__))
-
-
1
begin
-
1
require 'psych'
-
rescue LoadError
-
end
-
-
1
require 'i18n'
-
1
require 'set' # Fixes a bug in i18n 0.6.11
-
-
1
if I18n.respond_to?(:enforce_available_locales=)
-
1
I18n.enforce_available_locales = true
-
end
-
1
I18n.load_path += Dir[File.join(mydir, 'locales', '*.yml')]
-
-
-
1
module Faker
-
1
class Config
-
1
@locale = nil
-
-
1
class << self
-
1
attr_writer :locale
-
1
def locale
-
@locale || I18n.locale
-
end
-
end
-
end
-
-
1
class Base
-
1
Numbers = Array(0..9)
-
1
ULetters = Array('A'..'Z')
-
1
Letters = ULetters + Array('a'..'z')
-
-
1
class << self
-
## make sure numerify results doesn’t start with a zero
-
1
def numerify(number_string)
-
number_string.sub(/#/) { (rand(9)+1).to_s }.gsub(/#/) { rand(10).to_s }
-
end
-
-
1
def letterify(letter_string)
-
letter_string.gsub(/\?/) { ULetters.sample }
-
end
-
-
1
def bothify(string)
-
letterify(numerify(string))
-
end
-
-
# Given a regular expression, attempt to generate a string
-
# that would match it. This is a rather simple implementation,
-
# so don't be shocked if it blows up on you in a spectacular fashion.
-
#
-
# It does not handle ., *, unbounded ranges such as {1,},
-
# extensions such as (?=), character classes, some abbreviations
-
# for character classes, and nested parentheses.
-
#
-
# I told you it was simple. :) It's also probably dog-slow,
-
# so you shouldn't use it.
-
#
-
# It will take a regex like this:
-
#
-
# /^[A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}$/
-
#
-
# and generate a string like this:
-
#
-
# "U3V 3TP"
-
#
-
1
def regexify(re)
-
re = re.source if re.respond_to?(:source) # Handle either a Regexp or a String that looks like a Regexp
-
re.
-
gsub(/^\/?\^?/, '').gsub(/\$?\/?$/, ''). # Ditch the anchors
-
gsub(/\{(\d+)\}/, '{\1,\1}').gsub(/\?/, '{0,1}'). # All {2} become {2,2} and ? become {0,1}
-
gsub(/(\[[^\]]+\])\{(\d+),(\d+)\}/) {|match| $1 * Array(Range.new($2.to_i, $3.to_i)).sample }. # [12]{1,2} becomes [12] or [12][12]
-
gsub(/(\([^\)]+\))\{(\d+),(\d+)\}/) {|match| $1 * Array(Range.new($2.to_i, $3.to_i)).sample }. # (12|34){1,2} becomes (12|34) or (12|34)(12|34)
-
gsub(/(\\?.)\{(\d+),(\d+)\}/) {|match| $1 * Array(Range.new($2.to_i, $3.to_i)).sample }. # A{1,2} becomes A or AA or \d{3} becomes \d\d\d
-
gsub(/\((.*?)\)/) {|match| match.gsub(/[\(\)]/, '').split('|').sample }. # (this|that) becomes 'this' or 'that'
-
gsub(/\[([^\]]+)\]/) {|match| match.gsub(/(\w\-\w)/) {|range| Array(Range.new(*range.split('-'))).sample } }. # All A-Z inside of [] become C (or X, or whatever)
-
gsub(/\[([^\]]+)\]/) {|match| $1.split('').sample }. # All [ABC] become B (or A or C)
-
gsub('\d') {|match| Numbers.sample }.
-
gsub('\w') {|match| Letters.sample }
-
end
-
-
# Helper for the common approach of grabbing a translation
-
# with an array of values and selecting one of them.
-
1
def fetch(key)
-
fetched = translate("faker.#{key}")
-
fetched = fetched.sample if fetched.respond_to?(:sample)
-
if fetched.match(/^\//) and fetched.match(/\/$/) # A regex
-
regexify(fetched)
-
else
-
fetched
-
end
-
end
-
-
# Load formatted strings from the locale, "parsing" them
-
# into method calls that can be used to generate a
-
# formatted translation: e.g., "#{first_name} #{last_name}".
-
1
def parse(key)
-
fetch(key).scan(/(\(?)#\{([A-Za-z]+\.)?([^\}]+)\}([^#]+)?/).map {|prefix, kls, meth, etc|
-
# If the token had a class Prefix (e.g., Name.first_name)
-
# grab the constant, otherwise use self
-
cls = kls ? Faker.const_get(kls.chop) : self
-
-
# If an optional leading parentheses is not present, prefix.should == "", otherwise prefix.should == "("
-
# In either case the information will be retained for reconstruction of the string.
-
text = prefix
-
-
# If the class has the method, call it, otherwise
-
# fetch the transation (i.e., faker.name.first_name)
-
text += cls.respond_to?(meth) ? cls.send(meth) : fetch("#{(kls || self).to_s.split('::').last.downcase}.#{meth.downcase}")
-
-
# And tack on spaces, commas, etc. left over in the string
-
text += etc.to_s
-
}.join
-
end
-
-
# Call I18n.translate with our configured locale if no
-
# locale is specified
-
1
def translate(*args)
-
opts = args.last.is_a?(Hash) ? args.pop : {}
-
opts[:locale] ||= Faker::Config.locale
-
opts[:raise] = true
-
I18n.translate(*(args.push(opts)))
-
rescue I18n::MissingTranslationData
-
# Super-simple fallback -- fallback to en if the
-
# translation was missing. If the translation isn't
-
# in en either, then it will raise again.
-
I18n.translate(*(args.push(opts.merge(:locale => :en))))
-
end
-
-
1
def flexible(key)
-
6
@flexible_key = key
-
end
-
-
# You can add whatever you want to the locale file, and it will get caught here.
-
# E.g., in your locale file, create a
-
# name:
-
# girls_name: ["Alice", "Cheryl", "Tatiana"]
-
# Then you can call Faker::Name.girls_name and it will act like #first_name
-
1
def method_missing(m, *args, &block)
-
super unless @flexible_key
-
-
# Use the alternate form of translate to get a nil rather than a "missing translation" string
-
if translation = translate(:faker)[@flexible_key][m]
-
translation.respond_to?(:sample) ? translation.sample : translation
-
else
-
super
-
end
-
end
-
-
# Generates a random value between the interval
-
1
def rand_in_range(from, to)
-
from, to = to, from if to < from
-
Random.new.rand(from..to)
-
end
-
end
-
end
-
end
-
-
1
require 'faker/address'
-
1
require 'faker/code'
-
1
require 'faker/company'
-
1
require 'faker/finance'
-
1
require 'faker/internet'
-
1
require 'faker/lorem'
-
1
require 'faker/name'
-
1
require 'faker/team'
-
1
require 'faker/phone_number'
-
1
require 'faker/business'
-
1
require 'faker/commerce'
-
1
require 'faker/version'
-
1
require 'faker/number'
-
1
require 'faker/bitcoin'
-
1
require 'faker/avatar'
-
1
require 'faker/date'
-
1
require 'faker/time'
-
1
require 'faker/number'
-
1
require 'faker/hacker'
-
1
require 'faker/app'
-
-
1
require 'extensions/array'
-
1
require 'extensions/symbol'
-
1
module Faker
-
1
class Address < Base
-
1
flexible :address
-
-
1
class << self
-
1
def city
-
parse('address.city')
-
end
-
-
1
def street_name
-
parse('address.street_name')
-
end
-
-
1
def street_address(include_secondary = false)
-
numerify(parse('address.street_address') + (include_secondary ? ' ' + secondary_address : ''))
-
end
-
-
1
def secondary_address
-
numerify(fetch('address.secondary_address'))
-
end
-
-
1
def building_number
-
bothify(fetch('address.building_number'))
-
end
-
-
1
def zip_code(state_abbreviation = '')
-
return bothify(fetch('address.postcode')) if state_abbreviation === ''
-
-
# provide a zip code that is valid for the state provided
-
# see http://www.fincen.gov/forms/files/us_state_territory_zip_codes.pdf
-
bothify(fetch('address.postcode_by_state.' + state_abbreviation))
-
end
-
-
1
def time_zone
-
fetch('address.time_zone')
-
end
-
-
1
alias_method :zip, :zip_code
-
1
alias_method :postcode, :zip_code
-
-
1
def street_suffix; fetch('address.street_suffix'); end
-
1
def city_suffix; fetch('address.city_suffix'); end
-
1
def city_prefix; fetch('address.city_prefix'); end
-
1
def state_abbr; fetch('address.state_abbr'); end
-
1
def state; fetch('address.state'); end
-
1
def country; fetch('address.country'); end
-
1
def country_code; fetch('address.country_code'); end
-
-
1
def latitude
-
((rand * 180) - 90).to_s
-
end
-
-
1
def longitude
-
((rand * 360) - 180).to_s
-
end
-
-
end
-
end
-
end
-
1
module Faker
-
1
class App < Base
-
1
class << self
-
-
1
def name
-
fetch('app.name')
-
end
-
-
1
def version
-
if parse('app.version') == ""
-
numerify(fetch('app.version'))
-
else
-
parse('app.version')
-
end
-
end
-
-
1
def author
-
parse('app.author')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Avatar < Base
-
1
class << self
-
1
SUPPORTED_FORMATS = %w(png jpg bmp)
-
-
1
def image(slug = nil, size = '300x300', format = 'png')
-
raise ArgumentError, "Size should be specified in format 300x300" unless size.match(/^[0-9]+x[0-9]+$/)
-
raise ArgumentError, "Supported formats are #{SUPPORTED_FORMATS.join(', ')}" unless SUPPORTED_FORMATS.include?(format)
-
slug ||= Faker::Lorem.words.join
-
"http://robohash.org/#{slug}.#{format}?size=#{size}"
-
end
-
end
-
end
-
end
-
1
require 'digest'
-
1
require 'securerandom'
-
-
1
module Faker
-
1
class Bitcoin < Base
-
1
class << self
-
-
1
def address
-
hash = SecureRandom.hex(20)
-
version = 0
-
packed = version.chr + [hash].pack("H*")
-
checksum = Digest::SHA2.digest(Digest::SHA2.digest(packed))[0..3]
-
base58(packed + checksum)
-
end
-
-
1
protected
-
-
1
def base58(str)
-
alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
-
base = alphabet.size
-
-
lv = 0
-
str.split('').reverse.each_with_index { |v,i| lv += v.unpack('C')[0] * 256**i }
-
-
ret = ''
-
while lv > 0 do
-
lv, mod = lv.divmod(base)
-
ret << alphabet[mod]
-
end
-
-
npad = str.match(/^#{0.chr}*/)[0].to_s.size
-
'1'*npad + ret.reverse
-
end
-
-
end
-
end
-
end
-
1
require 'date'
-
-
1
module Faker
-
1
class Business < Base
-
1
flexible :business
-
-
1
class << self
-
1
def credit_card_number
-
fetch('business.credit_card_numbers')
-
end
-
-
1
def credit_card_expiry_date
-
::Date.parse(fetch('business.credit_card_expiry_dates'))
-
end
-
-
1
def credit_card_type
-
fetch('business.credit_card_types')
-
end
-
end
-
-
end
-
end
-
1
module Faker
-
1
class Code < Base
-
1
class << self
-
# By default generates 10 sign isbn code in format 123456789-X
-
# You can pass 13 to generate new 13 sign code
-
1
def isbn(base = 10)
-
base == 13 ? generate_base13_isbn : generate_base10_isbn
-
end
-
-
# By default generates 13 sign ean code in format 1234567890123
-
# You can pass 8 to generate ean8 code
-
1
def ean(base = 13)
-
base == 8 ? generate_base8_ean : generate_base13_ean
-
end
-
-
1
def rut
-
value = Number.number(8)
-
vd = rut_verificator_digit(value)
-
value << "-#{vd}"
-
end
-
-
1
private
-
-
1
def generate_base10_isbn
-
values = regexify(/\d{9}/)
-
remainder = sum(values) { |value, index| (index + 1) * value.to_i } % 11
-
values << "-#{remainder == 10 ? 'X' : remainder}"
-
end
-
-
1
def generate_base13_isbn
-
values = regexify(/\d{12}/)
-
remainder = sum(values) { |value, index| index.even? ? value.to_i : value.to_i * 3 } % 10
-
values << "-#{((10 - remainder) % 10)}"
-
end
-
-
1
def sum(values, &block)
-
values.split(//).each_with_index.inject(0) do |sum, (value, index)|
-
sum + block.call(value, index)
-
end
-
end
-
-
1
def generate_base8_ean
-
values = regexify(/\d{7}/)
-
check_digit = 10 - values.split(//).each_with_index.inject(0){ |s, (v, i)| s + v.to_i * EAN_CHECK_DIGIT8[i] } % 10
-
values << (check_digit == 10 ? 0 : check_digit).to_s
-
end
-
-
1
def generate_base13_ean
-
values = regexify(/\d{12}/)
-
check_digit = 10 - values.split(//).each_with_index.inject(0){ |s, (v, i)| s + v.to_i * EAN_CHECK_DIGIT13[i] } % 10
-
values << (check_digit == 10 ? 0 : check_digit).to_s
-
end
-
-
1
EAN_CHECK_DIGIT8 = [3, 1, 3, 1, 3, 1, 3]
-
1
EAN_CHECK_DIGIT13 = [1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3]
-
-
1
def rut_verificator_digit(rut)
-
total = rut.to_s.rjust(8, '0').split(//).zip(%w(3 2 7 6 5 4 3 2)).collect{|a, b| a.to_i * b.to_i}.inject(:+)
-
(11 - total % 11).to_s.gsub(/10/, 'k').gsub(/11/, '0')
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Commerce < Base
-
-
1
class << self
-
1
def color
-
fetch('commerce.color')
-
end
-
-
1
def department(max = 3, fixed_amount = false)
-
num = max if fixed_amount
-
num ||= 1 + rand(max)
-
-
categories = categories(num)
-
-
if num > 1
-
merge_categories(categories)
-
else
-
categories[0]
-
end
-
end
-
-
1
def product_name
-
fetch('commerce.product_name.adjective') + ' ' + fetch('commerce.product_name.material') + ' ' + fetch('commerce.product_name.product')
-
end
-
-
1
def price
-
random = Random.new
-
(random.rand(0..100.0) * 100).floor/100.0
-
end
-
-
1
private
-
-
1
def categories(num)
-
categories = []
-
while categories.length < num do
-
category = fetch('commerce.department')
-
categories << category unless categories.include?(category)
-
end
-
-
categories
-
end
-
-
1
def merge_categories(categories)
-
separator = fetch('separator')
-
comma_separated = categories.slice!(0...-1).join(', ')
-
-
[comma_separated, categories[0]].join(separator)
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Company < Base
-
1
flexible :company
-
-
1
class << self
-
1
def name
-
parse('company.name')
-
end
-
-
1
def suffix
-
fetch('company.suffix')
-
end
-
-
# Generate a buzzword-laden catch phrase.
-
1
def catch_phrase
-
translate('faker.company.buzzwords').collect {|list| list.sample }.join(' ')
-
end
-
-
# When a straight answer won't do, BS to the rescue!
-
1
def bs
-
translate('faker.company.bs').collect {|list| list.sample }.join(' ')
-
end
-
-
1
def ein
-
('%09d' % rand(10 ** 9)).gsub(/(\d\d)(\d\d\d\d\d\d\d)/, '\\1-\\2')
-
end
-
-
1
def duns_number
-
('%09d' % rand(10 ** 9)).gsub(/(\d\d)(\d\d\d)(\d\d\d\d)/, '\\1-\\2-\\3')
-
end
-
-
# Get a random company logo url in GIF format.
-
1
def logo
-
rand_num = Random.rand(76) + 1
-
"http://www.biz-logo.com/examples/#{ rand_num < 10 ? "00" : "0" }#{rand_num}.gif"
-
end
-
end
-
-
end
-
end
-
1
module Faker
-
1
class Date < Base
-
1
class << self
-
1
def between(from, to)
-
from = get_date_object(from)
-
to = get_date_object(to)
-
-
Faker::Base::rand_in_range(from, to)
-
end
-
-
1
def forward(days = 365)
-
from = ::Date.today + 1
-
to = ::Date.today + days
-
-
between(from, to).to_date
-
end
-
-
1
def backward(days = 365)
-
from = ::Date.today - days
-
to = ::Date.today - 1
-
-
between(from, to).to_date
-
end
-
-
1
def birthday(min_age = 18, max_age = 65)
-
t = ::Date.today
-
from = ::Date.new(t.year - min_age, t.month, t.day)
-
to = ::Date.new(t.year - max_age, t.month, t.day)
-
-
between(from, to).to_date
-
end
-
-
1
private
-
-
1
def get_date_object(date)
-
date = ::Date.parse(date) if date.is_a?(String)
-
date = date.to_date if date.respond_to?(:to_date)
-
date
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Finance < Base
-
1
CREDIT_CARD_TYPES = [ :visa, :mastercard, :discover, :american_express, :diners_club, :jcb, :switch, :solo, :dankort, :maestro, :forbrugsforeningen, :laser ]
-
-
1
class << self
-
1
def credit_card(*types)
-
types = CREDIT_CARD_TYPES if types.empty?
-
type = types.sample
-
template = numerify(fetch("credit_card.#{type}"))
-
-
# calculate the luhn checksum digit
-
multiplier = 1
-
luhn_sum = template.gsub(/[^0-9]/, '').split('').reverse.map(&:to_i).inject(0) do |sum, digit|
-
multiplier = (multiplier == 2 ? 1 : 2)
-
sum + (digit * multiplier).to_s.split('').map(&:to_i).inject(0) { |digit_sum, cur| digit_sum + cur }
-
end
-
# the sum plus whatever the last digit is must be a multiple of 10. So, the
-
# last digit must be 10 - the last digit of the sum.
-
luhn_digit = (10 - (luhn_sum % 10)) % 10
-
-
template.gsub! 'L', luhn_digit.to_s
-
template
-
end
-
end
-
end
-
end
-
#Port of http://shinytoylabs.com/jargon/
-
1
module Faker
-
1
class Hacker < Base
-
1
flexible :hacker
-
-
1
class << self
-
1
def say_something_smart
-
phrases.sample
-
end
-
-
1
def abbreviation; fetch('hacker.abbreviation'); end
-
1
def adjective; fetch('hacker.adjective'); end
-
1
def noun; fetch('hacker.noun'); end
-
1
def verb; fetch('hacker.verb'); end
-
1
def ingverb; fetch('hacker.ingverb'); end
-
-
1
def phrases
-
[ "If we #{verb} the #{noun}, we can get to the #{abbreviation} #{noun} through the #{adjective} #{abbreviation} #{noun}!",
-
"We need to #{verb} the #{adjective} #{abbreviation} #{noun}!",
-
"Try to #{verb} the #{abbreviation} #{noun}, maybe it will #{verb} the #{adjective} #{noun}!",
-
"You can't #{verb} the #{noun} without #{ingverb} the #{adjective} #{abbreviation} #{noun}!",
-
"Use the #{adjective} #{abbreviation} #{noun}, then you can #{verb} the #{adjective} #{noun}!",
-
"The #{abbreviation} #{noun} is down, #{verb} the #{adjective} #{noun} so we can #{verb} the #{abbreviation} #{noun}!",
-
"#{ingverb} the #{noun} won't do anything, we need to #{verb} the #{adjective} #{abbreviation} #{noun}!",
-
"I'll #{verb} the #{adjective} #{abbreviation} #{noun}, that should #{noun} the #{abbreviation} #{noun}!"
-
]
-
end
-
end
-
-
end
-
end
-
# encoding: utf-8
-
1
module Faker
-
1
class Internet < Base
-
1
class << self
-
1
def email(name = nil)
-
[ user_name(name), domain_name ].join('@')
-
end
-
-
1
def free_email(name = nil)
-
[ user_name(name), fetch('internet.free_email') ].join('@')
-
end
-
-
1
def safe_email(name = nil)
-
[user_name(name), 'example.'+ %w[org com net].shuffle.first].join('@')
-
end
-
-
1
def user_name(specifier = nil, separators = %w(. _))
-
if specifier.kind_of? String
-
return specifier.scan(/\w+/).shuffle.join(separators.sample).downcase
-
elsif specifier.kind_of? Integer
-
tries = 0 # Don't try forever in case we get something like 1_000_000.
-
begin
-
result = user_name nil, separators
-
tries += 1
-
end while result.length < specifier and tries < 7
-
until result.length >= specifier
-
result = result * 2
-
end
-
return result
-
elsif specifier.kind_of? Range
-
tries = 0
-
begin
-
result = user_name specifier.min, separators
-
tries += 1
-
end while not specifier.include? result.length and tries < 7
-
return result[0...specifier.max]
-
end
-
-
fix_umlauts([
-
Proc.new { Name.first_name.gsub(/\W/, '').downcase },
-
Proc.new {
-
[ Name.first_name, Name.last_name ].map {|n|
-
n.gsub(/\W/, '')
-
}.join(separators.sample).downcase }
-
].sample.call)
-
end
-
-
1
def password(min_length = 8, max_length = 16)
-
temp = Lorem.characters(min_length)
-
diff_length = max_length - min_length
-
if diff_length > 0
-
diff_rand = rand(diff_length + 1)
-
temp += Lorem.characters(diff_rand)
-
end
-
temp = temp[0..min_length] if min_length > 0
-
return temp
-
end
-
-
1
def domain_name
-
[ fix_umlauts(domain_word), domain_suffix ].join('.')
-
end
-
-
1
def fix_umlauts(string)
-
string.gsub(/[äöüß]/i) do |match|
-
case match.downcase
-
when "ä" 'ae'
-
when "ö" 'oe'
-
when "ü" 'ue'
-
when "ß" 'ss'
-
end
-
end
-
end
-
-
1
def domain_word
-
Company.name.split(' ').first.gsub(/\W/, '').downcase
-
end
-
-
1
def domain_suffix
-
fetch('internet.domain_suffix')
-
end
-
-
1
def mac_address(prefix='')
-
prefix_digits = prefix.split(':').map{ |d| d.to_i(16) }
-
address_digits = (6 - prefix_digits.size).times.map{ rand(256) }
-
(prefix_digits + address_digits).map{ |d| '%02x' % d }.join(':')
-
end
-
-
1
def ip_v4_address
-
ary = (2..254).to_a
-
[ary.sample,
-
ary.sample,
-
ary.sample,
-
ary.sample].join('.')
-
end
-
-
1
def ip_v6_address
-
@@ip_v6_space ||= (0..65535).to_a
-
container = (1..8).map{ |_| @@ip_v6_space.sample }
-
container.map{ |n| n.to_s(16) }.join(':')
-
end
-
-
1
def url(host = domain_name, path = "/#{user_name}")
-
"http://#{host}#{path}"
-
end
-
-
1
def slug(words = nil, glue = nil)
-
glue ||= %w[- _ .].sample
-
(words || Faker::Lorem::words(2).join(' ')).gsub(' ', glue).downcase
-
end
-
end
-
end
-
end
-
1
module Faker
-
# Based on Perl's Text::Lorem
-
1
class Lorem < Base
-
1
class << self
-
1
def word
-
translate('faker.lorem.words').sample
-
end
-
-
1
def words(num = 3, supplemental = false)
-
resolved_num = resolve(num)
-
word_list = (
-
translate('faker.lorem.words') +
-
(supplemental ? translate('faker.lorem.supplemental') : [])
-
)
-
word_list = word_list * ((resolved_num / word_list.length) + 1)
-
word_list.shuffle[0, resolved_num]
-
end
-
-
1
def character
-
characters(1)
-
end
-
-
1
def characters(char_count = 255)
-
return '' if char_count.respond_to?(:to_i) && char_count.to_i < 1
-
char_count = resolve(char_count)
-
rand(36**char_count).to_s(36).rjust(char_count, '0').chars.to_a.shuffle.join
-
end
-
-
1
def sentence(word_count = 4, supplemental = false, random_words_to_add = 6)
-
words(word_count + rand(random_words_to_add.to_i).to_i, supplemental).join(' ').capitalize + '.'
-
end
-
-
1
def sentences(sentence_count = 3, supplemental = false)
-
[].tap do |sentences|
-
1.upto(resolve(sentence_count)) do
-
sentences << sentence(3, supplemental)
-
end
-
end
-
end
-
-
1
def paragraph(sentence_count = 3, supplemental = false, random_sentences_to_add = 3)
-
sentences(resolve(sentence_count) + rand(random_sentences_to_add.to_i).to_i, supplemental).join(' ')
-
end
-
-
1
def paragraphs(paragraph_count = 3, supplemental = false)
-
[].tap do |paragraphs|
-
1.upto(resolve(paragraph_count)) do
-
paragraphs << paragraph(3, supplemental)
-
end
-
end
-
end
-
-
1
private
-
-
# If an array or range is passed, a random value will be selected.
-
# All other values are simply returned.
-
1
def resolve(value)
-
case value
-
when Array then value[rand(value.size)]
-
when Range then rand((value.last+1) - value.first) + value.first
-
else value
-
end
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class Name < Base
-
1
flexible :name
-
-
1
class << self
-
-
1
def name
-
parse('name.name')
-
end
-
-
1
def first_name; fetch('name.first_name'); end
-
1
def last_name; fetch('name.last_name'); end
-
1
def prefix; fetch('name.prefix'); end
-
1
def suffix; fetch('name.suffix'); end
-
-
# Generate a buzzword-laden job title
-
# Wordlist from http://www.bullshitjob.com/title/
-
1
def title; fetch('name.title.descriptor') + ' ' + fetch('name.title.level') + ' ' + fetch('name.title.job'); end
-
-
end
-
end
-
end
-
1
module Faker
-
1
class Number < Base
-
1
class << self
-
1
def number(digits)
-
(1..digits).collect {digit}.join
-
end
-
-
1
def decimal(l_digits, r_digits = 2)
-
l_d = self.number(l_digits)
-
r_d = self.number(r_digits)
-
"#{l_d}.#{r_d}"
-
end
-
-
1
def digit
-
(rand() * 9).round.to_s
-
end
-
-
1
def hexadecimal(digits)
-
hex = ""
-
digits.times { hex += rand(15).to_s(16) }
-
hex
-
end
-
-
1
def between(from = 1.00, to = 5000.00)
-
Faker::Base::rand_in_range(from, to)
-
end
-
-
1
def positive(from = 1.00, to = 5000.00)
-
random_number = between(from, to)
-
greater_than_zero(random_number)
-
end
-
-
1
def negative(from = -5000.00, to = -1.00)
-
random_number = between(from, to)
-
less_than_zero(random_number)
-
end
-
-
1
private
-
-
1
def greater_than_zero(number)
-
should_be(number, :>)
-
end
-
-
1
def less_than_zero(number)
-
should_be(number, :<)
-
end
-
-
1
def should_be(number, method_to_compare)
-
if number.send(method_to_compare, 0)
-
number
-
else
-
number * -1
-
end
-
end
-
end
-
end
-
end
-
1
module Faker
-
1
class PhoneNumber < Base
-
1
class << self
-
1
def phone_number
-
if parse('phone_number.formats') == ""
-
numerify(fetch('phone_number.formats'))
-
else
-
parse('phone_number.formats')
-
end
-
end
-
-
1
def cell_phone
-
if parse('cell_phone.formats') == ""
-
numerify(fetch('cell_phone.formats'))
-
else
-
parse('cell_phone.formats')
-
end
-
end
-
-
# US only
-
1
def area_code
-
begin
-
fetch('phone_number.area_code')
-
rescue I18n::MissingTranslationData
-
nil
-
end
-
end
-
-
# US only
-
1
def exchange_code
-
begin
-
fetch('phone_number.exchange_code')
-
rescue I18n::MissingTranslationData
-
nil
-
end
-
end
-
-
# US only
-
# Can be used for both extensions and last four digits of phone number.
-
# Since extensions can be of variable length, this method taks a length parameter
-
1
def subscriber_number(length = 4)
-
begin
-
rand.to_s[2..(1 + length)]
-
rescue I18n::MissingTranslationData
-
nil
-
end
-
end
-
-
1
alias_method :extension, :subscriber_number
-
end
-
end
-
end
-
1
module Faker
-
1
class Team < Base
-
1
flexible :team
-
-
1
class << self
-
1
def name
-
parse('team.name')
-
end
-
-
1
def creature
-
fetch('team.creature')
-
end
-
-
1
def state
-
fetch('faker.address.state').titleize
-
end
-
end
-
-
end
-
end
-
1
module Faker
-
1
class Time < Date
-
1
TIME_RANGES = {
-
:all => (0..23),
-
:day => (9..17),
-
:night => (18..23),
-
:morning => (6..11),
-
:afternoon => (12..17),
-
:evening => (17..21),
-
:midnight => (0..4)
-
}
-
-
1
class << self
-
1
def between(from, to, period = :all)
-
super(from, to).to_time + random_time(period)
-
end
-
-
1
def forward(days = 365, period = :all)
-
super(days).to_time + random_time(period)
-
end
-
-
1
def backward(days = 365, period = :all)
-
super(days).to_time + random_time(period)
-
end
-
-
1
private
-
-
1
def random_time(period)
-
hours(period) + minutes + seconds
-
end
-
-
1
def hours(period)
-
raise ArgumentError, 'invalid period' unless TIME_RANGES.has_key? period
-
hour_at_period = TIME_RANGES[period].to_a.sample
-
-
(60 * 60 * hour_at_period)
-
end
-
-
1
def minutes
-
60 * seconds
-
end
-
-
1
def seconds
-
(0..59).to_a.sample
-
end
-
end
-
end
-
end
-
1
module Faker #:nodoc:
-
1
VERSION = "1.4.3"
-
end
-
1
module FontAwesome
-
1
module Rails
-
1
module IconHelper
-
# Creates an icon tag given an icon name and possible icon
-
# modifiers.
-
#
-
# Examples
-
#
-
# fa_icon "camera-retro"
-
# # => <i class="fa fa-camera-retro"></i>
-
#
-
# fa_icon "camera-retro", text: "Take a photo"
-
# # => <i class="fa fa-camera-retro"></i> Take a photo
-
# fa_icon "chevron-right", text: "Get started", right: true
-
# # => Get started <i class="fa fa-chevron-right"></i>
-
#
-
# fa_icon "camera-retro 2x"
-
# # => <i class="fa fa-camera-retro fa-2x"></i>
-
# fa_icon ["camera-retro", "4x"]
-
# # => <i class="fa fa-camera-retro fa-4x"></i>
-
# fa_icon "spinner spin lg"
-
# # => <i class="fa fa-spinner fa-spin fa-lg">
-
#
-
# fa_icon "quote-left 4x", class: "pull-left"
-
# # => <i class="fa fa-quote-left fa-4x pull-left"></i>
-
#
-
# fa_icon "user", data: { id: 123 }
-
# # => <i class="fa fa-user" data-id="123"></i>
-
#
-
# content_tag(:li, fa_icon("check li", text: "Bulleted list item"))
-
# # => <li><i class="fa fa-check fa-li"></i> Bulleted list item</li>
-
1
def fa_icon(names = "flag", options = {})
-
classes = ["fa"]
-
classes.concat Private.icon_names(names)
-
classes.concat Array(options.delete(:class))
-
text = options.delete(:text)
-
right_icon = options.delete(:right)
-
icon = content_tag(:i, nil, options.merge(:class => classes))
-
Private.icon_join(icon, text, right_icon)
-
end
-
-
# Creates an stack set of icon tags given a base icon name, a main icon
-
# name, and possible icon modifiers.
-
#
-
# Examples
-
#
-
# fa_stacked_icon "twitter", base: "square-o"
-
# # => <span class="fa-stack">
-
# # => <i class="fa fa-square-o fa-stack-2x"></i>
-
# # => <i class="fa fa-twitter fa-stack-1x"></i>
-
# # => </span>
-
#
-
# fa_stacked_icon "terminal inverse", base: "square", class: "pull-right", text: "Hi!"
-
# # => <span class="fa-stack pull-right">
-
# # => <i class="fa fa-square fa-stack-2x"></i>
-
# # => <i class="fa fa-terminal fa-inverse fa-stack-1x"></i>
-
# # => </span> Hi!
-
#
-
# fa_stacked_icon "camera", base: "ban-circle", reverse: true
-
# # => <span class="fa-stack">
-
# # => <i class="fa fa-camera fa-stack-1x"></i>
-
# # => <i class="fa fa-ban-circle fa-stack-2x"></i>
-
# # => </span>
-
1
def fa_stacked_icon(names = "flag", options = {})
-
classes = Private.icon_names("stack").concat(Array(options.delete(:class)))
-
base_names = Private.array_value(options.delete(:base) || "square-o").push("stack-2x")
-
names = Private.array_value(names).push("stack-1x")
-
base = fa_icon(base_names, options.delete(:base_options) || {})
-
icon = fa_icon(names, options.delete(:icon_options) || {})
-
icons = [base, icon]
-
icons.reverse! if options.delete(:reverse)
-
text = options.delete(:text)
-
right_icon = options.delete(:right)
-
stacked_icon = content_tag(:span, safe_join(icons), options.merge(:class => classes))
-
Private.icon_join(stacked_icon, text, right_icon)
-
end
-
-
1
module Private
-
1
extend ActionView::Helpers::OutputSafetyHelper
-
-
1
def self.icon_join(icon, text, reverse_order = false)
-
return icon if text.blank?
-
elements = [icon, ERB::Util.html_escape(text)]
-
elements.reverse! if reverse_order
-
safe_join(elements, " ")
-
end
-
-
1
def self.icon_names(names = [])
-
array_value(names).map { |n| "fa-#{n}" }
-
end
-
-
1
def self.array_value(value = [])
-
value.is_a?(Array) ? value : value.to_s.split(/\s+/)
-
end
-
end
-
end
-
end
-
end
-
1
require "font-awesome-rails/version"
-
1
require "font-awesome-rails/engine" if defined?(::Rails)
-
1
module FontAwesome
-
1
module Rails
-
1
class Engine < ::Rails::Engine
-
end
-
end
-
end
-
1
module FontAwesome
-
1
module Rails
-
1
FA_VERSION = "4.2.0"
-
1
VERSION = "4.2.0.0"
-
end
-
end
-
1
require "fullcalendar-rails/version"
-
-
1
module Fullcalendar
-
1
module Rails
-
1
class Engine < ::Rails::Engine
-
end
-
end
-
end
-
1
module Fullcalendar
-
1
module Rails
-
1
VERSION = "1.6.4.0"
-
end
-
end
-
1
require 'handlebars_assets/version'
-
-
1
module HandlebarsAssets
-
1
autoload(:Config, 'handlebars_assets/config')
-
1
autoload(:Handlebars, 'handlebars_assets/handlebars')
-
1
autoload(:HandlebarsTemplate, 'handlebars_assets/handlebars_template')
-
-
1
PATH = File.expand_path('../../vendor/assets/javascripts', __FILE__)
-
-
1
def self.path
-
PATH
-
end
-
-
1
def self.configure
-
yield Config
-
end
-
-
1
def self.register_extensions(sprockets_environment)
-
1
Config.handlebars_extensions.each do |ext|
-
2
sprockets_environment.register_engine(ext, HandlebarsTemplate)
-
end
-
1
if Config.haml_enabled? && Config.haml_available?
-
Config.hamlbars_extensions.each do |ext|
-
sprockets_environment.register_engine(ext, HandlebarsTemplate)
-
end
-
end
-
1
if Config.slim_enabled? && Config.slim_available?
-
Config.slimbars_extensions.each do |ext|
-
sprockets_environment.register_engine(ext, HandlebarsTemplate)
-
end
-
end
-
end
-
-
end
-
-
# Register the engine (which will register extension in the app)
-
# or ASSUME using sprockets
-
1
if defined?(Rails)
-
1
require 'handlebars_assets/engine'
-
else
-
require 'sprockets'
-
::HandlebarsAssets.register_extensions(Sprockets)
-
end
-
1
module HandlebarsAssets
-
# Change config options in an initializer:
-
#
-
# HandlebarsAssets::Config.path_prefix = 'app/templates'
-
-
1
module Config
-
1
extend self
-
-
1
attr_writer :compiler, :compiler_path, :ember, :multiple_frameworks,
-
:haml_options, :known_helpers, :known_helpers_only, :options,
-
:patch_files, :patch_path, :path_prefix, :slim_options, :template_namespace,
-
:precompile, :haml_enabled, :slim_enabled,
-
:handlebars_extensions, :hamlbars_extensions, :slimbars_extensions,
-
:amd, :handlebars_amd_path, :amd_with_template_namespace
-
-
1
def compiler
-
@compiler || 'handlebars.js'
-
end
-
-
1
def self.configure
-
yield self
-
end
-
-
1
def compiler_path
-
@compiler_path || HandlebarsAssets.path
-
end
-
-
1
def ember?
-
@ember || false
-
end
-
-
1
def multiple_frameworks?
-
@multiple_frameworks
-
end
-
-
1
def haml_available?
-
1
defined? ::Haml::Engine
-
end
-
-
1
def haml_enabled?
-
1
@haml_enabled = true if @haml_enabled.nil?
-
1
@haml_enabled
-
end
-
-
1
def haml_options
-
@haml_options || {}
-
end
-
-
1
def slim_available?
-
1
defined? ::Slim::Engine
-
end
-
-
1
def slim_enabled?
-
1
@slim_enabled = true if @slim_enabled.nil?
-
1
@slim_enabled
-
end
-
-
1
def slim_options
-
@slim_options || {}
-
end
-
-
1
def known_helpers
-
@known_helpers || []
-
end
-
-
1
def known_helpers_only
-
@known_helpers_only = false if @known_helpers_only.nil?
-
@known_helpers_only
-
end
-
-
1
def options
-
@options ||= generate_options
-
end
-
-
1
def patch_files
-
Array(@patch_files)
-
end
-
-
1
def patch_path
-
@patch_path ||= compiler_path
-
end
-
-
1
def path_prefix
-
@path_prefix ||= 'templates'
-
end
-
-
1
def precompile
-
@precompile = true if @precompile.nil?
-
@precompile
-
end
-
-
1
def template_namespace
-
@template_namespace || 'HandlebarsTemplates'
-
end
-
-
1
def handlebars_extensions
-
1
@hbs_extensions ||= ['hbs', 'handlebars']
-
end
-
-
1
def hamlbars_extensions
-
@hamlbars_extensions ||= ['hamlbars']
-
end
-
-
1
def slimbars_extensions
-
@slimbars_extensions ||= ['slimbars']
-
end
-
-
1
def ember_extensions
-
@ember_extensions ||= ['ember']
-
end
-
-
1
def amd?
-
@amd || false
-
end
-
-
# indicate whether the template should
-
# be added to the global template namespace
-
1
def amd_with_template_namespace
-
@amd_with_template_namespace || false
-
end
-
-
# path specified by the require.js paths
-
# during configuration for the handlebars
-
1
def handlebars_amd_path
-
@handlebars_amd_path || 'handlebars'
-
end
-
-
1
private
-
-
1
def generate_known_helpers_hash
-
known_helpers.inject({}) do |hash, helper|
-
hash[helper] = true
-
hash
-
end
-
end
-
-
1
def generate_options
-
options = @options || {}
-
options[:knownHelpersOnly] = true if known_helpers_only
-
options[:knownHelpers] = generate_known_helpers_hash if known_helpers.any?
-
options
-
end
-
-
end
-
end
-
1
module HandlebarsAssets
-
# NOTE: must be an engine because we are including assets in the gem
-
1
class Engine < ::Rails::Engine
-
1
initializer "handlebars_assets.assets.register", :group => :all do |app|
-
1
::HandlebarsAssets::register_extensions(app.assets)
-
end
-
end
-
end
-
1
require 'tilt'
-
1
require 'json'
-
-
1
module HandlebarsAssets
-
1
module Unindent
-
# http://bit.ly/aze9FV
-
# Strip leading whitespace from each line that is the same as the
-
# amount of whitespace on the first line of the string.
-
# Leaves _additional_ indentation on later lines intact.
-
1
def unindent(heredoc)
-
heredoc.gsub(/^#{heredoc[/\A\s*/]}/, '')
-
end
-
end
-
-
1
class HandlebarsTemplate < Tilt::Template
-
-
1
include Unindent
-
-
1
def self.default_mime_type
-
4
'application/javascript'
-
end
-
-
1
def initialize_engine
-
begin
-
require 'haml'
-
rescue LoadError
-
# haml not available
-
end
-
begin
-
require 'slim'
-
rescue LoadError
-
# slim not available
-
end
-
end
-
-
1
def prepare
-
@template_path = TemplatePath.new(@file)
-
@engine =
-
if @template_path.is_haml?
-
Haml::Engine.new(data, HandlebarsAssets::Config.haml_options)
-
elsif @template_path.is_slim?
-
Slim::Template.new(HandlebarsAssets::Config.slim_options) { data }
-
else
-
nil
-
end
-
end
-
-
1
def evaluate(scope, locals, &block)
-
source =
-
if @engine
-
@engine.render(scope, locals, &block)
-
else
-
data
-
end
-
-
# remove trailing \n on file, for some reason the directives pipeline adds this
-
source.chomp!($/)
-
-
# handle the case of multiple frameworks combined with ember
-
# DEFER: use extension setup for ember
-
if (HandlebarsAssets::Config.multiple_frameworks? && @template_path.is_ember?) ||
-
(HandlebarsAssets::Config.ember? && !HandlebarsAssets::Config.multiple_frameworks?)
-
compile_ember(source)
-
else
-
compile_default(source)
-
end
-
end
-
-
1
def compile_ember(source)
-
"window.Ember.TEMPLATES[#{@template_path.name}] = Ember.Handlebars.compile(#{JSON.dump(source)});"
-
end
-
-
1
def compile_default(source)
-
template =
-
if HandlebarsAssets::Config.precompile
-
compiled_hbs = Handlebars.precompile(source, HandlebarsAssets::Config.options)
-
"Handlebars.template(#{compiled_hbs})"
-
else
-
"Handlebars.compile(#{JSON.dump(source)})"
-
end
-
-
template_namespace = HandlebarsAssets::Config.template_namespace
-
-
if HandlebarsAssets::Config.amd?
-
handlebars_amd_path = HandlebarsAssets::Config.handlebars_amd_path
-
if HandlebarsAssets::Config.amd_with_template_namespace
-
if @template_path.is_partial?
-
unindent <<-PARTIAL
-
define(['#{handlebars_amd_path}'],function(Handlebars){
-
var t = #{template};
-
Handlebars.registerPartial(#{@template_path.name}, t);
-
return t;
-
;})
-
PARTIAL
-
else
-
unindent <<-TEMPLATE
-
define(['#{handlebars_amd_path}'],function(Handlebars){
-
return #{template};
-
});
-
TEMPLATE
-
end
-
else
-
if @template_path.is_partial?
-
unindent <<-PARTIAL
-
define(['#{handlebars_amd_path}'],function(Handlebars){
-
var t = #{template};
-
Handlebars.registerPartial(#{@template_path.name}, t);
-
return t;
-
;})
-
PARTIAL
-
else
-
unindent <<-TEMPLATE
-
define(['#{handlebars_amd_path}'],function(Handlebars){
-
this.#{template_namespace} || (this.#{template_namespace} = {});
-
this.#{template_namespace}[#{@template_path.name}] = #{template};
-
return this.#{template_namespace}[#{@template_path.name}];
-
});
-
TEMPLATE
-
end
-
end
-
else
-
if @template_path.is_partial?
-
unindent <<-PARTIAL
-
(function() {
-
Handlebars.registerPartial(#{@template_path.name}, #{template});
-
}).call(this);
-
PARTIAL
-
else
-
unindent <<-TEMPLATE
-
(function() {
-
this.#{template_namespace} || (this.#{template_namespace} = {});
-
this.#{template_namespace}[#{@template_path.name}] = #{template};
-
return this.#{template_namespace}[#{@template_path.name}];
-
}).call(this);
-
TEMPLATE
-
end
-
end
-
end
-
-
1
protected
-
-
1
class TemplatePath
-
1
def initialize(path)
-
@full_path = path
-
end
-
-
1
def is_haml?
-
result = false
-
::HandlebarsAssets::Config.hamlbars_extensions.each do |ext|
-
if ext.start_with? '.'
-
ext = '\\#{ext}'
-
result ||= !(@full_path =~ /#{ext}(\..*)*$/).nil?
-
else
-
result ||= !(@full_path =~ /\.#{ext}(\..*)*$/).nil?
-
end
-
end
-
result
-
end
-
-
1
def is_slim?
-
result = false
-
::HandlebarsAssets::Config.slimbars_extensions.each do |ext|
-
if ext.start_with? '.'
-
ext = '\\#{ext}'
-
result ||= !(@full_path =~ /#{ext}(\..*)*$/).nil?
-
else
-
result ||= !(@full_path =~ /\.#{ext}(\..*)*$/).nil?
-
end
-
end
-
result
-
end
-
-
1
def is_partial?
-
@full_path.gsub(%r{.*/}, '').start_with?('_')
-
end
-
-
1
def is_ember?
-
result = false
-
::HandlebarsAssets::Config.ember_extensions.each do |ext|
-
if ext.start_with? '.'
-
ext = '\\#{ext}'
-
result ||= !(@full_path =~ /#{ext}(\..*)*$/).nil?
-
else
-
result ||= !(@full_path =~ /\.#{ext}(\..*)*$/).nil?
-
end
-
end
-
result
-
end
-
-
1
def name
-
template_name
-
end
-
-
1
private
-
-
1
def relative_path
-
@full_path.match(/.*#{HandlebarsAssets::Config.path_prefix}\/((.*\/)*([^.]*)).*$/)[1]
-
end
-
-
1
def template_name
-
relative_path.dump
-
end
-
end
-
end
-
end
-
1
module HandlebarsAssets
-
1
VERSION = "0.18"
-
end
-
1
module Hike
-
1
VERSION = "1.2.0"
-
-
1
autoload :Extensions, "hike/extensions"
-
1
autoload :Index, "hike/index"
-
1
autoload :NormalizedArray, "hike/normalized_array"
-
1
autoload :Paths, "hike/paths"
-
1
autoload :Trail, "hike/trail"
-
end
-
1
require 'hike/normalized_array'
-
-
1
module Hike
-
# `Extensions` is an internal collection for tracking extension names.
-
1
class Extensions < NormalizedArray
-
# Extensions added to this array are normalized with a leading
-
# `.`.
-
#
-
# extensions << "js"
-
# extensions << ".css"
-
#
-
# extensions
-
# # => [".js", ".css"]
-
#
-
1
def normalize_element(extension)
-
13
if extension[/^\./]
-
11
extension
-
else
-
2
".#{extension}"
-
end
-
end
-
end
-
end
-
1
require 'pathname'
-
-
1
module Hike
-
# `Index` is an internal cached variant of `Trail`. It assumes the
-
# file system does not change between `find` calls. All `stat` and
-
# `entries` calls are cached for the lifetime of the `Index` object.
-
1
class Index
-
# `Index#paths` is an immutable `Paths` collection.
-
1
attr_reader :paths
-
-
# `Index#extensions` is an immutable `Extensions` collection.
-
1
attr_reader :extensions
-
-
# `Index#aliases` is an immutable `Hash` mapping an extension to
-
# an `Array` of aliases.
-
1
attr_reader :aliases
-
-
# `Index.new` is an internal method. Instead of constructing it
-
# directly, create a `Trail` and call `Trail#index`.
-
1
def initialize(root, paths, extensions, aliases)
-
1
@root = root
-
-
# Freeze is used here so an error is throw if a mutator method
-
# is called on the array. Mutating `@paths`, `@extensions`, or
-
# `@aliases` would have unpredictable results.
-
1
@paths = paths.dup.freeze
-
1
@extensions = extensions.dup.freeze
-
1
@aliases = aliases.inject({}) { |h, (k, a)|
-
7
h[k] = a.dup.freeze; h
-
}.freeze
-
29
@pathnames = paths.map { |path| Pathname.new(path) }
-
-
1
@stats = {}
-
1
@entries = {}
-
1
@patterns = {}
-
end
-
-
# `Index#root` returns root path as a `String`. This attribute is immutable.
-
1
def root
-
@root.to_s
-
end
-
-
# `Index#index` returns `self` to be compatable with the `Trail` interface.
-
1
def index
-
self
-
end
-
-
# The real implementation of `find`. `Trail#find` generates a one
-
# time index and delegates here.
-
#
-
# See `Trail#find` for usage.
-
1
def find(*logical_paths, &block)
-
if block_given?
-
options = extract_options!(logical_paths)
-
base_path = Pathname.new(options[:base_path] || @root)
-
-
logical_paths.each do |logical_path|
-
logical_path = Pathname.new(logical_path.sub(/^\//, ''))
-
-
if relative?(logical_path)
-
find_in_base_path(logical_path, base_path, &block)
-
else
-
find_in_paths(logical_path, &block)
-
end
-
end
-
-
nil
-
else
-
find(*logical_paths) do |path|
-
return path
-
end
-
end
-
end
-
-
# A cached version of `Dir.entries` that filters out `.` files and
-
# `~` swap files. Returns an empty `Array` if the directory does
-
# not exist.
-
1
def entries(path)
-
@entries[path.to_s] ||= begin
-
pathname = Pathname.new(path)
-
if pathname.directory?
-
pathname.entries.reject { |entry| entry.to_s =~ /^\.|~$|^\#.*\#$/ }.sort
-
else
-
[]
-
end
-
end
-
end
-
-
# A cached version of `File.stat`. Returns nil if the file does
-
# not exist.
-
1
def stat(path)
-
key = path.to_s
-
if @stats.key?(key)
-
@stats[key]
-
elsif File.exist?(path)
-
@stats[key] = File.stat(path)
-
else
-
@stats[key] = nil
-
end
-
end
-
-
1
protected
-
1
def extract_options!(arguments)
-
arguments.last.is_a?(Hash) ? arguments.pop.dup : {}
-
end
-
-
1
def relative?(logical_path)
-
logical_path.to_s =~ /^\.\.?\//
-
end
-
-
# Finds logical path across all `paths`
-
1
def find_in_paths(logical_path, &block)
-
dirname, basename = logical_path.split
-
@pathnames.each do |base_path|
-
match(base_path.join(dirname), basename, &block)
-
end
-
end
-
-
# Finds relative logical path, `../test/test_trail`. Requires a
-
# `base_path` for reference.
-
1
def find_in_base_path(logical_path, base_path, &block)
-
candidate = base_path.join(logical_path)
-
dirname, basename = candidate.split
-
match(dirname, basename, &block) if paths_contain?(dirname)
-
end
-
-
# Checks if the path is actually on the file system and performs
-
# any syscalls if necessary.
-
1
def match(dirname, basename)
-
# Potential `entries` syscall
-
matches = entries(dirname)
-
-
pattern = pattern_for(basename)
-
matches = matches.select { |m| m.to_s =~ pattern }
-
-
sort_matches(matches, basename).each do |path|
-
pathname = dirname.join(path)
-
-
# Potential `stat` syscall
-
stat = stat(pathname)
-
-
# Exclude directories
-
if stat && stat.file?
-
yield pathname.to_s
-
end
-
end
-
end
-
-
# Returns true if `dirname` is a subdirectory of any of the `paths`
-
1
def paths_contain?(dirname)
-
paths.any? { |path| dirname.to_s[0, path.length] == path }
-
end
-
-
# Cache results of `build_pattern_for`
-
1
def pattern_for(basename)
-
@patterns[basename] ||= build_pattern_for(basename)
-
end
-
-
# Returns a `Regexp` that matches the allowed extensions.
-
#
-
# pattern_for("index.html") #=> /^index(.html|.htm)(.builder|.erb)*$/
-
1
def build_pattern_for(basename)
-
extname = basename.extname
-
aliases = find_aliases_for(extname)
-
-
if aliases.any?
-
basename = basename.basename(extname)
-
aliases = [extname] + aliases
-
aliases_pattern = aliases.map { |e| Regexp.escape(e) }.join("|")
-
basename_re = Regexp.escape(basename.to_s) + "(?:#{aliases_pattern})"
-
else
-
basename_re = Regexp.escape(basename.to_s)
-
end
-
-
extension_pattern = extensions.map { |e| Regexp.escape(e) }.join("|")
-
/^#{basename_re}(?:#{extension_pattern})*$/
-
end
-
-
# Sorts candidate matches by their extension
-
# priority. Extensions in the front of the `extensions` carry
-
# more weight.
-
1
def sort_matches(matches, basename)
-
aliases = find_aliases_for(basename.extname)
-
-
matches.sort_by do |match|
-
extnames = match.sub(basename.to_s, '').to_s.scan(/\.[^.]+/)
-
extnames.inject(0) do |sum, ext|
-
if i = extensions.index(ext)
-
sum + i + 1
-
elsif i = aliases.index(ext)
-
sum + i + 11
-
else
-
sum
-
end
-
end
-
end
-
end
-
-
1
def find_aliases_for(extension)
-
@aliases.inject([]) do |aliases, (key, value)|
-
aliases.push(key) if value == extension
-
aliases
-
end
-
end
-
end
-
end
-
1
module Hike
-
# `NormalizedArray` is an internal abstract wrapper class that calls
-
# a callback `normalize_element` anytime an element is added to the
-
# Array.
-
#
-
# `Extensions` and `Paths` are subclasses of `NormalizedArray`.
-
1
class NormalizedArray < Array
-
1
def initialize
-
4
super()
-
end
-
-
1
def []=(*args)
-
value = args.pop
-
-
if value.respond_to?(:to_ary)
-
value = normalize_elements(value)
-
else
-
value = normalize_element(value)
-
end
-
-
super(*args.concat([value]))
-
end
-
-
1
def <<(element)
-
super normalize_element(element)
-
end
-
-
1
def collect!
-
super do |element|
-
result = yield element
-
normalize_element(result)
-
end
-
end
-
-
1
alias_method :map!, :collect!
-
-
1
def insert(index, *elements)
-
super index, *normalize_elements(elements)
-
end
-
-
1
def push(*elements)
-
41
super(*normalize_elements(elements))
-
end
-
-
1
def replace(elements)
-
super normalize_elements(elements)
-
end
-
-
1
def unshift(*elements)
-
super(*normalize_elements(elements))
-
end
-
-
1
def normalize_elements(elements)
-
41
elements.map do |element|
-
41
normalize_element(element)
-
end
-
end
-
end
-
end
-
1
require 'pathname'
-
1
require 'hike/normalized_array'
-
-
1
module Hike
-
# `Paths` is an internal collection for tracking path strings.
-
1
class Paths < NormalizedArray
-
1
def initialize(root = ".")
-
2
@root = Pathname.new(root)
-
2
super()
-
end
-
-
# Relative paths added to this array are expanded relative to `@root`.
-
#
-
# paths = Paths.new("/usr/local")
-
# paths << "tmp"
-
# paths << "/tmp"
-
#
-
# paths
-
# # => ["/usr/local/tmp", "/tmp"]
-
#
-
1
def normalize_element(path)
-
28
path = Pathname.new(path)
-
28
path = @root.join(path) if path.relative?
-
28
path.expand_path.to_s
-
end
-
end
-
end
-
1
require 'pathname'
-
1
require 'hike/extensions'
-
1
require 'hike/index'
-
1
require 'hike/paths'
-
-
1
module Hike
-
# `Trail` is the public container class for holding paths and extensions.
-
1
class Trail
-
# `Trail#paths` is a mutable `Paths` collection.
-
#
-
# trail = Hike::Trail.new
-
# trail.paths.push "~/Projects/hike/lib", "~/Projects/hike/test"
-
#
-
# The order of the paths is significant. Paths in the beginning of
-
# the collection will be checked first. In the example above,
-
# `~/Projects/hike/lib/hike.rb` would shadow the existent of
-
# `~/Projects/hike/test/hike.rb`.
-
1
attr_reader :paths
-
-
# `Trail#extensions` is a mutable `Extensions` collection.
-
#
-
# trail = Hike::Trail.new
-
# trail.paths.push "~/Projects/hike/lib"
-
# trail.extensions.push ".rb"
-
#
-
# Extensions allow you to find files by just their name omitting
-
# their extension. Is similar to Ruby's require mechanism that
-
# allows you to require files with specifiying `foo.rb`.
-
1
attr_reader :extensions
-
-
# `Index#aliases` is a mutable `Hash` mapping an extension to
-
# an `Array` of aliases.
-
#
-
# trail = Hike::Trail.new
-
# trail.paths.push "~/Projects/hike/site"
-
# trail.aliases['.htm'] = 'html'
-
# trail.aliases['.xhtml'] = 'html'
-
# trail.aliases['.php'] = 'html'
-
#
-
# Aliases provide a fallback when the primary extension is not
-
# matched. In the example above, a lookup for "foo.html" will
-
# check for the existence of "foo.htm", "foo.xhtml", or "foo.php".
-
1
attr_reader :aliases
-
-
# A Trail accepts an optional root path that defaults to your
-
# current working directory. Any relative paths added to
-
# `Trail#paths` will expanded relative to the root.
-
1
def initialize(root = ".")
-
2
@root = Pathname.new(root).expand_path
-
2
@paths = Paths.new(@root)
-
2
@extensions = Extensions.new
-
2
@aliases = Hash.new { |h, k| h[k] = Extensions.new }
-
end
-
-
# `Trail#root` returns root path as a `String`. This attribute is immutable.
-
1
def root
-
1
@root.to_s
-
end
-
-
# Prepend `path` to `Paths` collection
-
1
def prepend_paths(*paths)
-
self.paths.unshift(*paths)
-
end
-
1
alias_method :prepend_path, :prepend_paths
-
-
# Append `path` to `Paths` collection
-
1
def append_paths(*paths)
-
28
self.paths.push(*paths)
-
end
-
1
alias_method :append_path, :append_paths
-
-
# Remove `path` from `Paths` collection
-
1
def remove_path(path)
-
self.paths.delete(path)
-
end
-
-
# Prepend `extension` to `Extensions` collection
-
1
def prepend_extensions(*extensions)
-
self.extensions.unshift(*extensions)
-
end
-
1
alias_method :prepend_extension, :prepend_extensions
-
-
# Append `extension` to `Extensions` collection
-
1
def append_extensions(*extensions)
-
13
self.extensions.push(*extensions)
-
end
-
1
alias_method :append_extension, :append_extensions
-
-
# Remove `extension` from `Extensions` collection
-
1
def remove_extension(extension)
-
self.extensions.delete(extension)
-
end
-
-
# Alias `new_extension` to `old_extension`
-
1
def alias_extension(new_extension, old_extension)
-
7
aliases[normalize_extension(new_extension)] = normalize_extension(old_extension)
-
end
-
-
# Remove the alias for `extension`
-
1
def unalias_extension(extension)
-
aliases.delete(normalize_extension(extension))
-
end
-
-
# `Trail#find` returns a the expand path for a logical path in the
-
# path collection.
-
#
-
# trail = Hike::Trail.new "~/Projects/hike"
-
# trail.extensions.push ".rb"
-
# trail.paths.push "lib", "test"
-
#
-
# trail.find "hike/trail"
-
# # => "~/Projects/hike/lib/hike/trail.rb"
-
#
-
# trail.find "test_trail"
-
# # => "~/Projects/hike/test/test_trail.rb"
-
#
-
# `find` accepts multiple fallback logical paths that returns the
-
# first match.
-
#
-
# trail.find "hike", "hike/index"
-
#
-
# is equivalent to
-
#
-
# trail.find("hike") || trail.find("hike/index")
-
#
-
# Though `find` always returns the first match, it is possible
-
# to iterate over all shadowed matches and fallbacks by supplying
-
# a block.
-
#
-
# trail.find("hike", "hike/index") { |path| warn path }
-
#
-
# This allows you to filter your matches by any condition.
-
#
-
# trail.find("application") do |path|
-
# return path if mime_type_for(path) == "text/css"
-
# end
-
#
-
1
def find(*args, &block)
-
index.find(*args, &block)
-
end
-
-
# `Trail#index` returns an `Index` object that has the same
-
# interface as `Trail`. An `Index` is a cached `Trail` object that
-
# does not update when the file system changes. If you are
-
# confident that you are not making changes the paths you are
-
# searching, `index` will avoid excess system calls.
-
#
-
# index = trail.index
-
# index.find "hike/trail"
-
# index.find "test_trail"
-
#
-
1
def index
-
1
Index.new(root, paths, extensions, aliases)
-
end
-
-
# `Trail#entries` is equivalent to `Dir#entries`. It is not
-
# recommend to use this method for general purposes. It exists for
-
# parity with `Index#entries`.
-
1
def entries(path)
-
pathname = Pathname.new(path)
-
if pathname.directory?
-
pathname.entries.reject { |entry| entry.to_s =~ /^\.|~$|^\#.*\#$/ }.sort
-
else
-
[]
-
end
-
end
-
-
# `Trail#stat` is equivalent to `File#stat`. It is not
-
# recommend to use this method for general purposes. It exists for
-
# parity with `Index#stat`.
-
1
def stat(path)
-
if File.exist?(path)
-
File.stat(path.to_s)
-
else
-
nil
-
end
-
end
-
-
1
private
-
1
def normalize_extension(extension)
-
14
if extension[/^\./]
-
12
extension
-
else
-
2
".#{extension}"
-
end
-
end
-
end
-
end
-
1
require 'i18n/version'
-
1
require 'i18n/exceptions'
-
1
require 'i18n/interpolate/ruby'
-
-
1
module I18n
-
1
autoload :Backend, 'i18n/backend'
-
1
autoload :Config, 'i18n/config'
-
1
autoload :Gettext, 'i18n/gettext'
-
1
autoload :Locale, 'i18n/locale'
-
1
autoload :Tests, 'i18n/tests'
-
-
1
RESERVED_KEYS = [:scope, :default, :separator, :resolve, :object, :fallback, :format, :cascade, :throw, :raise, :rescue_format]
-
1
RESERVED_KEYS_PATTERN = /%\{(#{RESERVED_KEYS.join("|")})\}/
-
-
1
extend(Module.new {
-
# Gets I18n configuration object.
-
1
def config
-
16
Thread.current[:i18n_config] ||= I18n::Config.new
-
end
-
-
# Sets I18n configuration object.
-
1
def config=(value)
-
Thread.current[:i18n_config] = value
-
end
-
-
# Write methods which delegates to the configuration object
-
%w(locale backend default_locale available_locales default_separator
-
1
exception_handler load_path enforce_available_locales).each do |method|
-
8
module_eval <<-DELEGATORS, __FILE__, __LINE__ + 1
-
def #{method}
-
config.#{method}
-
end
-
-
def #{method}=(value)
-
config.#{method} = (value)
-
end
-
DELEGATORS
-
end
-
-
# Tells the backend to reload translations. Used in situations like the
-
# Rails development environment. Backends can implement whatever strategy
-
# is useful.
-
1
def reload!
-
1
config.backend.reload!
-
end
-
-
# Translates, pluralizes and interpolates a given key using a given locale,
-
# scope, and default, as well as interpolation values.
-
#
-
# *LOOKUP*
-
#
-
# Translation data is organized as a nested hash using the upper-level keys
-
# as namespaces. <em>E.g.</em>, ActionView ships with the translation:
-
# <tt>:date => {:formats => {:short => "%b %d"}}</tt>.
-
#
-
# Translations can be looked up at any level of this hash using the key argument
-
# and the scope option. <em>E.g.</em>, in this example <tt>I18n.t :date</tt>
-
# returns the whole translations hash <tt>{:formats => {:short => "%b %d"}}</tt>.
-
#
-
# Key can be either a single key or a dot-separated key (both Strings and Symbols
-
# work). <em>E.g.</em>, the short format can be looked up using both:
-
# I18n.t 'date.formats.short'
-
# I18n.t :'date.formats.short'
-
#
-
# Scope can be either a single key, a dot-separated key or an array of keys
-
# or dot-separated keys. Keys and scopes can be combined freely. So these
-
# examples will all look up the same short date format:
-
# I18n.t 'date.formats.short'
-
# I18n.t 'formats.short', :scope => 'date'
-
# I18n.t 'short', :scope => 'date.formats'
-
# I18n.t 'short', :scope => %w(date formats)
-
#
-
# *INTERPOLATION*
-
#
-
# Translations can contain interpolation variables which will be replaced by
-
# values passed to #translate as part of the options hash, with the keys matching
-
# the interpolation variable names.
-
#
-
# <em>E.g.</em>, with a translation <tt>:foo => "foo %{bar}"</tt> the option
-
# value for the key +bar+ will be interpolated into the translation:
-
# I18n.t :foo, :bar => 'baz' # => 'foo baz'
-
#
-
# *PLURALIZATION*
-
#
-
# Translation data can contain pluralized translations. Pluralized translations
-
# are arrays of singluar/plural versions of translations like <tt>['Foo', 'Foos']</tt>.
-
#
-
# Note that <tt>I18n::Backend::Simple</tt> only supports an algorithm for English
-
# pluralization rules. Other algorithms can be supported by custom backends.
-
#
-
# This returns the singular version of a pluralized translation:
-
# I18n.t :foo, :count => 1 # => 'Foo'
-
#
-
# These both return the plural version of a pluralized translation:
-
# I18n.t :foo, :count => 0 # => 'Foos'
-
# I18n.t :foo, :count => 2 # => 'Foos'
-
#
-
# The <tt>:count</tt> option can be used both for pluralization and interpolation.
-
# <em>E.g.</em>, with the translation
-
# <tt>:foo => ['%{count} foo', '%{count} foos']</tt>, count will
-
# be interpolated to the pluralized translation:
-
# I18n.t :foo, :count => 1 # => '1 foo'
-
#
-
# *DEFAULTS*
-
#
-
# This returns the translation for <tt>:foo</tt> or <tt>default</tt> if no translation was found:
-
# I18n.t :foo, :default => 'default'
-
#
-
# This returns the translation for <tt>:foo</tt> or the translation for <tt>:bar</tt> if no
-
# translation for <tt>:foo</tt> was found:
-
# I18n.t :foo, :default => :bar
-
#
-
# Returns the translation for <tt>:foo</tt> or the translation for <tt>:bar</tt>
-
# or <tt>default</tt> if no translations for <tt>:foo</tt> and <tt>:bar</tt> were found.
-
# I18n.t :foo, :default => [:bar, 'default']
-
#
-
# *BULK LOOKUP*
-
#
-
# This returns an array with the translations for <tt>:foo</tt> and <tt>:bar</tt>.
-
# I18n.t [:foo, :bar]
-
#
-
# Can be used with dot-separated nested keys:
-
# I18n.t [:'baz.foo', :'baz.bar']
-
#
-
# Which is the same as using a scope option:
-
# I18n.t [:foo, :bar], :scope => :baz
-
#
-
# *LAMBDAS*
-
#
-
# Both translations and defaults can be given as Ruby lambdas. Lambdas will be
-
# called and passed the key and options.
-
#
-
# E.g. assuming the key <tt>:salutation</tt> resolves to:
-
# lambda { |key, options| options[:gender] == 'm' ? "Mr. %{options[:name]}" : "Mrs. %{options[:name]}" }
-
#
-
# Then <tt>I18n.t(:salutation, :gender => 'w', :name => 'Smith') will result in "Mrs. Smith".
-
#
-
# It is recommended to use/implement lambdas in an "idempotent" way. E.g. when
-
# a cache layer is put in front of I18n.translate it will generate a cache key
-
# from the argument values passed to #translate. Therefor your lambdas should
-
# always return the same translations/values per unique combination of argument
-
# values.
-
1
def translate(*args)
-
options = args.last.is_a?(Hash) ? args.pop.dup : {}
-
key = args.shift
-
backend = config.backend
-
locale = options.delete(:locale) || config.locale
-
handling = options.delete(:throw) && :throw || options.delete(:raise) && :raise # TODO deprecate :raise
-
-
enforce_available_locales!(locale)
-
raise I18n::ArgumentError if key.is_a?(String) && key.empty?
-
-
result = catch(:exception) do
-
if key.is_a?(Array)
-
key.map { |k| backend.translate(locale, k, options) }
-
else
-
backend.translate(locale, key, options)
-
end
-
end
-
result.is_a?(MissingTranslation) ? handle_exception(handling, result, locale, key, options) : result
-
end
-
1
alias :t :translate
-
-
# Wrapper for <tt>translate</tt> that adds <tt>:raise => true</tt>. With
-
# this option, if no translation is found, it will raise <tt>I18n::MissingTranslationData</tt>
-
1
def translate!(key, options={})
-
translate(key, options.merge(:raise => true))
-
end
-
1
alias :t! :translate!
-
-
# Returns true if a translation exists for a given key, otherwise returns false.
-
1
def exists?(key, locale = config.locale)
-
raise I18n::ArgumentError if key.is_a?(String) && key.empty?
-
config.backend.exists?(locale, key)
-
end
-
-
# Transliterates UTF-8 characters to ASCII. By default this method will
-
# transliterate only Latin strings to an ASCII approximation:
-
#
-
# I18n.transliterate("Ærøskøbing")
-
# # => "AEroskobing"
-
#
-
# I18n.transliterate("日本語")
-
# # => "???"
-
#
-
# It's also possible to add support for per-locale transliterations. I18n
-
# expects transliteration rules to be stored at
-
# <tt>i18n.transliterate.rule</tt>.
-
#
-
# Transliteration rules can either be a Hash or a Proc. Procs must accept a
-
# single string argument. Hash rules inherit the default transliteration
-
# rules, while Procs do not.
-
#
-
# *Examples*
-
#
-
# Setting a Hash in <locale>.yml:
-
#
-
# i18n:
-
# transliterate:
-
# rule:
-
# ü: "ue"
-
# ö: "oe"
-
#
-
# Setting a Hash using Ruby:
-
#
-
# store_translations(:de, :i18n => {
-
# :transliterate => {
-
# :rule => {
-
# "ü" => "ue",
-
# "ö" => "oe"
-
# }
-
# }
-
# )
-
#
-
# Setting a Proc:
-
#
-
# translit = lambda {|string| MyTransliterator.transliterate(string) }
-
# store_translations(:xx, :i18n => {:transliterate => {:rule => translit})
-
#
-
# Transliterating strings:
-
#
-
# I18n.locale = :en
-
# I18n.transliterate("Jürgen") # => "Jurgen"
-
# I18n.locale = :de
-
# I18n.transliterate("Jürgen") # => "Juergen"
-
# I18n.transliterate("Jürgen", :locale => :en) # => "Jurgen"
-
# I18n.transliterate("Jürgen", :locale => :de) # => "Juergen"
-
1
def transliterate(*args)
-
options = args.pop.dup if args.last.is_a?(Hash)
-
key = args.shift
-
locale = options && options.delete(:locale) || config.locale
-
handling = options && (options.delete(:throw) && :throw || options.delete(:raise) && :raise)
-
replacement = options && options.delete(:replacement)
-
enforce_available_locales!(locale)
-
config.backend.transliterate(locale, key, replacement)
-
rescue I18n::ArgumentError => exception
-
handle_exception(handling, exception, locale, key, options || {})
-
end
-
-
# Localizes certain objects, such as dates and numbers to local formatting.
-
1
def localize(object, options = nil)
-
options = options ? options.dup : {}
-
locale = options.delete(:locale) || config.locale
-
format = options.delete(:format) || :default
-
enforce_available_locales!(locale)
-
config.backend.localize(locale, object, format, options)
-
end
-
1
alias :l :localize
-
-
# Executes block with given I18n.locale set.
-
1
def with_locale(tmp_locale = nil)
-
if tmp_locale
-
current_locale = self.locale
-
self.locale = tmp_locale
-
end
-
yield
-
ensure
-
self.locale = current_locale if tmp_locale
-
end
-
-
# Merges the given locale, key and scope into a single array of keys.
-
# Splits keys that contain dots into multiple keys. Makes sure all
-
# keys are Symbols.
-
1
def normalize_keys(locale, key, scope, separator = nil)
-
separator ||= I18n.default_separator
-
-
keys = []
-
keys.concat normalize_key(locale, separator)
-
keys.concat normalize_key(scope, separator)
-
keys.concat normalize_key(key, separator)
-
keys
-
end
-
-
# Returns true when the passed locale, which can be either a String or a
-
# Symbol, is in the list of available locales. Returns false otherwise.
-
1
def locale_available?(locale)
-
I18n.config.available_locales_set.include?(locale)
-
end
-
-
# Raises an InvalidLocale exception when the passed locale is not available.
-
1
def enforce_available_locales!(locale)
-
handle_enforce_available_locales_deprecation
-
-
if config.enforce_available_locales
-
raise I18n::InvalidLocale.new(locale) if !locale_available?(locale)
-
end
-
end
-
-
# making these private until Ruby 1.9.2 can send to protected methods again
-
# see http://redmine.ruby-lang.org/repositories/revision/ruby-19?rev=24280
-
1
private
-
-
# Any exceptions thrown in translate will be sent to the @@exception_handler
-
# which can be a Symbol, a Proc or any other Object unless they're forced to
-
# be raised or thrown (MissingTranslation).
-
#
-
# If exception_handler is a Symbol then it will simply be sent to I18n as
-
# a method call. A Proc will simply be called. In any other case the
-
# method #call will be called on the exception_handler object.
-
#
-
# Examples:
-
#
-
# I18n.exception_handler = :default_exception_handler # this is the default
-
# I18n.default_exception_handler(exception, locale, key, options) # will be called like this
-
#
-
# I18n.exception_handler = lambda { |*args| ... } # a lambda
-
# I18n.exception_handler.call(exception, locale, key, options) # will be called like this
-
#
-
# I18n.exception_handler = I18nExceptionHandler.new # an object
-
# I18n.exception_handler.call(exception, locale, key, options) # will be called like this
-
1
def handle_exception(handling, exception, locale, key, options)
-
case handling
-
when :raise
-
raise(exception.respond_to?(:to_exception) ? exception.to_exception : exception)
-
when :throw
-
throw :exception, exception
-
else
-
case handler = options[:exception_handler] || config.exception_handler
-
when Symbol
-
send(handler, exception, locale, key, options)
-
else
-
handler.call(exception, locale, key, options)
-
end
-
end
-
end
-
-
1
def normalize_key(key, separator)
-
normalized_key_cache[separator][key] ||=
-
case key
-
when Array
-
key.map { |k| normalize_key(k, separator) }.flatten
-
else
-
keys = key.to_s.split(separator)
-
keys.delete('')
-
keys.map! { |k| k.to_sym }
-
keys
-
end
-
end
-
-
1
def normalized_key_cache
-
@normalized_key_cache ||= Hash.new { |h,k| h[k] = {} }
-
end
-
-
# DEPRECATED. Use I18n.normalize_keys instead.
-
1
def normalize_translation_keys(locale, key, scope, separator = nil)
-
puts "I18n.normalize_translation_keys is deprecated. Please use the class I18n.normalize_keys instead."
-
normalize_keys(locale, key, scope, separator)
-
end
-
-
# DEPRECATED. Please use the I18n::ExceptionHandler class instead.
-
1
def default_exception_handler(exception, locale, key, options)
-
puts "I18n.default_exception_handler is deprecated. Please use the class I18n::ExceptionHandler instead " +
-
"(an instance of which is set to I18n.exception_handler by default)."
-
exception.is_a?(MissingTranslation) ? exception.message : raise(exception)
-
end
-
-
1
def handle_enforce_available_locales_deprecation
-
if config.enforce_available_locales.nil? && !defined?(@unenforced_available_locales_deprecation)
-
$stderr.puts "[deprecated] I18n.enforce_available_locales will default to true in the future. If you really want to skip validation of your locale you can set I18n.enforce_available_locales = false to avoid this message."
-
@unenforced_available_locales_deprecation = true
-
end
-
end
-
})
-
end
-
1
module I18n
-
1
module Backend
-
1
autoload :Base, 'i18n/backend/base'
-
1
autoload :InterpolationCompiler, 'i18n/backend/interpolation_compiler'
-
1
autoload :Cache, 'i18n/backend/cache'
-
1
autoload :Cascade, 'i18n/backend/cascade'
-
1
autoload :Chain, 'i18n/backend/chain'
-
1
autoload :Fallbacks, 'i18n/backend/fallbacks'
-
1
autoload :Flatten, 'i18n/backend/flatten'
-
1
autoload :Gettext, 'i18n/backend/gettext'
-
1
autoload :KeyValue, 'i18n/backend/key_value'
-
1
autoload :Memoize, 'i18n/backend/memoize'
-
1
autoload :Metadata, 'i18n/backend/metadata'
-
1
autoload :Pluralization, 'i18n/backend/pluralization'
-
1
autoload :Simple, 'i18n/backend/simple'
-
1
autoload :Transliterator, 'i18n/backend/transliterator'
-
end
-
end
-
1
require 'yaml'
-
1
require 'i18n/core_ext/hash'
-
1
require 'i18n/core_ext/kernel/suppress_warnings'
-
-
1
module I18n
-
1
module Backend
-
1
module Base
-
1
include I18n::Backend::Transliterator
-
-
# Accepts a list of paths to translation files. Loads translations from
-
# plain Ruby (*.rb) or YAML files (*.yml). See #load_rb and #load_yml
-
# for details.
-
1
def load_translations(*filenames)
-
filenames = I18n.load_path if filenames.empty?
-
filenames.flatten.each { |filename| load_file(filename) }
-
end
-
-
# This method receives a locale, a data hash and options for storing translations.
-
# Should be implemented
-
1
def store_translations(locale, data, options = {})
-
raise NotImplementedError
-
end
-
-
1
def translate(locale, key, options = {})
-
raise InvalidLocale.new(locale) unless locale
-
entry = key && lookup(locale, key, options[:scope], options)
-
-
if options.empty?
-
entry = resolve(locale, key, entry, options)
-
else
-
count, default = options.values_at(:count, :default)
-
values = options.except(*RESERVED_KEYS)
-
entry = entry.nil? && default ?
-
default(locale, key, default, options) : resolve(locale, key, entry, options)
-
end
-
-
throw(:exception, I18n::MissingTranslation.new(locale, key, options)) if entry.nil?
-
entry = entry.dup if entry.is_a?(String)
-
-
entry = pluralize(locale, entry, count) if count
-
entry = interpolate(locale, entry, values) if values
-
entry
-
end
-
-
1
def exists?(locale, key)
-
lookup(locale, key) != nil
-
end
-
-
# Acts the same as +strftime+, but uses a localized version of the
-
# format string. Takes a key from the date/time formats translations as
-
# a format argument (<em>e.g.</em>, <tt>:short</tt> in <tt>:'date.formats'</tt>).
-
1
def localize(locale, object, format = :default, options = {})
-
raise ArgumentError, "Object must be a Date, DateTime or Time object. #{object.inspect} given." unless object.respond_to?(:strftime)
-
-
if Symbol === format
-
key = format
-
type = object.respond_to?(:sec) ? 'time' : 'date'
-
options = options.merge(:raise => true, :object => object, :locale => locale)
-
format = I18n.t(:"#{type}.formats.#{key}", options)
-
end
-
-
# format = resolve(locale, object, format, options)
-
format = format.to_s.gsub(/%[aAbBpP]/) do |match|
-
case match
-
when '%a' then I18n.t(:"date.abbr_day_names", :locale => locale, :format => format)[object.wday]
-
when '%A' then I18n.t(:"date.day_names", :locale => locale, :format => format)[object.wday]
-
when '%b' then I18n.t(:"date.abbr_month_names", :locale => locale, :format => format)[object.mon]
-
when '%B' then I18n.t(:"date.month_names", :locale => locale, :format => format)[object.mon]
-
when '%p' then I18n.t(:"time.#{object.hour < 12 ? :am : :pm}", :locale => locale, :format => format).upcase if object.respond_to? :hour
-
when '%P' then I18n.t(:"time.#{object.hour < 12 ? :am : :pm}", :locale => locale, :format => format).downcase if object.respond_to? :hour
-
end
-
end
-
-
object.strftime(format)
-
end
-
-
# Returns an array of locales for which translations are available
-
# ignoring the reserved translation meta data key :i18n.
-
1
def available_locales
-
raise NotImplementedError
-
end
-
-
1
def reload!
-
1
@skip_syntax_deprecation = false
-
end
-
-
1
protected
-
-
# The method which actually looks up for the translation in the store.
-
1
def lookup(locale, key, scope = [], options = {})
-
raise NotImplementedError
-
end
-
-
# Evaluates defaults.
-
# If given subject is an Array, it walks the array and returns the
-
# first translation that can be resolved. Otherwise it tries to resolve
-
# the translation directly.
-
1
def default(locale, object, subject, options = {})
-
options = options.dup.reject { |key, value| key == :default }
-
case subject
-
when Array
-
subject.each do |item|
-
result = resolve(locale, object, item, options) and return result
-
end and nil
-
else
-
resolve(locale, object, subject, options)
-
end
-
end
-
-
# Resolves a translation.
-
# If the given subject is a Symbol, it will be translated with the
-
# given options. If it is a Proc then it will be evaluated. All other
-
# subjects will be returned directly.
-
1
def resolve(locale, object, subject, options = {})
-
return subject if options[:resolve] == false
-
result = catch(:exception) do
-
case subject
-
when Symbol
-
I18n.translate(subject, options.merge(:locale => locale, :throw => true))
-
when Proc
-
date_or_time = options.delete(:object) || object
-
resolve(locale, object, subject.call(date_or_time, options))
-
else
-
subject
-
end
-
end
-
result unless result.is_a?(MissingTranslation)
-
end
-
-
# Picks a translation from a pluralized mnemonic subkey according to English
-
# pluralization rules :
-
# - It will pick the :one subkey if count is equal to 1.
-
# - It will pick the :other subkey otherwise.
-
# - It will pick the :zero subkey in the special case where count is
-
# equal to 0 and there is a :zero subkey present. This behaviour is
-
# not stand with regards to the CLDR pluralization rules.
-
# Other backends can implement more flexible or complex pluralization rules.
-
1
def pluralize(locale, entry, count)
-
return entry unless entry.is_a?(Hash) && count
-
-
key = :zero if count == 0 && entry.has_key?(:zero)
-
key ||= count == 1 ? :one : :other
-
raise InvalidPluralizationData.new(entry, count) unless entry.has_key?(key)
-
entry[key]
-
end
-
-
# Interpolates values into a given string.
-
#
-
# interpolate "file %{file} opened by %%{user}", :file => 'test.txt', :user => 'Mr. X'
-
# # => "file test.txt opened by %{user}"
-
1
def interpolate(locale, string, values = {})
-
if string.is_a?(::String) && !values.empty?
-
I18n.interpolate(string, values)
-
else
-
string
-
end
-
end
-
-
# Loads a single translations file by delegating to #load_rb or
-
# #load_yml depending on the file extension and directly merges the
-
# data to the existing translations. Raises I18n::UnknownFileType
-
# for all other file extensions.
-
1
def load_file(filename)
-
type = File.extname(filename).tr('.', '').downcase
-
raise UnknownFileType.new(type, filename) unless respond_to?(:"load_#{type}", true)
-
data = send(:"load_#{type}", filename)
-
unless data.is_a?(Hash)
-
raise InvalidLocaleData.new(filename, 'expects it to return a hash, but does not')
-
end
-
data.each { |locale, d| store_translations(locale, d || {}) }
-
end
-
-
# Loads a plain Ruby translations file. eval'ing the file must yield
-
# a Hash containing translation data with locales as toplevel keys.
-
1
def load_rb(filename)
-
eval(IO.read(filename), binding, filename)
-
end
-
-
# Loads a YAML translations file. The data must have locales as
-
# toplevel keys.
-
1
def load_yml(filename)
-
begin
-
YAML.load_file(filename)
-
rescue TypeError, ScriptError, StandardError => e
-
raise InvalidLocaleData.new(filename, e.inspect)
-
end
-
end
-
end
-
end
-
end
-
1
module I18n
-
1
module Backend
-
# A simple backend that reads translations from YAML files and stores them in
-
# an in-memory hash. Relies on the Base backend.
-
#
-
# The implementation is provided by a Implementation module allowing to easily
-
# extend Simple backend's behavior by including modules. E.g.:
-
#
-
# module I18n::Backend::Pluralization
-
# def pluralize(*args)
-
# # extended pluralization logic
-
# super
-
# end
-
# end
-
#
-
# I18n::Backend::Simple.include(I18n::Backend::Pluralization)
-
1
class Simple
-
3
(class << self; self; end).class_eval { public :include }
-
-
1
module Implementation
-
1
include Base
-
-
1
def initialized?
-
@initialized ||= false
-
end
-
-
# Stores translations for the given locale in memory.
-
# This uses a deep merge for the translations hash, so existing
-
# translations will be overwritten by new ones only at the deepest
-
# level of the hash.
-
1
def store_translations(locale, data, options = {})
-
locale = locale.to_sym
-
translations[locale] ||= {}
-
data = data.deep_symbolize_keys
-
translations[locale].deep_merge!(data)
-
end
-
-
# Get available locales from the translations hash
-
1
def available_locales
-
init_translations unless initialized?
-
translations.inject([]) do |locales, (locale, data)|
-
locales << locale unless (data.keys - [:i18n]).empty?
-
locales
-
end
-
end
-
-
# Clean up translations hash and set initialized to false on reload!
-
1
def reload!
-
1
@initialized = false
-
1
@translations = nil
-
1
super
-
end
-
-
1
protected
-
-
1
def init_translations
-
load_translations
-
@initialized = true
-
end
-
-
1
def translations
-
@translations ||= {}
-
end
-
-
# Looks up a translation from the translations hash. Returns nil if
-
# eiher key is nil, or locale, scope or key do not exist as a key in the
-
# nested translations hash. Splits keys or scopes containing dots
-
# into multiple keys, i.e. <tt>currency.format</tt> is regarded the same as
-
# <tt>%w(currency format)</tt>.
-
1
def lookup(locale, key, scope = [], options = {})
-
init_translations unless initialized?
-
keys = I18n.normalize_keys(locale, key, scope, options[:separator])
-
-
keys.inject(translations) do |result, _key|
-
_key = _key.to_sym
-
return nil unless result.is_a?(Hash) && result.has_key?(_key)
-
result = result[_key]
-
result = resolve(locale, _key, result, options.merge(:scope => nil)) if result.is_a?(Symbol)
-
result
-
end
-
end
-
end
-
-
1
include Implementation
-
end
-
end
-
end
-
# encoding: utf-8
-
1
module I18n
-
1
module Backend
-
1
module Transliterator
-
1
DEFAULT_REPLACEMENT_CHAR = "?"
-
-
# Given a locale and a UTF-8 string, return the locale's ASCII
-
# approximation for the string.
-
1
def transliterate(locale, string, replacement = nil)
-
@transliterators ||= {}
-
@transliterators[locale] ||= Transliterator.get I18n.t(:'i18n.transliterate.rule',
-
:locale => locale, :resolve => false, :default => {})
-
@transliterators[locale].transliterate(string, replacement)
-
end
-
-
# Get a transliterator instance.
-
1
def self.get(rule = nil)
-
if !rule || rule.kind_of?(Hash)
-
HashTransliterator.new(rule)
-
elsif rule.kind_of? Proc
-
ProcTransliterator.new(rule)
-
else
-
raise I18n::ArgumentError, "Transliteration rule must be a proc or a hash."
-
end
-
end
-
-
# A transliterator which accepts a Proc as its transliteration rule.
-
1
class ProcTransliterator
-
1
def initialize(rule)
-
@rule = rule
-
end
-
-
1
def transliterate(string, replacement = nil)
-
@rule.call(string)
-
end
-
end
-
-
# A transliterator which accepts a Hash of characters as its translation
-
# rule.
-
1
class HashTransliterator
-
1
DEFAULT_APPROXIMATIONS = {
-
"À"=>"A", "Á"=>"A", "Â"=>"A", "Ã"=>"A", "Ä"=>"A", "Å"=>"A", "Æ"=>"AE",
-
"Ç"=>"C", "È"=>"E", "É"=>"E", "Ê"=>"E", "Ë"=>"E", "Ì"=>"I", "Í"=>"I",
-
"Î"=>"I", "Ï"=>"I", "Ð"=>"D", "Ñ"=>"N", "Ò"=>"O", "Ó"=>"O", "Ô"=>"O",
-
"Õ"=>"O", "Ö"=>"O", "×"=>"x", "Ø"=>"O", "Ù"=>"U", "Ú"=>"U", "Û"=>"U",
-
"Ü"=>"U", "Ý"=>"Y", "Þ"=>"Th", "ß"=>"ss", "à"=>"a", "á"=>"a", "â"=>"a",
-
"ã"=>"a", "ä"=>"a", "å"=>"a", "æ"=>"ae", "ç"=>"c", "è"=>"e", "é"=>"e",
-
"ê"=>"e", "ë"=>"e", "ì"=>"i", "í"=>"i", "î"=>"i", "ï"=>"i", "ð"=>"d",
-
"ñ"=>"n", "ò"=>"o", "ó"=>"o", "ô"=>"o", "õ"=>"o", "ö"=>"o", "ø"=>"o",
-
"ù"=>"u", "ú"=>"u", "û"=>"u", "ü"=>"u", "ý"=>"y", "þ"=>"th", "ÿ"=>"y",
-
"Ā"=>"A", "ā"=>"a", "Ă"=>"A", "ă"=>"a", "Ą"=>"A", "ą"=>"a", "Ć"=>"C",
-
"ć"=>"c", "Ĉ"=>"C", "ĉ"=>"c", "Ċ"=>"C", "ċ"=>"c", "Č"=>"C", "č"=>"c",
-
"Ď"=>"D", "ď"=>"d", "Đ"=>"D", "đ"=>"d", "Ē"=>"E", "ē"=>"e", "Ĕ"=>"E",
-
"ĕ"=>"e", "Ė"=>"E", "ė"=>"e", "Ę"=>"E", "ę"=>"e", "Ě"=>"E", "ě"=>"e",
-
"Ĝ"=>"G", "ĝ"=>"g", "Ğ"=>"G", "ğ"=>"g", "Ġ"=>"G", "ġ"=>"g", "Ģ"=>"G",
-
"ģ"=>"g", "Ĥ"=>"H", "ĥ"=>"h", "Ħ"=>"H", "ħ"=>"h", "Ĩ"=>"I", "ĩ"=>"i",
-
"Ī"=>"I", "ī"=>"i", "Ĭ"=>"I", "ĭ"=>"i", "Į"=>"I", "į"=>"i", "İ"=>"I",
-
"ı"=>"i", "IJ"=>"IJ", "ij"=>"ij", "Ĵ"=>"J", "ĵ"=>"j", "Ķ"=>"K", "ķ"=>"k",
-
"ĸ"=>"k", "Ĺ"=>"L", "ĺ"=>"l", "Ļ"=>"L", "ļ"=>"l", "Ľ"=>"L", "ľ"=>"l",
-
"Ŀ"=>"L", "ŀ"=>"l", "Ł"=>"L", "ł"=>"l", "Ń"=>"N", "ń"=>"n", "Ņ"=>"N",
-
"ņ"=>"n", "Ň"=>"N", "ň"=>"n", "ʼn"=>"'n", "Ŋ"=>"NG", "ŋ"=>"ng",
-
"Ō"=>"O", "ō"=>"o", "Ŏ"=>"O", "ŏ"=>"o", "Ő"=>"O", "ő"=>"o", "Œ"=>"OE",
-
"œ"=>"oe", "Ŕ"=>"R", "ŕ"=>"r", "Ŗ"=>"R", "ŗ"=>"r", "Ř"=>"R", "ř"=>"r",
-
"Ś"=>"S", "ś"=>"s", "Ŝ"=>"S", "ŝ"=>"s", "Ş"=>"S", "ş"=>"s", "Š"=>"S",
-
"š"=>"s", "Ţ"=>"T", "ţ"=>"t", "Ť"=>"T", "ť"=>"t", "Ŧ"=>"T", "ŧ"=>"t",
-
"Ũ"=>"U", "ũ"=>"u", "Ū"=>"U", "ū"=>"u", "Ŭ"=>"U", "ŭ"=>"u", "Ů"=>"U",
-
"ů"=>"u", "Ű"=>"U", "ű"=>"u", "Ų"=>"U", "ų"=>"u", "Ŵ"=>"W", "ŵ"=>"w",
-
"Ŷ"=>"Y", "ŷ"=>"y", "Ÿ"=>"Y", "Ź"=>"Z", "ź"=>"z", "Ż"=>"Z", "ż"=>"z",
-
"Ž"=>"Z", "ž"=>"z"
-
}.freeze
-
-
1
def initialize(rule = nil)
-
@rule = rule
-
add DEFAULT_APPROXIMATIONS.dup
-
add rule if rule
-
end
-
-
1
def transliterate(string, replacement = nil)
-
string.gsub(/[^\x00-\x7f]/u) do |char|
-
approximations[char] || replacement || DEFAULT_REPLACEMENT_CHAR
-
end
-
end
-
-
1
private
-
-
1
def approximations
-
@approximations ||= {}
-
end
-
-
# Add transliteration rules to the approximations hash.
-
1
def add(hash)
-
hash.each do |key, value|
-
approximations[key.to_s] = value.to_s
-
end
-
end
-
end
-
end
-
end
-
end
-
1
class Hash
-
def slice(*keep_keys)
-
h = {}
-
keep_keys.each { |key| h[key] = fetch(key) }
-
h
-
1
end unless Hash.method_defined?(:slice)
-
-
def except(*less_keys)
-
slice(*keys - less_keys)
-
1
end unless Hash.method_defined?(:except)
-
-
def deep_symbolize_keys
-
inject({}) { |result, (key, value)|
-
value = value.deep_symbolize_keys if value.is_a?(Hash)
-
result[(key.to_sym rescue key) || key] = value
-
result
-
}
-
1
end unless Hash.method_defined?(:deep_symbolize_keys)
-
-
# deep_merge_hash! by Stefan Rusterholz, see http://www.ruby-forum.com/topic/142809
-
1
MERGER = proc do |key, v1, v2|
-
Hash === v1 && Hash === v2 ? v1.merge(v2, &MERGER) : v2
-
end
-
-
def deep_merge!(data)
-
merge!(data, &MERGER)
-
1
end unless Hash.method_defined?(:deep_merge!)
-
end
-
-
1
module Kernel
-
1
def suppress_warnings
-
original_verbosity, $VERBOSE = $VERBOSE, nil
-
yield
-
ensure
-
$VERBOSE = original_verbosity
-
end
-
end
-
1
require 'cgi'
-
-
1
module I18n
-
# Handles exceptions raised in the backend. All exceptions except for
-
# MissingTranslationData exceptions are re-thrown. When a MissingTranslationData
-
# was caught the handler returns an error message string containing the key/scope.
-
# Note that the exception handler is not called when the option :throw was given.
-
1
class ExceptionHandler
-
1
include Module.new {
-
1
def call(exception, locale, key, options)
-
if exception.is_a?(MissingTranslation)
-
#
-
# TODO: this block is to be replaced by `exception.message` when
-
# rescue_format is removed
-
if options[:rescue_format] == :html
-
if !defined?(@rescue_format_deprecation)
-
$stderr.puts "[DEPRECATED] I18n's :recue_format option will be removed from a future release. All exception messages will be plain text. If you need the exception handler to return an html format please set or pass a custom exception handler."
-
@rescue_format_deprecation = true
-
end
-
exception.html_message
-
else
-
exception.message
-
end
-
-
elsif exception.is_a?(Exception)
-
raise exception
-
else
-
throw :exception, exception
-
end
-
end
-
}
-
end
-
-
1
class ArgumentError < ::ArgumentError; end
-
-
1
class InvalidLocale < ArgumentError
-
1
attr_reader :locale
-
1
def initialize(locale)
-
@locale = locale
-
super "#{locale.inspect} is not a valid locale"
-
end
-
end
-
-
1
class InvalidLocaleData < ArgumentError
-
1
attr_reader :filename
-
1
def initialize(filename, exception_message)
-
@filename, @exception_message = filename, exception_message
-
super "can not load translations from #{filename}: #{exception_message}"
-
end
-
end
-
-
1
class MissingTranslation
-
1
module Base
-
1
attr_reader :locale, :key, :options
-
-
1
def initialize(locale, key, options = nil)
-
@key, @locale, @options = key, locale, options.dup || {}
-
options.each { |k, v| self.options[k] = v.inspect if v.is_a?(Proc) }
-
end
-
-
1
def html_message
-
key = CGI.escapeHTML titleize(keys.last)
-
path = CGI.escapeHTML keys.join('.')
-
%(<span class="translation_missing" title="translation missing: #{path}">#{key}</span>)
-
end
-
-
1
def keys
-
@keys ||= I18n.normalize_keys(locale, key, options[:scope]).tap do |keys|
-
keys << 'no key' if keys.size < 2
-
end
-
end
-
-
1
def message
-
"translation missing: #{keys.join('.')}"
-
end
-
1
alias :to_s :message
-
-
1
def to_exception
-
MissingTranslationData.new(locale, key, options)
-
end
-
-
1
protected
-
-
# TODO : remove when #html_message is removed
-
1
def titleize(key)
-
key.to_s.gsub('_', ' ').gsub(/\b('?[a-z])/) { $1.capitalize }
-
end
-
end
-
-
1
include Base
-
end
-
-
1
class MissingTranslationData < ArgumentError
-
1
include MissingTranslation::Base
-
end
-
-
1
class InvalidPluralizationData < ArgumentError
-
1
attr_reader :entry, :count
-
1
def initialize(entry, count)
-
@entry, @count = entry, count
-
super "translation data #{entry.inspect} can not be used with :count => #{count}"
-
end
-
end
-
-
1
class MissingInterpolationArgument < ArgumentError
-
1
attr_reader :key, :values, :string
-
1
def initialize(key, values, string)
-
@key, @values, @string = key, values, string
-
super "missing interpolation argument #{key.inspect} in #{string.inspect} (#{values.inspect} given)"
-
end
-
end
-
-
1
class ReservedInterpolationKey < ArgumentError
-
1
attr_reader :key, :string
-
1
def initialize(key, string)
-
@key, @string = key, string
-
super "reserved key #{key.inspect} used in #{string.inspect}"
-
end
-
end
-
-
1
class UnknownFileType < ArgumentError
-
1
attr_reader :type, :filename
-
1
def initialize(type, filename)
-
@type, @filename = type, filename
-
super "can not load translations from #{filename}, the file type #{type} is not known"
-
end
-
end
-
end
-
# heavily based on Masao Mutoh's gettext String interpolation extension
-
# http://github.com/mutoh/gettext/blob/f6566738b981fe0952548c421042ad1e0cdfb31e/lib/gettext/core_ext/string.rb
-
-
1
module I18n
-
1
INTERPOLATION_PATTERN = Regexp.union(
-
/%%/,
-
/%\{(\w+)\}/, # matches placeholders like "%{foo}"
-
/%<(\w+)>(.*?\d*\.?\d*[bBdiouxXeEfgGcps])/ # matches placeholders like "%<foo>.d"
-
)
-
-
1
class << self
-
# Return String or raises MissingInterpolationArgument exception.
-
# Missing argument's logic is handled by I18n.config.missing_interpolation_argument_handler.
-
1
def interpolate(string, values)
-
raise ReservedInterpolationKey.new($1.to_sym, string) if string =~ RESERVED_KEYS_PATTERN
-
raise ArgumentError.new('Interpolation values must be a Hash.') unless values.kind_of?(Hash)
-
interpolate_hash(string, values)
-
end
-
-
1
def interpolate_hash(string, values)
-
string.gsub(INTERPOLATION_PATTERN) do |match|
-
if match == '%%'
-
'%'
-
else
-
key = ($1 || $2).to_sym
-
value = if values.key?(key)
-
values[key]
-
else
-
config.missing_interpolation_argument_handler.call(key, values, string)
-
end
-
value = value.call(values) if value.respond_to?(:call)
-
$3 ? sprintf("%#{$3}", value) : value
-
end
-
end
-
end
-
end
-
end
-
1
module I18n
-
1
VERSION = "0.6.11"
-
end
-
1
require 'active_support/ordered_hash'
-
1
require 'active_support/core_ext/array/access'
-
1
require 'active_support/core_ext/enumerable'
-
1
require 'active_support/core_ext/hash'
-
1
require 'active_support/cache'
-
1
require 'multi_json'
-
-
1
begin
-
1
require 'active_support/proxy_object'
-
1
JbuilderProxy = ActiveSupport::ProxyObject
-
rescue LoadError
-
require 'active_support/basic_object'
-
JbuilderProxy = ActiveSupport::BasicObject
-
end
-
-
1
class Jbuilder < JbuilderProxy
-
1
class NullError < ::NoMethodError
-
1
def initialize(key)
-
super "Failed to add #{key.to_s.inspect} property to null object"
-
end
-
end
-
-
1
class KeyFormatter
-
1
def initialize(*args)
-
1
@format = ::ActiveSupport::OrderedHash.new
-
1
@cache = {}
-
-
1
options = args.extract_options!
-
1
args.each do |name|
-
@format[name] = []
-
end
-
1
options.each do |name, paramaters|
-
@format[name] = paramaters
-
end
-
end
-
-
1
def initialize_copy(original)
-
@cache = {}
-
end
-
-
1
def format(key)
-
@cache[key] ||= @format.inject(key.to_s) do |result, args|
-
func, args = args
-
if ::Proc === func
-
func.call result, *args
-
else
-
result.send func, *args
-
end
-
end
-
end
-
end
-
-
# Yields a builder and automatically turns the result into a JSON string
-
1
def self.encode(*args, &block)
-
new(*args, &block).target!
-
end
-
-
1
@@key_formatter = KeyFormatter.new
-
1
@@ignore_nil = false
-
-
1
def initialize(*args, &block)
-
@attributes = ::ActiveSupport::OrderedHash.new
-
-
options = args.extract_options!
-
@key_formatter = options.fetch(:key_formatter){ @@key_formatter.clone }
-
@ignore_nil = options.fetch(:ignore_nil, @@ignore_nil)
-
yield self if block
-
end
-
-
1
BLANK = ::Object.new
-
-
1
def set!(key, value = BLANK, *args, &block)
-
-
result = if block
-
if BLANK != value
-
# json.comments @post.comments { |comment| ... }
-
# { "comments": [ { ... }, { ... } ] }
-
_scope{ array! value, &block }
-
else
-
# json.comments { ... }
-
# { "comments": ... }
-
_scope { yield self }
-
end
-
elsif args.empty?
-
if ::Jbuilder === value
-
# json.age 32
-
# json.person another_jbuilder
-
# { "age": 32, "person": { ... }
-
value.attributes!
-
else
-
# json.age 32
-
# { "age": 32 }
-
value
-
end
-
elsif _mapable_arguments?(value, *args)
-
# json.comments @post.comments, :content, :created_at
-
# { "comments": [ { "content": "hello", "created_at": "..." }, { "content": "world", "created_at": "..." } ] }
-
_scope{ array! value, *args }
-
else
-
# json.author @post.creator, :name, :email_address
-
# { "author": { "name": "David", "email_address": "david@loudthinking.com" } }
-
_scope { extract! value, *args }
-
end
-
-
_set_value key, result
-
end
-
-
1
alias_method :method_missing, :set!
-
1
private :method_missing
-
-
-
# Specifies formatting to be applied to the key. Passing in a name of a function
-
# will cause that function to be called on the key. So :upcase will upper case
-
# the key. You can also pass in lambdas for more complex transformations.
-
#
-
# Example:
-
#
-
# json.key_format! :upcase
-
# json.author do
-
# json.name "David"
-
# json.age 32
-
# end
-
#
-
# { "AUTHOR": { "NAME": "David", "AGE": 32 } }
-
#
-
# You can pass parameters to the method using a hash pair.
-
#
-
# json.key_format! camelize: :lower
-
# json.first_name "David"
-
#
-
# { "firstName": "David" }
-
#
-
# Lambdas can also be used.
-
#
-
# json.key_format! ->(key){ "_" + key }
-
# json.first_name "David"
-
#
-
# { "_first_name": "David" }
-
#
-
1
def key_format!(*args)
-
@key_formatter = KeyFormatter.new(*args)
-
end
-
-
# Same as the instance method key_format! except sets the default.
-
1
def self.key_format(*args)
-
@@key_formatter = KeyFormatter.new(*args)
-
end
-
-
# If you want to skip adding nil values to your JSON hash. This is useful
-
# for JSON clients that don't deal well with nil values, and would prefer
-
# not to receive keys which have null values.
-
#
-
# Example:
-
# json.ignore_nil! false
-
# json.id User.new.id
-
#
-
# { "id": null }
-
#
-
# json.ignore_nil!
-
# json.id User.new.id
-
#
-
# {}
-
#
-
1
def ignore_nil!(value = true)
-
@ignore_nil = value
-
end
-
-
# Same as instance method ignore_nil! except sets the default.
-
1
def self.ignore_nil(value = true)
-
@@ignore_nil = value
-
end
-
-
# Turns the current element into an array and yields a builder to add a hash.
-
#
-
# Example:
-
#
-
# json.comments do
-
# json.child! { json.content "hello" }
-
# json.child! { json.content "world" }
-
# end
-
#
-
# { "comments": [ { "content": "hello" }, { "content": "world" } ]}
-
#
-
# More commonly, you'd use the combined iterator, though:
-
#
-
# json.comments(@post.comments) do |comment|
-
# json.content comment.formatted_content
-
# end
-
1
def child!
-
@attributes = [] unless ::Array === @attributes
-
@attributes << _scope { yield self }
-
end
-
-
# Turns the current element into an array and iterates over the passed collection, adding each iteration as
-
# an element of the resulting array.
-
#
-
# Example:
-
#
-
# json.array!(@people) do |person|
-
# json.name person.name
-
# json.age calculate_age(person.birthday)
-
# end
-
#
-
# [ { "name": David", "age": 32 }, { "name": Jamie", "age": 31 } ]
-
#
-
# If you are using Ruby 1.9+, you can use the call syntax instead of an explicit extract! call:
-
#
-
# json.(@people) { |person| ... }
-
#
-
# It's generally only needed to use this method for top-level arrays. If you have named arrays, you can do:
-
#
-
# json.people(@people) do |person|
-
# json.name person.name
-
# json.age calculate_age(person.birthday)
-
# end
-
#
-
# { "people": [ { "name": David", "age": 32 }, { "name": Jamie", "age": 31 } ] }
-
#
-
# If you omit the block then you can set the top level array directly:
-
#
-
# json.array! [1, 2, 3]
-
#
-
# [1,2,3]
-
1
def array!(collection = [], *attributes, &block)
-
@attributes = if block && block.arity == 2
-
_two_arguments_map_collection(collection, &block)
-
elsif block
-
_map_collection(collection, &block)
-
elsif attributes.any?
-
_map_collection(collection) { |element| extract! element, *attributes }
-
else
-
collection
-
end
-
end
-
-
# Extracts the mentioned attributes or hash elements from the passed object and turns them into attributes of the JSON.
-
#
-
# Example:
-
#
-
# @person = Struct.new(:name, :age).new('David', 32)
-
#
-
# or you can utilize a Hash
-
#
-
# @person = { name: 'David', age: 32 }
-
#
-
# json.extract! @person, :name, :age
-
#
-
# { "name": David", "age": 32 }, { "name": Jamie", "age": 31 }
-
#
-
# You can also use the call syntax instead of an explicit extract! call:
-
#
-
# json.(@person, :name, :age)
-
1
def extract!(object, *attributes)
-
if ::Hash === object
-
_extract_hash_values(object, *attributes)
-
else
-
_extract_method_values(object, *attributes)
-
end
-
end
-
-
1
def call(object, *attributes, &block)
-
if block
-
array! object, &block
-
else
-
extract! object, *attributes
-
end
-
end
-
-
# Returns the nil JSON.
-
1
def nil!
-
@attributes = nil
-
end
-
-
1
alias_method :null!, :nil!
-
-
# Returns the attributes of the current builder.
-
1
def attributes!
-
@attributes
-
end
-
-
# Encodes the current builder as JSON.
-
1
def target!
-
::MultiJson.dump @attributes
-
end
-
-
1
private
-
-
1
def _extract_hash_values(object, *attributes)
-
attributes.each{ |key| _set_value key, object.fetch(key) }
-
end
-
-
1
def _extract_method_values(object, *attributes)
-
attributes.each do |method_name|
-
unless object.respond_to?(method_name)
-
message = "Private method #{method_name.inspect} was used to " +
-
'extract value. This will be an error in future versions of Jbuilder'
-
end
-
-
_set_value method_name, object.send(method_name)
-
::ActiveSupport::Deprecation.warn message if message
-
end
-
end
-
-
1
def _set_value(key, value)
-
raise NullError, key if @attributes.nil?
-
unless @ignore_nil && value.nil?
-
@attributes[@key_formatter.format(key)] = value
-
end
-
end
-
-
1
def _map_collection(collection)
-
return [] if collection.nil?
-
-
collection.map do |element|
-
_scope { yield element }
-
end
-
end
-
-
1
def _scope
-
parent_attributes, parent_formatter = @attributes, @key_formatter
-
@attributes = ::ActiveSupport::OrderedHash.new
-
yield
-
@attributes
-
ensure
-
@attributes, @key_formatter = parent_attributes, parent_formatter
-
end
-
-
1
def _merge(hash_or_array)
-
if ::Array === hash_or_array
-
@attributes = [] unless ::Array === @attributes
-
@attributes.concat hash_or_array
-
else
-
@attributes.update hash_or_array
-
end
-
end
-
-
1
def _two_arguments_map_collection(collection, &block)
-
message = "Passing jbuilder object to block is " \
-
"deprecated and will be removed soon."
-
-
if block.respond_to?(:parameters)
-
arguments = block.parameters.map(&:last)
-
actual = "|#{arguments.drop(1) * ', '}|"
-
deprecated = "|#{arguments * ', '}|"
-
message += "\nUse #{actual} instead of #{deprecated} as block arguments"
-
end
-
-
::ActiveSupport::Deprecation.warn message, ::Kernel.caller(5)
-
-
_map_collection(collection){ |element| block[self, element] }
-
end
-
-
1
def _mapable_arguments?(value, *args)
-
value.respond_to?(:map)
-
end
-
end
-
-
1
require 'jbuilder/jbuilder_template' if defined?(ActionView::Template)
-
1
require 'jbuilder/railtie' if defined?(Rails::VERSION::MAJOR) && Rails::VERSION::MAJOR == 4
-
1
require 'jbuilder'
-
1
require 'action_dispatch/http/mime_type'
-
-
1
class JbuilderTemplate < Jbuilder
-
1
class << self
-
1
attr_accessor :template_lookup_options
-
end
-
-
1
self.template_lookup_options = { :handlers => [:jbuilder] }
-
-
1
def initialize(context, *args, &block)
-
@context = context
-
super(*args, &block)
-
end
-
-
1
def partial!(name_or_options, locals = {})
-
case name_or_options
-
when ::Hash
-
# partial! partial: 'name', locals: { foo: 'bar' }
-
options = name_or_options
-
else
-
# partial! 'name', foo: 'bar'
-
options = { :partial => name_or_options, :locals => locals }
-
as = locals.delete(:as)
-
options[:as] = as if as.present?
-
options[:collection] = locals[:collection] if locals.key?(:collection)
-
end
-
-
options[:collection] ||= [] if options.key?(:collection)
-
-
_handle_partial_options options
-
end
-
-
1
def array!(collection = [], *attributes, &block)
-
options = attributes.extract_options!
-
-
if options.key?(:partial)
-
partial! options[:partial], options.merge(:collection => collection)
-
else
-
super
-
end
-
end
-
-
# Caches the json constructed within the block passed. Has the same signature as the `cache` helper
-
# method in `ActionView::Helpers::CacheHelper` and so can be used in the same way.
-
#
-
# Example:
-
#
-
# json.cache! ['v1', @person], expires_in: 10.minutes do
-
# json.extract! @person, :name, :age
-
# end
-
1
def cache!(key=nil, options={}, &block)
-
if @context.controller.perform_caching
-
value = ::Rails.cache.fetch(_cache_key(key), options) do
-
_scope { yield self }
-
end
-
-
_merge(value)
-
else
-
yield
-
end
-
end
-
-
1
protected
-
1
def _handle_partial_options(options)
-
options.reverse_merge! :locals => {}
-
options.reverse_merge! ::JbuilderTemplate.template_lookup_options
-
collection = options.delete(:collection)
-
as = options[:as]
-
-
if collection && as
-
array!(collection) do |member|
-
options[:locals].merge!(as => member, :collection => collection)
-
_render_partial options
-
end
-
else
-
_render_partial options
-
end
-
end
-
-
1
def _render_partial(options)
-
options[:locals].merge!(:json => self)
-
@context.render options
-
end
-
-
1
def _cache_key(key)
-
if @context.respond_to?(:cache_fragment_name)
-
# Current compatibility, fragment_name_with_digest is private again and cache_fragment_name
-
# should be used instead.
-
@context.cache_fragment_name(key)
-
elsif @context.respond_to?(:fragment_name_with_digest)
-
# Backwards compatibility for period of time when fragment_name_with_digest was made public.
-
@context.fragment_name_with_digest(key)
-
else
-
::ActiveSupport::Cache.expand_cache_key(key.is_a?(::Hash) ? url_for(key).split('://').last : key, :jbuilder)
-
end
-
end
-
-
1
private
-
-
1
def _mapable_arguments?(value, *args)
-
return true if super
-
options = args.last
-
::Hash === options && options.key?(:as)
-
end
-
end
-
-
1
class JbuilderHandler
-
1
cattr_accessor :default_format
-
1
self.default_format = Mime::JSON
-
-
1
def self.call(template)
-
# this juggling is required to keep line numbers right in the error
-
%{__already_defined = defined?(json); json||=JbuilderTemplate.new(self); #{template.source}
-
json.target! unless __already_defined}
-
end
-
end
-
-
1
ActionView::Template.register_template_handler :jbuilder, JbuilderHandler
-
1
require 'rails/railtie'
-
-
1
class Jbuilder
-
1
class Railtie < ::Rails::Railtie
-
1
generators do |app|
-
Rails::Generators.configure! app.config.generators
-
Rails::Generators.hidden_namespaces.uniq!
-
require 'generators/rails/scaffold_controller_generator'
-
end
-
end
-
end
-
1
module ActionDispatch
-
1
module Assertions
-
1
module SelectorAssertions
-
# Selects content from a JQuery response. Patterned loosely on
-
# assert_select_rjs.
-
#
-
# === Narrowing down
-
#
-
# With no arguments, asserts that one or more method calls are made.
-
#
-
# Use the +method+ argument to narrow down the assertion to only
-
# statements that call that specific method.
-
#
-
# Use the +opt+ argument to narrow down the assertion to only statements
-
# that pass +opt+ as the first argument.
-
#
-
# Use the +id+ argument to narrow down the assertion to only statements
-
# that invoke methods on the result of using that identifier as a
-
# selector.
-
#
-
# === Using blocks
-
#
-
# Without a block, +assert_select_jquery_ merely asserts that the
-
# response contains one or more statements that match the conditions
-
# specified above
-
#
-
# With a block +assert_select_jquery_ also asserts that the method call
-
# passes a javascript escaped string containing HTML. All such HTML
-
# fragments are selected and passed to the block. Nested assertions are
-
# supported.
-
#
-
# === Examples
-
#
-
# # asserts that the #notice element is hidden
-
# assert_select :hide, '#notice'
-
#
-
# # asserts that the #cart element is shown with a blind parameter
-
# assert_select :show, :blind, '#cart'
-
#
-
# # asserts that #cart content contains a #current_item
-
# assert_select :html, '#cart' do
-
# assert_select '#current_item'
-
# end
-
-
1
PATTERN_HTML = "\"((\\\\\"|[^\"])*)\""
-
1
PATTERN_UNICODE_ESCAPED_CHAR = /\\u([0-9a-zA-Z]{4})/
-
-
1
def assert_select_jquery(*args, &block)
-
jquery_method = args.first.is_a?(Symbol) ? args.shift : nil
-
jquery_opt = args.first.is_a?(Symbol) ? args.shift : nil
-
id = args.first.is_a?(String) ? args.shift : nil
-
-
pattern = "\\.#{jquery_method || '\\w+'}\\("
-
pattern = "#{pattern}['\"]#{jquery_opt}['\"],?\\s*" if jquery_opt
-
pattern = "#{pattern}#{PATTERN_HTML}"
-
pattern = "(?:jQuery|\\$)\\(['\"]#{id}['\"]\\)#{pattern}" if id
-
-
fragments = []
-
response.body.scan(Regexp.new(pattern)).each do |match|
-
doc = HTML::Document.new(unescape_js(match.first))
-
doc.root.children.each do |child|
-
fragments.push child if child.tag?
-
end
-
end
-
-
if fragments.empty?
-
opts = [jquery_method, jquery_opt, id].compact
-
flunk "No JQuery call matches #{opts.inspect}"
-
end
-
-
if block
-
begin
-
in_scope, @selected = @selected, fragments
-
yield
-
ensure
-
@selected = in_scope
-
end
-
end
-
end
-
-
1
private
-
-
# Unescapes a JS string.
-
1
def unescape_js(js_string)
-
# js encodes double quotes and line breaks.
-
unescaped= js_string.gsub('\"', '"')
-
unescaped.gsub!('\\\'', "'")
-
unescaped.gsub!(/\\\//, '/')
-
unescaped.gsub!('\n', "\n")
-
unescaped.gsub!('\076', '>')
-
unescaped.gsub!('\074', '<')
-
# js encodes non-ascii characters.
-
unescaped.gsub!(PATTERN_UNICODE_ESCAPED_CHAR) {|u| [$1.hex].pack('U*')}
-
unescaped
-
end
-
-
end
-
end
-
end
-
1
require 'jquery/assert_select' if ::Rails.env.test?
-
1
require 'jquery/rails/engine' if ::Rails.version >= '3.1'
-
1
require 'jquery/rails/railtie'
-
1
require 'jquery/rails/version'
-
-
1
module Jquery
-
1
module Rails
-
1
PROTOTYPE_JS = %w{prototype effects dragdrop controls}
-
end
-
end
-
1
module Jquery
-
1
module Rails
-
1
class Engine < ::Rails::Engine
-
end
-
end
-
end
-
# Used to ensure that Rails 3.0.x, as well as Rails >= 3.1 with asset pipeline disabled
-
# get the minified version of the scripts included into the layout in production.
-
1
module Jquery
-
1
module Rails
-
1
class Railtie < ::Rails::Railtie
-
1
config.before_configuration do
-
1
if config.action_view.javascript_expansions
-
jq_defaults = ::Rails.env.production? || ::Rails.env.test? ? %w(jquery.min) : %w(jquery)
-
-
# Merge the jQuery scripts, remove the Prototype defaults and finally add 'jquery_ujs'
-
# at the end, because load order is important
-
config.action_view.javascript_expansions[:defaults] -= PROTOTYPE_JS + ['rails']
-
config.action_view.javascript_expansions[:defaults] |= jq_defaults + ['jquery_ujs']
-
end
-
end
-
end
-
end
-
end
-
1
module Jquery
-
1
module Rails
-
1
VERSION = "3.1.2"
-
1
JQUERY_VERSION = "1.11.1"
-
1
JQUERY_UJS_VERSION = "1.0.1"
-
end
-
end
-
1
require 'jquery-tablesorter/engine'
-
-
1
module JqueryTablesorter
-
end
-
1
module JqueryTablesorter
-
1
class Engine < Rails::Engine
-
1
isolate_namespace JqueryTablesorter
-
end
-
end
-
1
require 'jquery/ui/rails'
-
1
require 'jquery/ui/rails/engine'
-
1
require 'jquery/ui/rails/version'
-
1
module Jquery
-
1
module Ui
-
1
module Rails
-
1
class Engine < ::Rails::Engine
-
end
-
end
-
end
-
end
-
1
module Jquery
-
1
module Ui
-
1
module Rails
-
1
VERSION = "5.0.0"
-
1
JQUERY_UI_VERSION = "1.11.0"
-
end
-
end
-
end
-
1
module Kaminari
-
end
-
-
# load Rails/Railtie
-
1
begin
-
1
require 'rails'
-
rescue LoadError
-
#do nothing
-
end
-
-
1
$stderr.puts <<-EOC if !defined?(Rails) && !defined?(Sinatra) && !defined?(Grape)
-
warning: no framework detected.
-
-
Your Gemfile might not be configured properly.
-
---- e.g. ----
-
Rails:
-
gem 'kaminari'
-
-
Sinatra/Padrino:
-
gem 'kaminari', :require => 'kaminari/sinatra'
-
-
Grape:
-
gem 'kaminari', :require => 'kaminari/grape'
-
-
EOC
-
-
# load Kaminari components
-
1
require 'kaminari/config'
-
1
require 'kaminari/helpers/action_view_extension'
-
1
require 'kaminari/helpers/paginator'
-
1
require 'kaminari/models/page_scope_methods'
-
1
require 'kaminari/models/configuration_methods'
-
1
require 'kaminari/hooks'
-
-
# if not using Railtie, call `Kaminari::Hooks.init` directly
-
1
if defined? Rails
-
1
require 'kaminari/railtie'
-
1
require 'kaminari/engine'
-
end
-
1
require 'active_support/configurable'
-
-
1
module Kaminari
-
# Configures global settings for Kaminari
-
# Kaminari.configure do |config|
-
# config.default_per_page = 10
-
# end
-
1
def self.configure(&block)
-
1
yield @config ||= Kaminari::Configuration.new
-
end
-
-
# Global settings for Kaminari
-
1
def self.config
-
3
@config
-
end
-
-
# need a Class for 3.0
-
1
class Configuration #:nodoc:
-
1
include ActiveSupport::Configurable
-
1
config_accessor :default_per_page
-
1
config_accessor :max_per_page
-
1
config_accessor :window
-
1
config_accessor :outer_window
-
1
config_accessor :left
-
1
config_accessor :right
-
1
config_accessor :page_method_name
-
1
config_accessor :max_pages
-
-
1
def param_name
-
config.param_name.respond_to?(:call) ? config.param_name.call : config.param_name
-
end
-
-
# define param_name writer (copied from AS::Configurable)
-
1
writer, line = 'def param_name=(value); config.param_name = value; end', __LINE__
-
1
singleton_class.class_eval writer, __FILE__, line
-
1
class_eval writer, __FILE__, line
-
end
-
-
# this is ugly. why can't we pass the default value to config_accessor...?
-
1
configure do |config|
-
1
config.default_per_page = 25
-
1
config.max_per_page = nil
-
1
config.window = 4
-
1
config.outer_window = 0
-
1
config.left = 0
-
1
config.right = 0
-
1
config.page_method_name = :page
-
1
config.param_name = :page
-
1
config.max_pages = nil
-
end
-
end
-
1
module Kaminari #:nodoc:
-
1
class Engine < ::Rails::Engine #:nodoc:
-
end
-
end
-
1
module Kaminari
-
# = Helpers
-
1
module ActionViewExtension
-
# A helper that renders the pagination links.
-
#
-
# <%= paginate @articles %>
-
#
-
# ==== Options
-
# * <tt>:window</tt> - The "inner window" size (4 by default).
-
# * <tt>:outer_window</tt> - The "outer window" size (0 by default).
-
# * <tt>:left</tt> - The "left outer window" size (0 by default).
-
# * <tt>:right</tt> - The "right outer window" size (0 by default).
-
# * <tt>:params</tt> - url_for parameters for the links (:controller, :action, etc.)
-
# * <tt>:param_name</tt> - parameter name for page number in the links (:page by default)
-
# * <tt>:remote</tt> - Ajax? (false by default)
-
# * <tt>:ANY_OTHER_VALUES</tt> - Any other hash key & values would be directly passed into each tag as :locals value.
-
1
def paginate(scope, options = {}, &block)
-
paginator = Kaminari::Helpers::Paginator.new self, options.reverse_merge(:current_page => scope.current_page, :total_pages => scope.total_pages, :per_page => scope.limit_value, :remote => false)
-
paginator.to_s
-
end
-
-
# A simple "Twitter like" pagination link that creates a link to the previous page.
-
#
-
# ==== Examples
-
# Basic usage:
-
#
-
# <%= link_to_previous_page @items, 'Previous Page' %>
-
#
-
# Ajax:
-
#
-
# <%= link_to_previous_page @items, 'Previous Page', :remote => true %>
-
#
-
# By default, it renders nothing if there are no more results on the previous page.
-
# You can customize this output by passing a block.
-
#
-
# <%= link_to_previous_page @users, 'Previous Page' do %>
-
# <span>At the Beginning</span>
-
# <% end %>
-
1
def link_to_previous_page(scope, name, options = {}, &block)
-
params = options.delete(:params) || {}
-
param_name = options.delete(:param_name) || Kaminari.config.param_name
-
link_to_unless scope.first_page?, name, params.merge(param_name => scope.prev_page), options.reverse_merge(:rel => 'previous') do
-
block.call if block
-
end
-
end
-
-
# A simple "Twitter like" pagination link that creates a link to the next page.
-
#
-
# ==== Examples
-
# Basic usage:
-
#
-
# <%= link_to_next_page @items, 'Next Page' %>
-
#
-
# Ajax:
-
#
-
# <%= link_to_next_page @items, 'Next Page', :remote => true %>
-
#
-
# By default, it renders nothing if there are no more results on the next page.
-
# You can customize this output by passing a block.
-
#
-
# <%= link_to_next_page @users, 'Next Page' do %>
-
# <span>No More Pages</span>
-
# <% end %>
-
1
def link_to_next_page(scope, name, options = {}, &block)
-
params = options.delete(:params) || {}
-
param_name = options.delete(:param_name) || Kaminari.config.param_name
-
link_to_unless scope.last_page?, name, params.merge(param_name => scope.next_page), options.reverse_merge(:rel => 'next') do
-
block.call if block
-
end
-
end
-
-
# Renders a helpful message with numbers of displayed vs. total entries.
-
# Ported from mislav/will_paginate
-
#
-
# ==== Examples
-
# Basic usage:
-
#
-
# <%= page_entries_info @posts %>
-
# #-> Displaying posts 6 - 10 of 26 in total
-
#
-
# By default, the message will use the humanized class name of objects
-
# in collection: for instance, "project types" for ProjectType models.
-
# The namespace will be cutted out and only the last name will be used.
-
# Override this with the <tt>:entry_name</tt> parameter:
-
#
-
# <%= page_entries_info @posts, :entry_name => 'item' %>
-
# #-> Displaying items 6 - 10 of 26 in total
-
1
def page_entries_info(collection, options = {})
-
entry_name = options[:entry_name] || collection.entry_name
-
entry_name = entry_name.pluralize unless collection.total_count == 1
-
-
if collection.total_pages < 2
-
t('helpers.page_entries_info.one_page.display_entries', :entry_name => entry_name, :count => collection.total_count)
-
else
-
first = collection.offset_value + 1
-
last = collection.last_page? ? collection.total_count : collection.offset_value + collection.limit_value
-
t('helpers.page_entries_info.more_pages.display_entries', :entry_name => entry_name, :first => first, :last => last, :total => collection.total_count)
-
end.html_safe
-
end
-
-
# Renders rel="next" and rel="prev" links to be used in the head.
-
#
-
# ==== Examples
-
# Basic usage:
-
#
-
# In head:
-
# <head>
-
# <title>My Website</title>
-
# <%= yield :head %>
-
# </head>
-
#
-
# Somewhere in body:
-
# <% content_for :head do %>
-
# <%= rel_next_prev_link_tags @items %>
-
# <% end %>
-
#
-
# #-> <link rel="next" href="/items/page/3" /><link rel="prev" href="/items/page/1" />
-
#
-
1
def rel_next_prev_link_tags(scope, options = {})
-
params = options.delete(:params) || {}
-
param_name = options.delete(:param_name) || Kaminari.config.param_name
-
-
output = ""
-
output << '<link rel="next" href="' + url_for(params.merge(param_name => scope.next_page, :only_path => true)) + '"/>' if scope.next_page
-
output << '<link rel="prev" href="' + url_for(params.merge(param_name => scope.prev_page, :only_path => true)) + '"/>' if scope.prev_page
-
-
output.html_safe
-
end
-
end
-
end
-
1
require 'active_support/inflector'
-
1
require 'action_view'
-
1
require 'action_view/log_subscriber'
-
1
require 'action_view/context'
-
1
require 'kaminari/helpers/tags'
-
-
1
module Kaminari
-
1
module Helpers
-
# The main container tag
-
1
class Paginator < Tag
-
# so that this instance can actually "render"
-
1
include ::ActionView::Context
-
-
1
def initialize(template, options) #:nodoc:
-
#FIXME for compatibility. remove num_pages at some time in the future
-
options[:total_pages] ||= options[:num_pages]
-
options[:num_pages] ||= options[:total_pages]
-
-
@window_options = {}.tap do |h|
-
h[:window] = options.delete(:window) || options.delete(:inner_window) || Kaminari.config.window
-
outer_window = options.delete(:outer_window) || Kaminari.config.outer_window
-
h[:left] = options.delete(:left) || Kaminari.config.left
-
h[:left] = outer_window if h[:left] == 0
-
h[:right] = options.delete(:right) || Kaminari.config.right
-
h[:right] = outer_window if h[:right] == 0
-
end
-
@template, @options = template, options
-
@theme = @options[:theme]
-
@views_prefix = @options[:views_prefix]
-
@window_options.merge! @options
-
@window_options[:current_page] = @options[:current_page] = PageProxy.new(@window_options, @options[:current_page], nil)
-
-
@last = nil
-
# initialize the output_buffer for Context
-
@output_buffer = ActionView::OutputBuffer.new
-
end
-
-
# render given block as a view template
-
1
def render(&block)
-
instance_eval(&block) if @options[:total_pages] > 1
-
@output_buffer
-
end
-
-
# enumerate each page providing PageProxy object as the block parameter
-
# Because of performance reason, this doesn't actually enumerate all pages but pages that are seemingly relevant to the paginator.
-
# "Relevant" pages are:
-
# * pages inside the left outer window plus one for showing the gap tag
-
# * pages inside the inner window plus one on the left plus one on the right for showing the gap tags
-
# * pages inside the right outer window plus one for showing the gap tag
-
1
def each_relevant_page
-
return to_enum(:each_relevant_page) unless block_given?
-
-
relevant_pages(@window_options).each do |page|
-
yield PageProxy.new(@window_options, page, @last)
-
end
-
end
-
1
alias each_page each_relevant_page
-
-
1
def relevant_pages(options)
-
left_window_plus_one = 1.upto(options[:left] + 1).to_a
-
right_window_plus_one = (options[:total_pages] - options[:right]).upto(options[:total_pages]).to_a
-
inside_window_plus_each_sides = (options[:current_page] - options[:window] - 1).upto(options[:current_page] + options[:window] + 1).to_a
-
-
(left_window_plus_one + inside_window_plus_each_sides + right_window_plus_one).uniq.sort.reject {|x| (x < 1) || (x > options[:total_pages])}
-
end
-
1
private :relevant_pages
-
-
1
def page_tag(page)
-
@last = Page.new @template, @options.merge(:page => page)
-
end
-
-
1
%w[first_page prev_page next_page last_page gap].each do |tag|
-
5
eval <<-DEF
-
def #{tag}_tag
-
@last = #{tag.classify}.new @template, @options
-
end
-
DEF
-
end
-
-
1
def to_s #:nodoc:
-
subscriber = ActionView::LogSubscriber.log_subscribers.detect {|ls| ls.is_a? ActionView::LogSubscriber}
-
-
# There is a logging subscriber
-
# and we don't want it to log render_partial
-
# It is threadsafe, but might not repress logging
-
# consistently in a high-load environment
-
if subscriber
-
unless defined? subscriber.render_partial_with_logging
-
class << subscriber
-
alias_method :render_partial_with_logging, :render_partial
-
attr_accessor :render_without_logging
-
# ugly hack to make a renderer where
-
# we can turn logging on or off
-
def render_partial(event)
-
render_partial_with_logging(event) unless render_without_logging
-
end
-
end
-
end
-
-
subscriber.render_without_logging = true
-
ret = super @window_options.merge :paginator => self
-
subscriber.render_without_logging = false
-
-
ret
-
else
-
super @window_options.merge :paginator => self
-
end
-
end
-
-
# delegates view helper methods to @template
-
1
def method_missing(name, *args, &block)
-
@template.respond_to?(name) ? @template.send(name, *args, &block) : super
-
end
-
1
private :method_missing
-
-
# Wraps a "page number" and provides some utility methods
-
1
class PageProxy
-
1
include Comparable
-
-
1
def initialize(options, page, last) #:nodoc:
-
@options, @page, @last = options, page, last
-
end
-
-
# the page number
-
1
def number
-
@page
-
end
-
-
# current page or not
-
1
def current?
-
@page == @options[:current_page]
-
end
-
-
# the first page or not
-
1
def first?
-
@page == 1
-
end
-
-
# the last page or not
-
1
def last?
-
@page == @options[:total_pages]
-
end
-
-
# the previous page or not
-
1
def prev?
-
@page == @options[:current_page] - 1
-
end
-
-
# the next page or not
-
1
def next?
-
@page == @options[:current_page] + 1
-
end
-
-
# within the left outer window or not
-
1
def left_outer?
-
@page <= @options[:left]
-
end
-
-
# within the right outer window or not
-
1
def right_outer?
-
@options[:total_pages] - @page < @options[:right]
-
end
-
-
# inside the inner window or not
-
1
def inside_window?
-
(@options[:current_page] - @page).abs <= @options[:window]
-
end
-
-
# The last rendered tag was "truncated" or not
-
1
def was_truncated?
-
@last.is_a? Gap
-
end
-
-
1
def to_i
-
number
-
end
-
-
1
def to_s
-
number.to_s
-
end
-
-
1
def +(other)
-
to_i + other.to_i
-
end
-
-
1
def -(other)
-
to_i - other.to_i
-
end
-
-
1
def <=>(other)
-
to_i <=> other.to_i
-
end
-
end
-
end
-
end
-
end
-
1
module Kaminari
-
1
module Helpers
-
# A tag stands for an HTML tag inside the paginator.
-
# Basically, a tag has its own partial template file, so every tag can be
-
# rendered into String using its partial template.
-
#
-
# The template file should be placed in your app/views/kaminari/ directory
-
# with underscored class name (besides the "Tag" class. Tag is an abstract
-
# class, so _tag parital is not needed).
-
# e.g.) PrevLink -> app/views/kaminari/_prev_link.html.erb
-
#
-
# When no matching template were found in your app, the engine's pre
-
# installed template will be used.
-
# e.g.) Paginator -> $GEM_HOME/kaminari-x.x.x/app/views/kaminari/_paginator.html.erb
-
1
class Tag
-
1
def initialize(template, options = {}) #:nodoc:
-
@template, @options = template, options.dup
-
@param_name = @options.delete(:param_name) || Kaminari.config.param_name
-
@theme = @options.delete(:theme)
-
@views_prefix = @options.delete(:views_prefix)
-
@params = @options[:params] ? template.params.merge(@options.delete :params) : template.params
-
end
-
-
1
def to_s(locals = {}) #:nodoc:
-
@template.render :partial => partial_path, :locals => @options.merge(locals), :formats => [:html]
-
end
-
-
1
def page_url_for(page)
-
@template.url_for @params.merge(@param_name => (page <= 1 ? nil : page), :only_path => true)
-
end
-
-
1
def partial_path
-
[
-
@views_prefix,
-
"kaminari",
-
@theme,
-
self.class.name.demodulize.underscore
-
].compact.join("/")
-
end
-
end
-
-
# Tag that contains a link
-
1
module Link
-
# target page number
-
1
def page
-
raise 'Override page with the actual page value to be a Page.'
-
end
-
# the link's href
-
1
def url
-
page_url_for page
-
end
-
1
def to_s(locals = {}) #:nodoc:
-
super locals.merge(:url => url)
-
end
-
end
-
-
# A page
-
1
class Page < Tag
-
1
include Link
-
# target page number
-
1
def page
-
@options[:page]
-
end
-
1
def to_s(locals = {}) #:nodoc:
-
super locals.merge(:page => page)
-
end
-
end
-
-
# Link with page number that appears at the leftmost
-
1
class FirstPage < Tag
-
1
include Link
-
1
def page #:nodoc:
-
1
-
end
-
end
-
-
# Link with page number that appears at the rightmost
-
1
class LastPage < Tag
-
1
include Link
-
1
def page #:nodoc:
-
@options[:total_pages]
-
end
-
end
-
-
# The "previous" page of the current page
-
1
class PrevPage < Tag
-
1
include Link
-
1
def page #:nodoc:
-
@options[:current_page] - 1
-
end
-
end
-
-
# The "next" page of the current page
-
1
class NextPage < Tag
-
1
include Link
-
1
def page #:nodoc:
-
@options[:current_page] + 1
-
end
-
end
-
-
# Non-link tag that stands for skipped pages...
-
1
class Gap < Tag
-
end
-
end
-
end
-
1
module Kaminari
-
1
class Hooks
-
1
def self.init
-
1
ActiveSupport.on_load(:active_record) do
-
1
require 'kaminari/models/active_record_extension'
-
1
::ActiveRecord::Base.send :include, Kaminari::ActiveRecordExtension
-
end
-
-
1
begin; require 'data_mapper'; rescue LoadError; end
-
1
if defined? ::DataMapper
-
require 'dm-aggregates'
-
require 'kaminari/models/data_mapper_extension'
-
::DataMapper::Collection.send :include, Kaminari::DataMapperExtension::Collection
-
::DataMapper::Model.append_extensions Kaminari::DataMapperExtension::Model
-
# ::DataMapper::Model.send :extend, Kaminari::DataMapperExtension::Model
-
end
-
-
1
begin; require 'mongoid'; rescue LoadError; end
-
1
if defined? ::Mongoid
-
require 'kaminari/models/mongoid_extension'
-
::Mongoid::Document.send :include, Kaminari::MongoidExtension::Document
-
end
-
-
1
ActiveSupport.on_load(:mongo_mapper) do
-
require 'kaminari/models/mongo_mapper_extension'
-
::MongoMapper::Document.send :include, Kaminari::MongoMapperExtension::Document
-
::Plucky::Query.send :include, Kaminari::PluckyCriteriaMethods
-
end
-
1
require 'kaminari/models/array_extension'
-
-
1
ActiveSupport.on_load(:action_view) do
-
1
::ActionView::Base.send :include, Kaminari::ActionViewExtension
-
end
-
end
-
end
-
end
-
1
require 'kaminari/models/active_record_model_extension'
-
-
1
module Kaminari
-
1
module ActiveRecordExtension
-
1
extend ActiveSupport::Concern
-
1
included do
-
# Future subclasses will pick up the model extension
-
1
class << self
-
1
def inherited_with_kaminari(kls) #:nodoc:
-
2
inherited_without_kaminari kls
-
2
kls.send(:include, Kaminari::ActiveRecordModelExtension) if kls.superclass == ::ActiveRecord::Base
-
end
-
1
alias_method_chain :inherited, :kaminari
-
end
-
-
# Existing subclasses pick up the model extension as well
-
1
self.descendants.each do |kls|
-
kls.send(:include, Kaminari::ActiveRecordModelExtension) if kls.superclass == ::ActiveRecord::Base
-
end
-
end
-
end
-
end
-
1
require 'kaminari/models/active_record_relation_methods'
-
-
1
module Kaminari
-
1
module ActiveRecordModelExtension
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
2
self.send(:include, Kaminari::ConfigurationMethods)
-
-
# Fetch the values at the specified page number
-
# Model.page(5)
-
2
eval <<-RUBY
-
def self.#{Kaminari.config.page_method_name}(num = nil)
-
limit(default_per_page).offset(default_per_page * ([num.to_i, 1].max - 1)).extending do
-
include Kaminari::ActiveRecordRelationMethods
-
include Kaminari::PageScopeMethods
-
end
-
end
-
RUBY
-
end
-
end
-
end
-
1
module Kaminari
-
1
module ActiveRecordRelationMethods
-
# a workaround for AR 3.0.x that returns 0 for #count when page > 1
-
# if +limit_value+ is specified, load all the records and count them
-
1
if ActiveRecord::VERSION::STRING < '3.1'
-
def count(column_name = nil, options = {}) #:nodoc:
-
limit_value && !options[:distinct] ? length : super(column_name, options)
-
end
-
end
-
-
1
def entry_name
-
model_name.human.downcase
-
end
-
-
1
def total_count(column_name = :all, options = {}) #:nodoc:
-
# #count overrides the #select which could include generated columns referenced in #order, so skip #order here, where it's irrelevant to the result anyway
-
@total_count ||= begin
-
c = except(:offset, :limit, :order)
-
-
# Remove includes only if they are irrelevant
-
c = c.except(:includes) unless references_eager_loaded_tables?
-
-
# Rails 4.1 removes the `options` argument from AR::Relation#count
-
args = [column_name]
-
args << options if ActiveRecord::VERSION::STRING < '4.1.0'
-
-
# .group returns an OrderdHash that responds to #count
-
c = c.count(*args)
-
if c.is_a?(Hash) || c.is_a?(ActiveSupport::OrderedHash)
-
c.count
-
else
-
c.respond_to?(:count) ? c.count(*args) : c
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module'
-
1
module Kaminari
-
# Kind of Array that can paginate
-
1
class PaginatableArray < Array
-
1
include Kaminari::ConfigurationMethods::ClassMethods
-
-
1
attr_internal_accessor :limit_value, :offset_value
-
-
# ==== Options
-
# * <tt>:limit</tt> - limit
-
# * <tt>:offset</tt> - offset
-
# * <tt>:total_count</tt> - total_count
-
1
def initialize(original_array = [], options = {})
-
@_original_array, @_limit_value, @_offset_value, @_total_count, @_padding = original_array, (options[:limit] || default_per_page).to_i, options[:offset].to_i, options[:total_count], options[:padding].to_i
-
-
if options[:limit] && options[:offset]
-
extend Kaminari::PageScopeMethods
-
end
-
-
if @_total_count
-
original_array = original_array.first(@_total_count)
-
end
-
-
super(original_array[@_offset_value, @_limit_value] || [])
-
end
-
-
1
def entry_name
-
"entry"
-
end
-
-
# items at the specified "page"
-
1
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{Kaminari.config.page_method_name}(num = 1)
-
offset(limit_value * ([num.to_i, 1].max - 1))
-
end
-
RUBY
-
-
# returns another chunk of the original array
-
1
def limit(num)
-
self.class.new @_original_array, :limit => num, :offset => @_offset_value, :total_count => @_total_count, :padding => @_padding
-
end
-
-
# total item numbers of the original array
-
1
def total_count
-
@_total_count || @_original_array.count
-
end
-
-
# returns another chunk of the original array
-
1
def offset(num)
-
self.class.new @_original_array, :limit => @_limit_value, :offset => num, :total_count => @_total_count, :padding => @_padding
-
end
-
end
-
-
# Wrap an Array object to make it paginatable
-
# ==== Options
-
# * <tt>:limit</tt> - limit
-
# * <tt>:offset</tt> - offset
-
# * <tt>:total_count</tt> - total_count
-
1
def self.paginate_array(array, options = {})
-
PaginatableArray.new array, options
-
end
-
end
-
1
module Kaminari
-
1
module ConfigurationMethods
-
1
extend ActiveSupport::Concern
-
1
module ClassMethods
-
# Overrides the default +per_page+ value per model
-
# class Article < ActiveRecord::Base
-
# paginates_per 10
-
# end
-
1
def paginates_per(val)
-
@_default_per_page = val
-
end
-
-
# This model's default +per_page+ value
-
# returns +default_per_page+ value unless explicitly overridden via <tt>paginates_per</tt>
-
1
def default_per_page
-
(defined?(@_default_per_page) && @_default_per_page) || Kaminari.config.default_per_page
-
end
-
-
# Overrides the max +per_page+ value per model
-
# class Article < ActiveRecord::Base
-
# max_paginates_per 100
-
# end
-
1
def max_paginates_per(val)
-
@_max_per_page = val
-
end
-
-
# This model's max +per_page+ value
-
# returns +max_per_page+ value unless explicitly overridden via <tt>max_paginates_per</tt>
-
1
def max_per_page
-
(defined?(@_max_per_page) && @_max_per_page) || Kaminari.config.max_per_page
-
end
-
-
# Overrides the max_pages value per model
-
# class Article < ActiveRecord::Base
-
# max_pages_per 100
-
# end
-
1
def max_pages_per(val)
-
@_max_pages = val
-
end
-
-
# This model's max_pages value
-
# returns max_pages value unless explicitly overridden via <tt>max_pages_per</tt>
-
1
def max_pages
-
(defined?(@_max_pages) && @_max_pages) || Kaminari.config.max_pages
-
end
-
end
-
end
-
end
-
1
module Kaminari
-
1
module PageScopeMethods
-
# Specify the <tt>per_page</tt> value for the preceding <tt>page</tt> scope
-
# Model.page(3).per(10)
-
1
def per(num)
-
if (n = num.to_i) <= 0
-
self
-
elsif max_per_page && max_per_page < n
-
limit(max_per_page).offset(offset_value / limit_value * max_per_page)
-
else
-
limit(n).offset(offset_value / limit_value * n)
-
end
-
end
-
-
1
def padding(num)
-
@_padding = num
-
offset(offset_value + num.to_i)
-
end
-
-
# Total number of pages
-
1
def total_pages
-
count_without_padding = total_count
-
count_without_padding -= @_padding if defined?(@_padding) && @_padding
-
count_without_padding = 0 if count_without_padding < 0
-
-
total_pages_count = (count_without_padding.to_f / limit_value).ceil
-
if max_pages.present? && max_pages < total_pages_count
-
max_pages
-
else
-
total_pages_count
-
end
-
end
-
#FIXME for compatibility. remove num_pages at some time in the future
-
1
alias num_pages total_pages
-
-
# Current page number
-
1
def current_page
-
offset_without_padding = offset_value
-
offset_without_padding -= @_padding if defined?(@_padding) && @_padding
-
offset_without_padding = 0 if offset_without_padding < 0
-
-
(offset_without_padding / limit_value) + 1
-
end
-
-
# Next page number in the collection
-
1
def next_page
-
current_page + 1 unless last_page?
-
end
-
-
# Previous page number in the collection
-
1
def prev_page
-
current_page - 1 unless first_page?
-
end
-
-
# First page of the collection?
-
1
def first_page?
-
current_page == 1
-
end
-
-
# Last page of the collection?
-
1
def last_page?
-
current_page >= total_pages
-
end
-
-
# Out of range of the collection?
-
1
def out_of_range?
-
current_page > total_pages
-
end
-
end
-
end
-
1
module Kaminari
-
1
class Railtie < ::Rails::Railtie #:nodoc:
-
1
initializer 'kaminari' do |_app|
-
1
Kaminari::Hooks.init
-
end
-
end
-
end
-
-
1
require 'less/defaults'
-
1
require 'less/errors'
-
1
require 'less/loader'
-
1
require 'less/parser'
-
1
require 'less/version'
-
1
require 'less/java_script'
-
-
1
module Less
-
1
extend Less::Defaults
-
-
# NOTE: keep the @loader as less-rails depends on
-
# it as it overrides some less/tree.js functions!
-
1
@loader = Less::Loader.new
-
1
@less = @loader.require('less/index')
-
-
1
def self.[](name)
-
@less[name]
-
end
-
-
# exposes less.Parser
-
1
def self.Parser
-
self['Parser']
-
end
-
-
# exposes less.tree e.g. for attaching custom functions
-
# Less.tree.functions['foo'] = lambda { |*args| 'bar' }
-
1
def self.tree
-
self['tree']
-
end
-
-
end
-
1
module Less
-
1
module Defaults
-
-
1
def defaults
-
@defaults ||= { :paths => [], :relativeUrls => true, :syncImport => true }
-
end
-
-
1
def paths
-
defaults[:paths]
-
end
-
-
end
-
end
-
1
module Less
-
-
1
class Error < ::StandardError
-
-
1
def initialize(cause, value = nil)
-
@value = value
-
message = nil
-
if @value # 2 args passed
-
message = @value['message']
-
else # allow passing only value as first arg cause :
-
if cause.respond_to?(:'[]') && message = cause['message']
-
@value = cause
-
end
-
end
-
-
if cause.is_a?(::Exception)
-
@cause = cause
-
super(message || cause.message)
-
else
-
super(message || cause)
-
end
-
end
-
-
1
def cause
-
@cause
-
end
-
-
1
def backtrace
-
@cause ? @cause.backtrace : super
-
end
-
-
# function LessError(e, env) { ... }
-
1
%w{ type filename stack extract }.each do |key|
-
4
class_eval "def #{key}; @value && @value['#{key}']; end"
-
end
-
1
%w{ index line column }.each do |key|
-
3
class_eval "def #{key}; @value && @value['#{key}'].to_i; end"
-
end
-
-
end
-
-
1
class ParseError < Error; end
-
-
end
-
1
module Less
-
1
module JavaScript
-
-
1
def self.default_context_wrapper
-
1
if defined?(JRUBY_VERSION)
-
require 'less/java_script/rhino_context'
-
RhinoContext
-
else
-
1
require 'less/java_script/v8_context'
-
1
V8Context
-
end
-
end
-
-
1
@@context_wrapper = nil
-
-
1
def self.context_wrapper
-
1
@@context_wrapper ||= default_context_wrapper
-
end
-
-
1
def self.context_wrapper=(klass)
-
@@context_wrapper = klass
-
end
-
-
# execute a block as JS
-
1
def self.exec(&block)
-
context_wrapper.instance.exec(&block)
-
end
-
-
1
def self.eval(source)
-
context_wrapper.instance.eval(source)
-
end
-
-
end
-
end
-
1
begin
-
1
require 'v8' unless defined?(V8)
-
rescue LoadError => e
-
warn "[WARNING] Please install gem 'therubyracer' to use Less."
-
raise e
-
end
-
-
1
require 'pathname'
-
-
1
module Less
-
1
module JavaScript
-
1
class V8Context
-
-
1
def self.instance
-
1
return new
-
end
-
-
1
def initialize(globals = nil)
-
1
lock do
-
1
@v8_context = V8::Context.new
-
1
globals.each { |key, val| @v8_context[key] = val } if globals
-
end
-
end
-
-
1
def unwrap
-
1
@v8_context
-
end
-
-
1
def exec(&block)
-
lock(&block)
-
end
-
-
1
def eval(source, options = nil) # passing options not supported
-
source = source.encode('UTF-8') if source.respond_to?(:encode)
-
-
lock do
-
@v8_context.eval("(#{source})")
-
end
-
end
-
-
1
def call(properties, *args)
-
args.last.is_a?(::Hash) ? args.pop : nil # extract_options!
-
-
lock do
-
@v8_context.eval(properties).call(*args)
-
end
-
end
-
-
1
def method_missing(symbol, *args)
-
if @v8_context.respond_to?(symbol)
-
@v8_context.send(symbol, *args)
-
else
-
super
-
end
-
end
-
-
1
private
-
-
1
def lock(&block)
-
1
do_lock(&block)
-
rescue V8::JSError => e
-
if e.in_javascript?
-
js_value = e.value.respond_to?(:'[]')
-
name = js_value && e.value["name"]
-
constructor = js_value && e.value['constructor']
-
if name == "SyntaxError" ||
-
( constructor && constructor.name == "LessError" )
-
raise Less::ParseError.new(e, js_value ? e.value : nil)
-
end
-
# NOTE: less/parser.js :
-
#
-
# error = new(LessError)({
-
# index: i,
-
# type: 'Parse',
-
# message: "missing closing `}`",
-
# filename: env.filename
-
# }, env);
-
#
-
# comes back as value: RuntimeError !
-
elsif e.value.to_s =~ /missing opening `\(`/
-
raise Less::ParseError.new(e.value.to_s)
-
end
-
raise Less::Error.new(e)
-
end
-
-
1
def do_lock
-
1
result, exception = nil, nil
-
1
V8::C::Locker() do
-
1
begin
-
1
result = yield
-
rescue Exception => e
-
exception = e
-
end
-
end
-
-
1
if exception
-
raise exception
-
else
-
1
result
-
end
-
end
-
-
end
-
end
-
end
-
1
require 'pathname'
-
1
require 'commonjs'
-
1
require 'net/http'
-
1
require 'uri'
-
1
require 'base64'
-
-
1
module Less
-
1
class Loader
-
-
1
attr_reader :environment
-
-
1
def initialize
-
1
context_wrapper = Less::JavaScript.context_wrapper.instance
-
1
@context = context_wrapper.unwrap
-
1
@context['process'] = Process.new
-
1
@context['console'] = Console.new
-
1
@context['Buffer'] = Buffer
-
1
path = Pathname(__FILE__).dirname.join('js', 'lib')
-
1
@environment = CommonJS::Environment.new(@context, :path => path.to_s)
-
1
@environment.native('path', Path)
-
1
@environment.native('util', Util)
-
1
@environment.native('fs', FS)
-
1
@environment.native('url', Url)
-
1
@environment.native('http', Http)
-
end
-
-
1
def require(module_id)
-
16
@environment.require(module_id)
-
end
-
-
# JS exports (required by less.js) :
-
-
1
class Process # :nodoc:
-
1
def exit(*args)
-
warn("JS process.exit(#{args.first}) called from: \n#{caller.join("\n")}")
-
end
-
end
-
-
1
class Console # :nodoc:
-
1
def log(*msgs)
-
puts msgs.join(', ')
-
end
-
-
1
def warn(*msgs)
-
$stderr.puts msgs.join(', ')
-
end
-
end
-
-
# stubbed JS modules (required by less.js) :
-
-
1
module Path # :nodoc:
-
1
def self.join(*components)
-
# node.js expands path on join
-
File.expand_path(File.join(*components))
-
end
-
-
1
def self.dirname(path)
-
File.dirname(path)
-
end
-
-
1
def self.basename(path)
-
File.basename(path)
-
end
-
-
1
def self.extname(path)
-
File.extname(path)
-
end
-
-
1
def self.resolve(path)
-
File.basename(path)
-
end
-
-
end
-
-
1
module Util # :nodoc:
-
-
1
def self.error(*errors)
-
raise errors.join(' ')
-
end
-
-
1
def self.puts(*args)
-
args.each { |arg| STDOUT.puts(arg) }
-
end
-
-
end
-
-
1
module FS # :nodoc:
-
-
1
def self.statSync(path)
-
File.stat(path)
-
end
-
-
1
def self.readFile(path, encoding, callback)
-
callback.call(nil, File.read(path))
-
end
-
-
1
def self.readFileSync(path, encoding = nil)
-
buf = Buffer.new(File.read(path), encoding)
-
encoding.nil? ? buf : buf.toString(encoding)
-
end
-
-
end
-
-
1
class Buffer # :nodoc:
-
-
1
attr_accessor :data
-
-
1
def initialize(data, encoding = nil)
-
unless data.is_a? String
-
data = data.to_ruby
-
end
-
@data = data
-
end
-
-
1
def length
-
@data.length
-
end
-
-
1
def toString(encoding = nil, begPos = 0, endPos = length)
-
data = @data[ begPos..endPos ]
-
if encoding == 'base64'
-
data = Base64.encode64(data)
-
data.delete!("\n"); data
-
else # encoding == 'binary'
-
data
-
end
-
end
-
end
-
-
1
module Url # :nodoc:
-
-
1
def self.resolve(*args)
-
URI.join(*args)
-
end
-
-
1
def self.parse(url_string)
-
u = URI.parse(url_string)
-
result = {}
-
result['protocol'] = u.scheme + ':' if u.scheme
-
result['hostname'] = u.host if u.host
-
result['pathname'] = u.path if u.path
-
result['port'] = u.port if u.port
-
result['query'] = u.query if u.query
-
result['search'] = '?' + u.query if u.query
-
result['hash'] = '#' + u.fragment if u.fragment
-
result
-
end
-
-
end
-
-
1
module Http # :nodoc:
-
-
1
def self.get(options, callback)
-
err = nil
-
begin
-
#less always sends options as an object, so no need to check for string
-
uri_hash = {}
-
uri_hash[:host] = options['hostname'] ? options['hostname'] : options['host']
-
path_components = options['path'] ? options['path'].split('?', 2) : [''] #have to do this because node expects path and query to be combined
-
if path_components.length > 1
-
uri_hash[:path] = path_components[0]
-
uri_hash[:query] = path_components[0]
-
else
-
uri_hash[:path] = path_components[0]
-
end
-
uri_hash[:port] = options['port'] ? options['port'] : Net::HTTP.http_default_port
-
uri_hash[:scheme] = uri_hash[:port] == Net::HTTP.https_default_port ? 'https' : 'http' #have to check this way because of node's http.get
-
case uri_hash[:scheme]
-
when 'http'
-
uri = URI::HTTP.build(uri_hash)
-
when 'https'
-
uri = URI::HTTPS.build(uri_hash)
-
else
-
raise Exception, 'Less import only supports http and https'
-
end
-
http = Net::HTTP.new uri.host, uri.port
-
if uri.scheme == 'https'
-
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
-
http.use_ssl = true
-
end
-
response = nil
-
http.start do |req|
-
response = req.get(uri.to_s)
-
end
-
callback.call ServerResponse.new(response.read_body, response.code.to_i)
-
rescue => e
-
err = e.message
-
ensure
-
ret = HttpGetResult.new(err)
-
end
-
ret
-
end
-
-
1
class HttpGetResult
-
1
attr_accessor :err
-
-
1
def initialize(err)
-
@err = err
-
end
-
-
1
def on(event, callback)
-
case event
-
when 'error'
-
callback.call(@err) if @err #only call when error exists
-
else
-
callback.call()
-
end
-
end
-
end
-
-
1
class ServerResponse
-
1
attr_accessor :statusCode
-
1
attr_accessor :data #faked because ServerResponse acutally implements WriteableStream
-
-
1
def initialize(data, status_code)
-
@data = data
-
@statusCode = status_code
-
end
-
-
1
def on(event, callback)
-
case event
-
when 'data'
-
callback.call(@data)
-
else
-
callback.call()
-
end
-
end
-
end
-
-
end
-
-
end
-
end
-
1
require 'pathname'
-
-
1
module Less
-
-
# Convert lesscss source into an abstract syntax Tree
-
1
class Parser
-
-
# Construct and configure new Less::Parser
-
#
-
# @param [Hash] options configuration options
-
# @option options [Array] :paths a list of directories to search when handling \@import statements
-
# @option options [String] :filename to associate with resulting parse trees (useful for generating errors)
-
# @option options [TrueClass, FalseClass] :compress
-
# @option options [TrueClass, FalseClass] :strictImports
-
# @option options [TrueClass, FalseClass] :relativeUrls
-
# @option options [String] :dumpLineNumbers one of 'mediaquery', 'comments', or 'all'
-
1
def initialize(options = {})
-
# LeSS supported _env_ options :
-
#
-
# - paths (unmodified) - paths to search for imports on
-
# - optimization - optimization level (for the chunker)
-
# - mime (browser only) mime type for sheet import
-
# - contents (browser only)
-
# - strictImports
-
# - dumpLineNumbers - whether to dump line numbers
-
# - compress - whether to compress
-
# - processImports - whether to process imports. if false then imports will not be imported
-
# - relativeUrls (true/false) whether to adjust URL's to be relative
-
# - errback (error callback function)
-
# - rootpath string
-
# - entryPath string
-
# - files (internal) - list of files that have been imported, used for import-once
-
# - currentFileInfo (internal) - information about the current file -
-
# for error reporting and importing and making urls relative etc :
-
# this.currentFileInfo = {
-
# filename: filename,
-
# relativeUrls: this.relativeUrls,
-
# rootpath: options.rootpath || "",
-
# currentDirectory: entryPath,
-
# entryPath: entryPath,
-
# rootFilename: filename
-
# };
-
#
-
env = {}
-
Less.defaults.merge(options).each do |key, val|
-
env[key.to_s] =
-
case val
-
when Symbol, Pathname then val.to_s
-
when Array
-
val.map!(&:to_s) if key.to_sym == :paths # might contain Pathname-s
-
val # keep the original passed Array
-
else val # true/false/String/Method
-
end
-
end
-
@parser = Less::JavaScript.exec { Less['Parser'].new(env) }
-
end
-
-
# Convert `less` source into a abstract syntaxt tree
-
# @param [String] less the source to parse
-
# @return [Less::Tree] the parsed tree
-
1
def parse(less)
-
error, tree = nil, nil
-
Less::JavaScript.exec do
-
@parser.parse(less, lambda { |*args| # (error, tree)
-
# v8 >= 0.10 passes this as first arg :
-
if args.size > 2
-
error, tree = args[-2], args[-1]
-
elsif args.last.respond_to?(:message) && args.last.message
-
# might get invoked as callback(error)
-
error = args.last
-
else
-
error, tree = *args
-
end
-
fail error.message unless error.nil?
-
})
-
end
-
Tree.new(tree) if tree
-
end
-
-
1
def imports
-
Less::JavaScript.exec { @parser.imports.files.map { |file, _| file } }
-
end
-
-
1
private
-
-
# Abstract LessCSS syntax tree Less. Mainly used to emit CSS
-
1
class Tree
-
-
# Create a tree from a native javascript object.
-
# @param [V8::Object] tree the native less.js tree
-
1
def initialize(tree)
-
@tree = tree
-
end
-
-
# Serialize this tree into CSS.
-
# By default this will be in pretty-printed form.
-
# @param [Hash] opts modifications to the output
-
# @option opts [Boolean] :compress minify output instead of pretty-printing
-
1
def to_css(options = {})
-
Less::JavaScript.exec { @tree.toCSS(options) }
-
end
-
-
end
-
-
end
-
-
end
-
1
module Less
-
1
VERSION = '2.5.1'
-
end
-
1
module Less
-
1
module Rails
-
end
-
end
-
-
1
require 'less'
-
1
require 'rails'
-
1
require 'tilt'
-
1
require 'sprockets'
-
1
begin
-
1
require 'sprockets/railtie'
-
rescue LoadError
-
require 'sprockets/rails/railtie'
-
end
-
-
1
require 'less/rails/version'
-
1
require 'less/rails/helpers'
-
1
require 'less/rails/template_handlers'
-
1
require 'less/rails/import_processor'
-
1
require 'less/rails/railtie'
-
1
module Less
-
-
1
def self.less
-
@less
-
end
-
-
1
def self.register_rails_helper(name, &block)
-
15
tree = @loader.require('less/tree')
-
15
tree.functions[name] = lambda do |*args|
-
# args: (this, node) v8 >= 0.10, otherwise (node)
-
raise ArgumentError, "missing node" if args.empty?
-
tree[:Anonymous].new block.call(tree, args.last)
-
end
-
end
-
-
1
module Rails
-
1
module Helpers
-
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
Less.register_rails_helper('asset-path') { |tree, cxt| asset_path unquote(cxt.toCSS()) }
-
1
Less.register_rails_helper('asset-url') { |tree, cxt| asset_url unquote(cxt.toCSS()) }
-
1
Less.register_rails_helper('image-path') { |tree, cxt| image_path unquote(cxt.toCSS()) }
-
1
Less.register_rails_helper('image-url') { |tree, cxt| image_url unquote(cxt.toCSS()) }
-
1
Less.register_rails_helper('video-path') { |tree, cxt| video_path unquote(cxt.toCSS()) }
-
1
Less.register_rails_helper('video-url') { |tree, cxt| video_url unquote(cxt.toCSS()) }
-
1
Less.register_rails_helper('audio-path') { |tree, cxt| audio_path unquote(cxt.toCSS()) }
-
1
Less.register_rails_helper('audio-url') { |tree, cxt| audio_url unquote(cxt.toCSS()) }
-
1
Less.register_rails_helper('javascript-path') { |tree, cxt| javascript_path unquote(cxt.toCSS()) }
-
1
Less.register_rails_helper('javascript-url') { |tree, cxt| javascript_url unquote(cxt.toCSS()) }
-
1
Less.register_rails_helper('stylesheet-path') { |tree, cxt| stylesheet_path unquote(cxt.toCSS()) }
-
1
Less.register_rails_helper('stylesheet-url') { |tree, cxt| stylesheet_url unquote(cxt.toCSS()) }
-
1
Less.register_rails_helper('font-path') { |tree, cxt| font_path unquote(cxt.toCSS()) }
-
1
Less.register_rails_helper('font-url') { |tree, cxt| font_url unquote(cxt.toCSS()) }
-
1
Less.register_rails_helper('asset-data-url') { |tree, cxt| asset_data_url unquote(cxt.toCSS()) }
-
end
-
-
1
module ClassMethods
-
-
1
def asset_data_url(path)
-
"url(#{scope.asset_data_uri(path)})"
-
end
-
-
1
def asset_path(asset)
-
public_path(asset).inspect
-
end
-
-
1
def asset_url(asset)
-
"url(#{public_path(asset)})"
-
end
-
-
1
def image_path(img)
-
scope.image_path(img).inspect
-
end
-
-
1
def image_url(img)
-
"url(#{scope.image_path(img)})"
-
end
-
-
1
def video_path(video)
-
scope.video_path(video).inspect
-
end
-
-
1
def video_url(video)
-
"url(#{scope.video_path(video)})"
-
end
-
-
1
def audio_path(audio)
-
scope.audio_path(audio).inspect
-
end
-
-
1
def audio_url(audio)
-
"url(#{scope.audio_path(audio)})"
-
end
-
-
1
def javascript_path(javascript)
-
scope.javascript_path(javascript).inspect
-
end
-
-
1
def javascript_url(javascript)
-
"url(#{scope.javascript_path(javascript)})"
-
end
-
-
1
def stylesheet_path(stylesheet)
-
scope.stylesheet_path(stylesheet).inspect
-
end
-
-
1
def stylesheet_url(stylesheet)
-
"url(#{scope.stylesheet_path(stylesheet)})"
-
end
-
-
1
def font_path(font)
-
if scope.respond_to?(:font_path)
-
scope.font_path(font).inspect
-
else
-
asset_path(font)
-
end
-
end
-
-
1
def font_url(font)
-
if scope.respond_to?(:font_path)
-
"url(#{scope.font_path(font)})"
-
else
-
asset_url(font)
-
end
-
end
-
-
1
private
-
-
1
def scope
-
Less.Parser['scope']
-
end
-
-
1
def public_path(asset)
-
if scope.respond_to?(:asset_paths)
-
scope.asset_paths.compute_public_path asset, ::Rails.application.config.assets.prefix
-
else
-
scope.path_to_asset(asset)
-
end
-
end
-
-
1
def context_asset_data_uri(path)
-
-
end
-
-
1
def unquote(str)
-
s = str.to_s.strip
-
s =~ /^['"](.*?)['"]$/ ? $1 : s
-
end
-
-
end
-
-
end
-
end
-
end
-
-
1
module Less
-
1
module Rails
-
1
class ImportProcessor < Tilt::Template
-
-
1
IMPORT_SCANNER = /@import\s*['"]([^'"]+)['"]\s*;/.freeze
-
1
PATHNAME_FINDER = Proc.new { |scope, path|
-
begin
-
scope.resolve(path)
-
rescue Sprockets::FileNotFound
-
nil
-
end
-
}
-
-
1
def prepare
-
end
-
-
1
def evaluate(scope, locals, &block)
-
depend_on scope, data
-
data
-
end
-
-
1
def depend_on(scope, data, base=File.dirname(scope.logical_path))
-
import_paths = data.scan(IMPORT_SCANNER).flatten.compact.uniq
-
import_paths.each do |path|
-
pathname = PATHNAME_FINDER.call(scope,path) || PATHNAME_FINDER.call(scope, File.join(base, path))
-
scope.depend_on(pathname) if pathname && pathname.to_s.ends_with?('.less')
-
depend_on scope, File.read(pathname), File.dirname(path) if pathname
-
end
-
data
-
end
-
-
end
-
end
-
end
-
1
module Less
-
1
module Rails
-
1
class Railtie < ::Rails::Railtie
-
-
1
module LessContext
-
1
attr_accessor :less_config
-
end
-
-
1
config.less = ActiveSupport::OrderedOptions.new
-
1
config.less.paths = []
-
1
config.less.compress = false
-
1
config.app_generators.stylesheet_engine :less
-
-
1
config.before_initialize do |app|
-
1
require 'less'
-
1
require 'less-rails'
-
1
Sprockets::Engines #force autoloading
-
1
Sprockets.register_engine '.less', LessTemplate
-
end
-
-
1
initializer 'less-rails.before.load_config_initializers', :before => :load_config_initializers, :group => :all do |app|
-
1
(Sprockets.respond_to?('register_preprocessor') ? Sprockets : app.assets).register_preprocessor 'text/css', ImportProcessor
-
1
app.assets.context_class.extend(LessContext)
-
1
app.assets.context_class.less_config = app.config.less
-
end
-
-
1
initializer 'less-rails.after.append_assets_path', :after => :append_assets_path, :group => :all do |app|
-
29
assets_stylesheet_paths = app.config.assets.paths.select { |p| p && p.to_s.ends_with?('stylesheets') }
-
1
app.config.less.paths.unshift(*assets_stylesheet_paths)
-
end
-
-
1
initializer 'less-rails.setup_compression', :group => :all do |app|
-
1
config.less.compress = app.config.assets.compress
-
end
-
-
end
-
end
-
end
-
-
1
module Less
-
1
module Rails
-
1
class LessTemplate < Tilt::LessTemplate
-
-
1
self.default_mime_type = 'text/css'
-
-
1
include Helpers
-
-
1
TO_CSS_KEYS = [:compress, :optimization, :silent, :color]
-
-
1
def prepare
-
end
-
-
1
def evaluate(scope, locals, &block)
-
@output ||= begin
-
Less.Parser['scope'] = scope
-
parser = ::Less::Parser.new config_to_less_parser_options(scope)
-
engine = parser.parse(data)
-
engine.to_css config_to_css_options(scope)
-
end
-
end
-
-
1
protected
-
-
1
def config_to_less_parser_options(scope)
-
paths = config_paths(scope) + scope.environment.paths
-
local_path = scope.pathname.dirname
-
paths += [local_path] unless paths.include? local_path
-
{:filename => eval_file, :line => line, :paths => paths, :dumpLineNumbers => config_from_rails(scope).line_numbers}
-
end
-
-
1
def config_to_css_options(scope)
-
Hash[config_from_rails(scope).each.to_a].slice *TO_CSS_KEYS
-
end
-
-
1
def config_paths(scope)
-
config_from_rails(scope)[:paths]
-
end
-
-
1
def config_from_rails(scope)
-
scope.environment.context_class.less_config
-
end
-
-
end
-
end
-
end
-
1
module Less
-
1
module Rails
-
1
VERSION = "2.5.0"
-
end
-
end
-
# encoding: utf-8
-
# This file loads up the parsers for mail to use. It also will attempt to compile parsers
-
# if they don't exist.
-
#
-
# It also only uses the compiler if we are running the SPEC suite
-
1
module Mail # :doc:
-
1
require 'treetop/runtime'
-
-
1
def self.compile_parser(parser)
-
require 'treetop/compiler'
-
Treetop.load(File.join(File.dirname(__FILE__)) + "/mail/parsers/#{parser}")
-
end
-
-
1
parsers = %w[ rfc2822_obsolete rfc2822 address_lists phrase_lists
-
date_time received message_ids envelope_from rfc2045
-
mime_version content_type content_disposition
-
content_transfer_encoding content_location ]
-
-
1
if defined?(MAIL_SPEC_SUITE_RUNNING)
-
parsers.each do |parser|
-
compile_parser(parser)
-
end
-
-
else
-
1
parsers.each do |parser|
-
14
begin
-
14
require "mail/parsers/#{parser}"
-
rescue LoadError
-
compile_parser(parser)
-
end
-
end
-
-
end
-
-
end
-
# encoding: utf-8
-
1
module Mail # :doc:
-
-
1
require 'date'
-
1
require 'shellwords'
-
-
1
require 'uri'
-
1
require 'net/smtp'
-
1
require 'mime/types'
-
-
1
if RUBY_VERSION <= '1.8.6'
-
begin
-
require 'tlsmail'
-
rescue LoadError
-
raise "You need to install tlsmail if you are using ruby <= 1.8.6"
-
end
-
end
-
-
1
if RUBY_VERSION >= "1.9.0"
-
1
require 'mail/version_specific/ruby_1_9'
-
1
RubyVer = Ruby19
-
else
-
require 'mail/version_specific/ruby_1_8'
-
RubyVer = Ruby18
-
end
-
-
1
require 'mail/version'
-
-
1
require 'mail/core_extensions/nil'
-
1
require 'mail/core_extensions/object'
-
1
require 'mail/core_extensions/string'
-
1
require 'mail/core_extensions/smtp' if RUBY_VERSION < '1.9.3'
-
1
require 'mail/indifferent_hash'
-
-
# Only load our multibyte extensions if AS is not already loaded
-
1
if defined?(ActiveSupport)
-
1
require 'active_support/inflector'
-
else
-
require 'mail/core_extensions/string/access'
-
require 'mail/core_extensions/string/multibyte'
-
require 'mail/multibyte'
-
end
-
-
1
require 'mail/patterns'
-
1
require 'mail/utilities'
-
1
require 'mail/configuration'
-
-
1
@@autoloads = {}
-
1
def self.register_autoload(name, path)
-
53
@@autoloads[name] = path
-
53
autoload(name, path)
-
end
-
-
# This runs through the autoload list and explictly requires them for you.
-
# Useful when running mail in a threaded process.
-
#
-
# Usage:
-
#
-
# require 'mail'
-
# Mail.eager_autoload!
-
1
def self.eager_autoload!
-
@@autoloads.each { |_,path| require(path) }
-
end
-
-
# Autoload mail send and receive classes.
-
1
require 'mail/network'
-
-
1
require 'mail/message'
-
1
require 'mail/part'
-
1
require 'mail/header'
-
1
require 'mail/parts_list'
-
1
require 'mail/attachments_list'
-
1
require 'mail/body'
-
1
require 'mail/field'
-
1
require 'mail/field_list'
-
-
1
require 'mail/envelope'
-
-
1
require 'load_parsers'
-
-
# Autoload header field elements and transfer encodings.
-
1
require 'mail/elements'
-
1
require 'mail/encodings'
-
1
require 'mail/encodings/base64'
-
1
require 'mail/encodings/quoted_printable'
-
-
1
require 'mail/matchers/has_sent_mail'
-
-
# Finally... require all the Mail.methods
-
1
require 'mail/mail'
-
end
-
# encoding: utf-8
-
1
module Mail
-
-
# = Body
-
#
-
# The body is where the text of the email is stored. Mail treats the body
-
# as a single object. The body itself has no information about boundaries
-
# used in the MIME standard, it just looks at its content as either a single
-
# block of text, or (if it is a multipart message) as an array of blocks of text.
-
#
-
# A body has to be told to split itself up into a multipart message by calling
-
# #split with the correct boundary. This is because the body object has no way
-
# of knowing what the correct boundary is for itself (there could be many
-
# boundaries in a body in the case of a nested MIME text).
-
#
-
# Once split is called, Mail::Body will slice itself up on this boundary,
-
# assigning anything that appears before the first part to the preamble, and
-
# anything that appears after the closing boundary to the epilogue, then
-
# each part gets initialized into a Mail::Part object.
-
#
-
# The boundary that is used to split up the Body is also stored in the Body
-
# object for use on encoding itself back out to a string. You can
-
# overwrite this if it needs to be changed.
-
#
-
# On encoding, the body will return the preamble, then each part joined by
-
# the boundary, followed by a closing boundary string and then the epilogue.
-
1
class Body
-
-
1
def initialize(string = '')
-
@boundary = nil
-
@preamble = nil
-
@epilogue = nil
-
@charset = nil
-
@part_sort_order = [ "text/plain", "text/enriched", "text/html" ]
-
@parts = Mail::PartsList.new
-
if string.blank?
-
@raw_source = ''
-
else
-
# Do join first incase we have been given an Array in Ruby 1.9
-
if string.respond_to?(:join)
-
@raw_source = string.join('')
-
elsif string.respond_to?(:to_s)
-
@raw_source = string.to_s
-
else
-
raise "You can only assign a string or an object that responds_to? :join or :to_s to a body."
-
end
-
end
-
@encoding = (only_us_ascii? ? '7bit' : '8bit')
-
set_charset
-
end
-
-
# Matches this body with another body. Also matches the decoded value of this
-
# body with a string.
-
#
-
# Examples:
-
#
-
# body = Mail::Body.new('The body')
-
# body == body #=> true
-
#
-
# body = Mail::Body.new('The body')
-
# body == 'The body' #=> true
-
#
-
# body = Mail::Body.new("VGhlIGJvZHk=\n")
-
# body.encoding = 'base64'
-
# body == "The body" #=> true
-
1
def ==(other)
-
if other.class == String
-
self.decoded == other
-
else
-
super
-
end
-
end
-
-
# Accepts a string and performs a regular expression against the decoded text
-
#
-
# Examples:
-
#
-
# body = Mail::Body.new('The body')
-
# body =~ /The/ #=> 0
-
#
-
# body = Mail::Body.new("VGhlIGJvZHk=\n")
-
# body.encoding = 'base64'
-
# body =~ /The/ #=> 0
-
1
def =~(regexp)
-
self.decoded =~ regexp
-
end
-
-
# Accepts a string and performs a regular expression against the decoded text
-
#
-
# Examples:
-
#
-
# body = Mail::Body.new('The body')
-
# body.match(/The/) #=> #<MatchData "The">
-
#
-
# body = Mail::Body.new("VGhlIGJvZHk=\n")
-
# body.encoding = 'base64'
-
# body.match(/The/) #=> #<MatchData "The">
-
1
def match(regexp)
-
self.decoded.match(regexp)
-
end
-
-
# Accepts anything that responds to #to_s and checks if it's a substring of the decoded text
-
#
-
# Examples:
-
#
-
# body = Mail::Body.new('The body')
-
# body.include?('The') #=> true
-
#
-
# body = Mail::Body.new("VGhlIGJvZHk=\n")
-
# body.encoding = 'base64'
-
# body.include?('The') #=> true
-
1
def include?(other)
-
self.decoded.include?(other.to_s)
-
end
-
-
# Allows you to set the sort order of the parts, overriding the default sort order.
-
# Defaults to 'text/plain', then 'text/enriched', then 'text/html' with any other content
-
# type coming after.
-
1
def set_sort_order(order)
-
@part_sort_order = order
-
end
-
-
# Allows you to sort the parts according to the default sort order, or the sort order you
-
# set with :set_sort_order.
-
#
-
# sort_parts! is also called from :encode, so there is no need for you to call this explicitly
-
1
def sort_parts!
-
@parts.each do |p|
-
p.body.set_sort_order(@part_sort_order)
-
@parts.sort!(@part_sort_order)
-
p.body.sort_parts!
-
end
-
end
-
-
# Returns the raw source that the body was initialized with, without
-
# any tampering
-
1
def raw_source
-
@raw_source
-
end
-
-
1
def get_best_encoding(target)
-
target_encoding = Mail::Encodings.get_encoding(target)
-
target_encoding.get_best_compatible(encoding, raw_source)
-
end
-
-
# Returns a body encoded using transfer_encoding. Multipart always uses an
-
# identiy encoding (i.e. no encoding).
-
# Calling this directly is not a good idea, but supported for compatibility
-
# TODO: Validate that preamble and epilogue are valid for requested encoding
-
1
def encoded(transfer_encoding = '8bit')
-
if multipart?
-
self.sort_parts!
-
encoded_parts = parts.map { |p| p.encoded }
-
([preamble] + encoded_parts).join(crlf_boundary) + end_boundary + epilogue.to_s
-
else
-
be = get_best_encoding(transfer_encoding)
-
dec = Mail::Encodings::get_encoding(encoding)
-
enc = Mail::Encodings::get_encoding(be)
-
if transfer_encoding == encoding and dec.nil?
-
# Cannot decode, so skip normalization
-
raw_source
-
else
-
# Decode then encode to normalize and allow transforming
-
# from base64 to Q-P and vice versa
-
decoded = dec.decode(raw_source)
-
if defined?(Encoding) && charset && charset != "US-ASCII"
-
decoded.encode!(charset)
-
decoded.force_encoding('BINARY') unless Encoding.find(charset).ascii_compatible?
-
end
-
enc.encode(decoded)
-
end
-
end
-
end
-
-
1
def decoded
-
if !Encodings.defined?(encoding)
-
raise UnknownEncodingType, "Don't know how to decode #{encoding}, please call #encoded and decode it yourself."
-
else
-
Encodings.get_encoding(encoding).decode(raw_source)
-
end
-
end
-
-
1
def to_s
-
decoded
-
end
-
-
1
def charset
-
@charset
-
end
-
-
1
def charset=( val )
-
@charset = val
-
end
-
-
1
def encoding(val = nil)
-
if val
-
self.encoding = val
-
else
-
@encoding
-
end
-
end
-
-
1
def encoding=( val )
-
@encoding = if val == "text" || val.blank?
-
(only_us_ascii? ? '7bit' : '8bit')
-
else
-
val
-
end
-
end
-
-
# Returns the preamble (any text that is before the first MIME boundary)
-
1
def preamble
-
@preamble
-
end
-
-
# Sets the preamble to a string (adds text before the first MIME boundary)
-
1
def preamble=( val )
-
@preamble = val
-
end
-
-
# Returns the epilogue (any text that is after the last MIME boundary)
-
1
def epilogue
-
@epilogue
-
end
-
-
# Sets the epilogue to a string (adds text after the last MIME boundary)
-
1
def epilogue=( val )
-
@epilogue = val
-
end
-
-
# Returns true if there are parts defined in the body
-
1
def multipart?
-
true unless parts.empty?
-
end
-
-
# Returns the boundary used by the body
-
1
def boundary
-
@boundary
-
end
-
-
# Allows you to change the boundary of this Body object
-
1
def boundary=( val )
-
@boundary = val
-
end
-
-
1
def parts
-
@parts
-
end
-
-
1
def <<( val )
-
if @parts
-
@parts << val
-
else
-
@parts = Mail::PartsList.new[val]
-
end
-
end
-
-
1
def split!(boundary)
-
self.boundary = boundary
-
parts = raw_source.split(/(?:\A|\r\n)--#{Regexp.escape(boundary)}(?=(?:--)?\s*$)/)
-
# Make the preamble equal to the preamble (if any)
-
self.preamble = parts[0].to_s.strip
-
# Make the epilogue equal to the epilogue (if any)
-
self.epilogue = parts[-1].to_s.sub('--', '').strip
-
parts[1...-1].to_a.each { |part| @parts << Mail::Part.new(part) }
-
self
-
end
-
-
1
def only_us_ascii?
-
!(raw_source =~ /[^\x01-\x7f]/)
-
end
-
-
1
def empty?
-
!!raw_source.to_s.empty?
-
end
-
-
1
private
-
-
1
def crlf_boundary
-
"\r\n--#{boundary}\r\n"
-
end
-
-
1
def end_boundary
-
"\r\n--#{boundary}--\r\n"
-
end
-
-
1
def set_charset
-
only_us_ascii? ? @charset = 'US-ASCII' : @charset = nil
-
end
-
end
-
end
-
1
module Mail
-
1
module CheckDeliveryParams
-
1
def check_delivery_params(mail)
-
if mail.smtp_envelope_from.blank?
-
raise ArgumentError.new('An SMTP From address is required to send a message. Set the message smtp_envelope_from, return_path, sender, or from address.')
-
end
-
-
if mail.smtp_envelope_to.blank?
-
raise ArgumentError.new('An SMTP To address is required to send a message. Set the message smtp_envelope_to, to, cc, or bcc address.')
-
end
-
-
message = mail.encoded if mail.respond_to?(:encoded)
-
if message.blank?
-
raise ArgumentError.new('An encoded message is required to send an email')
-
end
-
-
[mail.smtp_envelope_from, mail.smtp_envelope_to, message]
-
end
-
end
-
end
-
# encoding: utf-8
-
#
-
# Thanks to Nicolas Fouché for this wrapper
-
#
-
1
require 'singleton'
-
-
1
module Mail
-
-
# The Configuration class is a Singleton used to hold the default
-
# configuration for all Mail objects.
-
#
-
# Each new mail object gets a copy of these values at initialization
-
# which can be overwritten on a per mail object basis.
-
1
class Configuration
-
1
include Singleton
-
-
1
def initialize
-
@delivery_method = nil
-
@retriever_method = nil
-
super
-
end
-
-
1
def delivery_method(method = nil, settings = {})
-
return @delivery_method if @delivery_method && method.nil?
-
@delivery_method = lookup_delivery_method(method).new(settings)
-
end
-
-
1
def lookup_delivery_method(method)
-
case method.is_a?(String) ? method.to_sym : method
-
when nil
-
Mail::SMTP
-
when :smtp
-
Mail::SMTP
-
when :sendmail
-
Mail::Sendmail
-
when :exim
-
Mail::Exim
-
when :file
-
Mail::FileDelivery
-
when :smtp_connection
-
Mail::SMTPConnection
-
when :test
-
Mail::TestMailer
-
else
-
method
-
end
-
end
-
-
1
def retriever_method(method = nil, settings = {})
-
return @retriever_method if @retriever_method && method.nil?
-
@retriever_method = lookup_retriever_method(method).new(settings)
-
end
-
-
1
def lookup_retriever_method(method)
-
case method
-
when nil
-
Mail::POP3
-
when :pop3
-
Mail::POP3
-
when :imap
-
Mail::IMAP
-
when :test
-
Mail::TestRetriever
-
else
-
method
-
end
-
end
-
-
1
def param_encode_language(value = nil)
-
value ? @encode_language = value : @encode_language ||= 'en'
-
end
-
-
end
-
-
end
-
# encoding: utf-8
-
-
# This is not loaded if ActiveSupport is already loaded
-
-
1
class NilClass #:nodoc:
-
1
unless nil.respond_to? :blank?
-
def blank?
-
true
-
end
-
end
-
-
1
def to_crlf
-
''
-
end
-
-
1
def to_lf
-
''
-
end
-
end
-
# encoding: utf-8
-
-
1
unless Object.method_defined? :blank?
-
class Object
-
def blank?
-
if respond_to?(:empty?)
-
empty?
-
else
-
!self
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
1
class String #:nodoc:
-
1
def to_crlf
-
to_str.gsub(/\n|\r\n|\r/) { "\r\n" }
-
end
-
-
1
def to_lf
-
to_str.gsub(/\n|\r\n|\r/) { "\n" }
-
end
-
-
166
unless String.instance_methods(false).map {|m| m.to_sym}.include?(:blank?)
-
def blank?
-
self !~ /\S/
-
end
-
end
-
-
1
unless method_defined?(:ascii_only?)
-
# Backport from Ruby 1.9 checks for non-us-ascii characters.
-
def ascii_only?
-
self !~ MATCH_NON_US_ASCII
-
end
-
-
MATCH_NON_US_ASCII = /[^\x00-\x7f]/
-
end
-
-
1
def not_ascii_only?
-
!ascii_only?
-
end
-
-
1
unless method_defined?(:bytesize)
-
alias :bytesize :length
-
end
-
end
-
1
module Mail
-
1
register_autoload :Address, 'mail/elements/address'
-
1
register_autoload :AddressList, 'mail/elements/address_list'
-
1
register_autoload :ContentDispositionElement, 'mail/elements/content_disposition_element'
-
1
register_autoload :ContentLocationElement, 'mail/elements/content_location_element'
-
1
register_autoload :ContentTransferEncodingElement, 'mail/elements/content_transfer_encoding_element'
-
1
register_autoload :ContentTypeElement, 'mail/elements/content_type_element'
-
1
register_autoload :DateTimeElement, 'mail/elements/date_time_element'
-
1
register_autoload :EnvelopeFromElement, 'mail/elements/envelope_from_element'
-
1
register_autoload :MessageIdsElement, 'mail/elements/message_ids_element'
-
1
register_autoload :MimeVersionElement, 'mail/elements/mime_version_element'
-
1
register_autoload :PhraseList, 'mail/elements/phrase_list'
-
1
register_autoload :ReceivedElement, 'mail/elements/received_element'
-
end
-
# encoding: utf-8
-
-
1
module Mail
-
# Raised when attempting to decode an unknown encoding type
-
1
class UnknownEncodingType < StandardError #:nodoc:
-
end
-
-
1
module Encodings
-
-
1
include Mail::Patterns
-
1
extend Mail::Utilities
-
-
1
@transfer_encodings = {}
-
-
# Register transfer encoding
-
#
-
# Example
-
#
-
# Encodings.register "base64", Mail::Encodings::Base64
-
1
def Encodings.register(name, cls)
-
5
@transfer_encodings[get_name(name)] = cls
-
end
-
-
# Is the encoding we want defined?
-
#
-
# Example:
-
#
-
# Encodings.defined?(:base64) #=> true
-
1
def Encodings.defined?( str )
-
@transfer_encodings.include? get_name(str)
-
end
-
-
# Gets a defined encoding type, QuotedPrintable or Base64 for now.
-
#
-
# Each encoding needs to be defined as a Mail::Encodings::ClassName for
-
# this to work, allows us to add other encodings in the future.
-
#
-
# Example:
-
#
-
# Encodings.get_encoding(:base64) #=> Mail::Encodings::Base64
-
1
def Encodings.get_encoding( str )
-
@transfer_encodings[get_name(str)]
-
end
-
-
1
def Encodings.get_all
-
@transfer_encodings.values
-
end
-
-
1
def Encodings.get_name(enc)
-
5
enc = enc.to_s.gsub("-", "_").downcase
-
end
-
-
# Encodes a parameter value using URI Escaping, note the language field 'en' can
-
# be set using Mail::Configuration, like so:
-
#
-
# Mail.defaults do
-
# param_encode_language 'jp'
-
# end
-
#
-
# The character set used for encoding will either be the value of $KCODE for
-
# Ruby < 1.9 or the encoding on the string passed in.
-
#
-
# Example:
-
#
-
# Mail::Encodings.param_encode("This is fun") #=> "us-ascii'en'This%20is%20fun"
-
1
def Encodings.param_encode(str)
-
case
-
when str.ascii_only? && str =~ TOKEN_UNSAFE
-
%Q{"#{str}"}
-
when str.ascii_only?
-
str
-
else
-
RubyVer.param_encode(str)
-
end
-
end
-
-
# Decodes a parameter value using URI Escaping.
-
#
-
# Example:
-
#
-
# Mail::Encodings.param_decode("This%20is%20fun", 'us-ascii') #=> "This is fun"
-
#
-
# str = Mail::Encodings.param_decode("This%20is%20fun", 'iso-8559-1')
-
# str.encoding #=> 'ISO-8859-1' ## Only on Ruby 1.9
-
# str #=> "This is fun"
-
1
def Encodings.param_decode(str, encoding)
-
RubyVer.param_decode(str, encoding)
-
end
-
-
# Decodes or encodes a string as needed for either Base64 or QP encoding types in
-
# the =?<encoding>?[QB]?<string>?=" format.
-
#
-
# The output type needs to be :decode to decode the input string or :encode to
-
# encode the input string. The character set used for encoding will either be
-
# the value of $KCODE for Ruby < 1.9 or the encoding on the string passed in.
-
#
-
# On encoding, will only send out Base64 encoded strings.
-
1
def Encodings.decode_encode(str, output_type)
-
case
-
when output_type == :decode
-
Encodings.value_decode(str)
-
else
-
if str.ascii_only?
-
str
-
else
-
Encodings.b_value_encode(str, find_encoding(str))
-
end
-
end
-
end
-
-
# Decodes a given string as Base64 or Quoted Printable, depending on what
-
# type it is.
-
#
-
# String has to be of the format =?<encoding>?[QB]?<string>?=
-
1
def Encodings.value_decode(str)
-
# Optimization: If there's no encoded-words in the string, just return it
-
return str unless str =~ /\=\?[^?]+\?[QB]\?[^?]+?\?\=/xmi
-
-
lines = collapse_adjacent_encodings(str)
-
-
# Split on white-space boundaries with capture, so we capture the white-space as well
-
lines.map do |line|
-
line.split(/([ \t])/).map do |text|
-
if text.index('=?').nil?
-
text
-
else
-
# Search for occurences of quoted strings or plain strings
-
text.scan(/( # Group around entire regex to include it in matches
-
\=\?[^?]+\?([QB])\?[^?]+?\?\= # Quoted String with subgroup for encoding method
-
| # or
-
.+?(?=\=\?|$) # Plain String
-
)/xmi).map do |matches|
-
string, method = *matches
-
if method == 'b' || method == 'B'
-
b_value_decode(string)
-
elsif method == 'q' || method == 'Q'
-
q_value_decode(string)
-
else
-
string
-
end
-
end
-
end
-
end
-
end.flatten.join("")
-
end
-
-
# Takes an encoded string of the format =?<encoding>?[QB]?<string>?=
-
1
def Encodings.unquote_and_convert_to(str, to_encoding)
-
output = value_decode( str ).to_s # output is already converted to UTF-8
-
-
if 'utf8' == to_encoding.to_s.downcase.gsub("-", "")
-
output
-
elsif to_encoding
-
begin
-
if RUBY_VERSION >= '1.9'
-
output.encode(to_encoding)
-
else
-
require 'iconv'
-
Iconv.iconv(to_encoding, 'UTF-8', output).first
-
end
-
rescue Iconv::IllegalSequence, Iconv::InvalidEncoding, Errno::EINVAL
-
# the 'from' parameter specifies a charset other than what the text
-
# actually is...not much we can do in this case but just return the
-
# unconverted text.
-
#
-
# Ditto if either parameter represents an unknown charset, like
-
# X-UNKNOWN.
-
output
-
end
-
else
-
output
-
end
-
end
-
-
1
def Encodings.address_encode(address, charset = 'utf-8')
-
if address.is_a?(Array)
-
# loop back through for each element
-
address.compact.map { |a| Encodings.address_encode(a, charset) }.join(", ")
-
else
-
# find any word boundary that is not ascii and encode it
-
encode_non_usascii(address, charset) if address
-
end
-
end
-
-
1
def Encodings.encode_non_usascii(address, charset)
-
return address if address.ascii_only? or charset.nil?
-
us_ascii = %Q{\x00-\x7f}
-
# Encode any non usascii strings embedded inside of quotes
-
address = address.gsub(/(".*?[^#{us_ascii}].*?")/) { |s| Encodings.b_value_encode(unquote(s), charset) }
-
# Then loop through all remaining items and encode as needed
-
tokens = address.split(/\s/)
-
map_with_index(tokens) do |word, i|
-
if word.ascii_only?
-
word
-
else
-
previous_non_ascii = i>0 && tokens[i-1] && !tokens[i-1].ascii_only?
-
if previous_non_ascii #why are we adding an extra space here?
-
word = " #{word}"
-
end
-
Encodings.b_value_encode(word, charset)
-
end
-
end.join(' ')
-
end
-
-
# Encode a string with Base64 Encoding and returns it ready to be inserted
-
# as a value for a field, that is, in the =?<charset>?B?<string>?= format
-
#
-
# Example:
-
#
-
# Encodings.b_value_encode('This is あ string', 'UTF-8')
-
# #=> "=?UTF-8?B?VGhpcyBpcyDjgYIgc3RyaW5n?="
-
1
def Encodings.b_value_encode(encoded_str, encoding = nil)
-
return encoded_str if encoded_str.to_s.ascii_only?
-
string, encoding = RubyVer.b_value_encode(encoded_str, encoding)
-
map_lines(string) do |str|
-
"=?#{encoding}?B?#{str.chomp}?="
-
end.join(" ")
-
end
-
-
# Encode a string with Quoted-Printable Encoding and returns it ready to be inserted
-
# as a value for a field, that is, in the =?<charset>?Q?<string>?= format
-
#
-
# Example:
-
#
-
# Encodings.q_value_encode('This is あ string', 'UTF-8')
-
# #=> "=?UTF-8?Q?This_is_=E3=81=82_string?="
-
1
def Encodings.q_value_encode(encoded_str, encoding = nil)
-
return encoded_str if encoded_str.to_s.ascii_only?
-
string, encoding = RubyVer.q_value_encode(encoded_str, encoding)
-
string.gsub!("=\r\n", '') # We already have limited the string to the length we want
-
map_lines(string) do |str|
-
"=?#{encoding}?Q?#{str.chomp.gsub(/ /, '_')}?="
-
end.join(" ")
-
end
-
-
1
private
-
-
# Decodes a Base64 string from the "=?UTF-8?B?VGhpcyBpcyDjgYIgc3RyaW5n?=" format
-
#
-
# Example:
-
#
-
# Encodings.b_value_decode("=?UTF-8?B?VGhpcyBpcyDjgYIgc3RyaW5n?=")
-
# #=> 'This is あ string'
-
1
def Encodings.b_value_decode(str)
-
RubyVer.b_value_decode(str)
-
end
-
-
# Decodes a Quoted-Printable string from the "=?UTF-8?Q?This_is_=E3=81=82_string?=" format
-
#
-
# Example:
-
#
-
# Encodings.q_value_decode("=?UTF-8?Q?This_is_=E3=81=82_string?=")
-
# #=> 'This is あ string'
-
1
def Encodings.q_value_decode(str)
-
RubyVer.q_value_decode(str)
-
end
-
-
1
def Encodings.split_encoding_from_string( str )
-
match = str.match(/\=\?([^?]+)?\?[QB]\?(.+)?\?\=/mi)
-
if match
-
match[1]
-
else
-
nil
-
end
-
end
-
-
1
def Encodings.find_encoding(str)
-
RUBY_VERSION >= '1.9' ? str.encoding : $KCODE
-
end
-
-
# Gets the encoding type (Q or B) from the string.
-
1
def Encodings.split_value_encoding_from_string(str)
-
match = str.match(/\=\?[^?]+?\?([QB])\?(.+)?\?\=/mi)
-
if match
-
match[1]
-
else
-
nil
-
end
-
end
-
-
# When the encoded string consists of multiple lines, lines with the same
-
# encoding (Q or B) can be joined together.
-
#
-
# String has to be of the format =?<encoding>?[QB]?<string>?=
-
1
def Encodings.collapse_adjacent_encodings(str)
-
lines = str.split(/(\?=)\s*(=\?)/).each_slice(2).map(&:join)
-
results = []
-
previous_encoding = nil
-
-
lines.each do |line|
-
encoding = split_value_encoding_from_string(line)
-
-
if encoding == previous_encoding
-
line = results.pop + line
-
line.gsub!(/\?\=\=\?.+?\?[QqBb]\?/m, '')
-
end
-
-
previous_encoding = encoding
-
results << line
-
end
-
-
results
-
end
-
end
-
end
-
# encoding: utf-8
-
1
require 'mail/encodings/8bit'
-
-
1
module Mail
-
1
module Encodings
-
1
class SevenBit < EightBit
-
1
NAME = '7bit'
-
-
1
PRIORITY = 1
-
-
# 7bit and 8bit operate the same
-
-
# Decode the string
-
1
def self.decode(str)
-
super
-
end
-
-
# Encode the string
-
1
def self.encode(str)
-
super
-
end
-
-
# Idenity encodings have a fixed cost, 1 byte out per 1 byte in
-
1
def self.cost(str)
-
super
-
end
-
-
1
Encodings.register(NAME, self)
-
end
-
end
-
end
-
# encoding: utf-8
-
1
require 'mail/encodings/binary'
-
-
1
module Mail
-
1
module Encodings
-
1
class EightBit < Binary
-
1
NAME = '8bit'
-
-
1
PRIORITY = 4
-
-
# 8bit is an identiy encoding, meaning nothing to do
-
-
# Decode the string
-
1
def self.decode(str)
-
str.to_lf
-
end
-
-
# Encode the string
-
1
def self.encode(str)
-
str.to_crlf
-
end
-
-
# Idenity encodings have a fixed cost, 1 byte out per 1 byte in
-
1
def self.cost(str)
-
1.0
-
end
-
-
1
Encodings.register(NAME, self)
-
end
-
end
-
end
-
# encoding: utf-8
-
1
require 'mail/encodings/7bit'
-
-
1
module Mail
-
1
module Encodings
-
1
class Base64 < SevenBit
-
1
NAME = 'base64'
-
-
1
PRIORITY = 3
-
-
1
def self.can_encode?(enc)
-
true
-
end
-
-
# Decode the string from Base64
-
1
def self.decode(str)
-
RubyVer.decode_base64( str )
-
end
-
-
# Encode the string to Base64
-
1
def self.encode(str)
-
RubyVer.encode_base64( str ).to_crlf
-
end
-
-
# Base64 has a fixed cost, 4 bytes out per 3 bytes in
-
1
def self.cost(str)
-
4.0/3
-
end
-
-
1
Encodings.register(NAME, self)
-
end
-
end
-
end
-
# encoding: utf-8
-
1
require 'mail/encodings/transfer_encoding'
-
-
1
module Mail
-
1
module Encodings
-
1
class Binary < TransferEncoding
-
1
NAME = 'binary'
-
-
1
PRIORITY = 5
-
-
# Binary is an identiy encoding, meaning nothing to do
-
-
# Decode the string
-
1
def self.decode(str)
-
str
-
end
-
-
# Encode the string
-
1
def self.encode(str)
-
str
-
end
-
-
# Idenity encodings have a fixed cost, 1 byte out per 1 byte in
-
1
def self.cost(str)
-
1.0
-
end
-
-
1
Encodings.register(NAME, self)
-
end
-
end
-
end
-
# encoding: utf-8
-
1
require 'mail/encodings/7bit'
-
-
1
module Mail
-
1
module Encodings
-
1
class QuotedPrintable < SevenBit
-
1
NAME='quoted-printable'
-
-
1
PRIORITY = 2
-
-
1
def self.can_encode?(str)
-
EightBit.can_encode? str
-
end
-
-
# Decode the string from Quoted-Printable. Cope with hard line breaks
-
# that were incorrectly encoded as hex instead of literal CRLF.
-
1
def self.decode(str)
-
str.gsub(/(?:=0D=0A|=0D|=0A)\r\n/, "\r\n").unpack("M*").first.to_lf
-
end
-
-
1
def self.encode(str)
-
[str.to_lf].pack("M").to_crlf
-
end
-
-
1
def self.cost(str)
-
# These bytes probably do not need encoding
-
c = str.count("\x9\xA\xD\x20-\x3C\x3E-\x7E")
-
# Everything else turns into =XX where XX is a
-
# two digit hex number (taking 3 bytes)
-
total = (str.bytesize - c)*3 + c
-
total.to_f/str.bytesize
-
end
-
-
1
private
-
-
1
Encodings.register(NAME, self)
-
end
-
end
-
end
-
# encoding: utf-8
-
1
module Mail
-
1
module Encodings
-
1
class TransferEncoding
-
1
NAME = ''
-
-
1
PRIORITY = -1
-
-
1
def self.can_transport?(enc)
-
enc = Encodings.get_name(enc)
-
if Encodings.defined? enc
-
Encodings.get_encoding(enc).new.is_a? self
-
else
-
false
-
end
-
end
-
-
1
def self.can_encode?(enc)
-
can_transport? enc
-
end
-
-
1
def self.cost(str)
-
raise "Unimplemented"
-
end
-
-
1
def self.to_s
-
self::NAME
-
end
-
-
1
def self.get_best_compatible(source_encoding, str)
-
if self.can_transport? source_encoding then
-
source_encoding
-
else
-
choices = []
-
Encodings.get_all.each do |enc|
-
choices << enc if self.can_transport? enc and enc.can_encode? source_encoding
-
end
-
best = nil
-
best_cost = 100
-
choices.each do |enc|
-
this_cost = enc.cost str
-
if this_cost < best_cost then
-
best_cost = this_cost
-
best = enc
-
elsif this_cost == best_cost then
-
best = enc if enc::PRIORITY < best::PRIORITY
-
end
-
end
-
best
-
end
-
end
-
-
1
def to_s
-
self.class.to_s
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Mail Envelope
-
#
-
# The Envelope class provides a field for the first line in an
-
# mbox file, that looks like "From mikel@test.lindsaar.net DATETIME"
-
#
-
# This envelope class reads that line, and turns it into an
-
# Envelope.from and Envelope.date for your use.
-
1
module Mail
-
1
class Envelope < StructuredField
-
-
1
def initialize(*args)
-
super(FIELD_NAME, strip_field(FIELD_NAME, args.last))
-
end
-
-
1
def tree
-
@element ||= Mail::EnvelopeFromElement.new(value)
-
@tree ||= @element.tree
-
end
-
-
1
def element
-
@element ||= Mail::EnvelopeFromElement.new(value)
-
end
-
-
1
def date
-
::DateTime.parse("#{element.date_time}")
-
end
-
-
1
def from
-
element.address
-
end
-
-
end
-
end
-
1
require 'mail/fields'
-
-
# encoding: utf-8
-
1
module Mail
-
# Provides a single class to call to create a new structured or unstructured
-
# field. Works out per RFC what field of field it is being given and returns
-
# the correct field of class back on new.
-
#
-
# ===Per RFC 2822
-
#
-
# 2.2. Header Fields
-
#
-
# Header fields are lines composed of a field name, followed by a colon
-
# (":"), followed by a field body, and terminated by CRLF. A field
-
# name MUST be composed of printable US-ASCII characters (i.e.,
-
# characters that have values between 33 and 126, inclusive), except
-
# colon. A field body may be composed of any US-ASCII characters,
-
# except for CR and LF. However, a field body may contain CRLF when
-
# used in header "folding" and "unfolding" as described in section
-
# 2.2.3. All field bodies MUST conform to the syntax described in
-
# sections 3 and 4 of this standard.
-
#
-
1
class Field
-
-
1
include Patterns
-
1
include Comparable
-
-
1
STRUCTURED_FIELDS = %w[ bcc cc content-description content-disposition
-
content-id content-location content-transfer-encoding
-
content-type date from in-reply-to keywords message-id
-
mime-version received references reply-to
-
resent-bcc resent-cc resent-date resent-from
-
resent-message-id resent-sender resent-to
-
return-path sender to ]
-
-
1
KNOWN_FIELDS = STRUCTURED_FIELDS + ['comments', 'subject']
-
-
1
FIELDS_MAP = {
-
"to" => ToField,
-
"cc" => CcField,
-
"bcc" => BccField,
-
"message-id" => MessageIdField,
-
"in-reply-to" => InReplyToField,
-
"references" => ReferencesField,
-
"subject" => SubjectField,
-
"comments" => CommentsField,
-
"keywords" => KeywordsField,
-
"date" => DateField,
-
"from" => FromField,
-
"sender" => SenderField,
-
"reply-to" => ReplyToField,
-
"resent-date" => ResentDateField,
-
"resent-from" => ResentFromField,
-
"resent-sender" => ResentSenderField,
-
"resent-to" => ResentToField,
-
"resent-cc" => ResentCcField,
-
"resent-bcc" => ResentBccField,
-
"resent-message-id" => ResentMessageIdField,
-
"return-path" => ReturnPathField,
-
"received" => ReceivedField,
-
"mime-version" => MimeVersionField,
-
"content-transfer-encoding" => ContentTransferEncodingField,
-
"content-description" => ContentDescriptionField,
-
"content-disposition" => ContentDispositionField,
-
"content-type" => ContentTypeField,
-
"content-id" => ContentIdField,
-
"content-location" => ContentLocationField,
-
}
-
-
# Generic Field Exception
-
1
class FieldError < StandardError
-
end
-
-
# Raised when a parsing error has occurred (ie, a StructuredField has tried
-
# to parse a field that is invalid or improperly written)
-
1
class ParseError < FieldError #:nodoc:
-
1
attr_accessor :element, :value, :reason
-
-
1
def initialize(element, value, reason)
-
@element = element
-
@value = value
-
@reason = reason
-
super("#{element} can not parse |#{value}|\nReason was: #{reason}")
-
end
-
end
-
-
# Raised when attempting to set a structured field's contents to an invalid syntax
-
1
class SyntaxError < FieldError #:nodoc:
-
end
-
-
# Accepts a string:
-
#
-
# Field.new("field-name: field data")
-
#
-
# Or name, value pair:
-
#
-
# Field.new("field-name", "value")
-
#
-
# Or a name by itself:
-
#
-
# Field.new("field-name")
-
#
-
# Note, does not want a terminating carriage return. Returns
-
# self appropriately parsed. If value is not a string, then
-
# it will be passed through as is, for example, content-type
-
# field can accept an array with the type and a hash of
-
# parameters:
-
#
-
# Field.new('content-type', ['text', 'plain', {:charset => 'UTF-8'}])
-
1
def initialize(name, value = nil, charset = 'utf-8')
-
case
-
when name =~ /:/ # Field.new("field-name: field data")
-
charset = value unless value.blank?
-
name, value = split(name)
-
create_field(name, value, charset)
-
when name !~ /:/ && value.blank? # Field.new("field-name")
-
create_field(name, nil, charset)
-
else # Field.new("field-name", "value")
-
create_field(name, value, charset)
-
end
-
return self
-
end
-
-
1
def field=(value)
-
@field = value
-
end
-
-
1
def field
-
@field
-
end
-
-
1
def name
-
field.name
-
end
-
-
1
def value
-
field.value
-
end
-
-
1
def value=(val)
-
create_field(name, val, charset)
-
end
-
-
1
def to_s
-
field.to_s
-
end
-
-
1
def update(name, value)
-
create_field(name, value, charset)
-
end
-
-
1
def same( other )
-
match_to_s(other.name, field.name)
-
end
-
-
1
alias_method :==, :same
-
-
1
def <=>( other )
-
self.field_order_id <=> other.field_order_id
-
end
-
-
1
def field_order_id
-
@field_order_id ||= (FIELD_ORDER_LOOKUP[self.name.to_s.downcase] || 100)
-
end
-
-
1
def method_missing(name, *args, &block)
-
field.send(name, *args, &block)
-
end
-
-
1
FIELD_ORDER = %w[ return-path received
-
resent-date resent-from resent-sender resent-to
-
resent-cc resent-bcc resent-message-id
-
date from sender reply-to to cc bcc
-
message-id in-reply-to references
-
subject comments keywords
-
mime-version content-type content-transfer-encoding
-
content-location content-disposition content-description ]
-
-
1
FIELD_ORDER_LOOKUP = Hash[FIELD_ORDER.each_with_index.to_a]
-
-
1
private
-
-
1
def split(raw_field)
-
match_data = raw_field.mb_chars.match(FIELD_SPLIT)
-
[match_data[1].to_s.mb_chars.strip, match_data[2].to_s.mb_chars.strip]
-
rescue
-
STDERR.puts "WARNING: Could not parse (and so ignoring) '#{raw_field}'"
-
end
-
-
1
def create_field(name, value, charset)
-
begin
-
self.field = new_field(name, value, charset)
-
rescue Mail::Field::ParseError => e
-
self.field = Mail::UnstructuredField.new(name, value)
-
self.field.errors << [name, value, e]
-
self.field
-
end
-
end
-
-
1
def new_field(name, value, charset)
-
lower_case_name = name.to_s.downcase
-
if field_klass = FIELDS_MAP[lower_case_name]
-
field_klass.new(value, charset)
-
else
-
OptionalField.new(name, value, charset)
-
end
-
end
-
-
end
-
-
end
-
# encoding: utf-8
-
1
module Mail
-
-
# Field List class provides an enhanced array that keeps a list of
-
# email fields in order. And allows you to insert new fields without
-
# having to worry about the order they will appear in.
-
1
class FieldList < Array
-
-
1
include Enumerable
-
-
1
def <<( new_field )
-
current_entry = self.rindex(new_field)
-
if current_entry
-
self.insert((current_entry + 1), new_field)
-
else
-
insert_idx = -1
-
self.each_with_index do |item, idx|
-
case item <=> new_field
-
when -1
-
next
-
when 0
-
next
-
when 1
-
insert_idx = idx
-
break
-
end
-
end
-
insert(insert_idx, new_field)
-
end
-
end
-
-
end
-
end
-
1
module Mail
-
1
register_autoload :UnstructuredField, 'mail/fields/unstructured_field'
-
1
register_autoload :StructuredField, 'mail/fields/structured_field'
-
1
register_autoload :OptionalField, 'mail/fields/optional_field'
-
-
1
register_autoload :BccField, 'mail/fields/bcc_field'
-
1
register_autoload :CcField, 'mail/fields/cc_field'
-
1
register_autoload :CommentsField, 'mail/fields/comments_field'
-
1
register_autoload :ContentDescriptionField, 'mail/fields/content_description_field'
-
1
register_autoload :ContentDispositionField, 'mail/fields/content_disposition_field'
-
1
register_autoload :ContentIdField, 'mail/fields/content_id_field'
-
1
register_autoload :ContentLocationField, 'mail/fields/content_location_field'
-
1
register_autoload :ContentTransferEncodingField, 'mail/fields/content_transfer_encoding_field'
-
1
register_autoload :ContentTypeField, 'mail/fields/content_type_field'
-
1
register_autoload :DateField, 'mail/fields/date_field'
-
1
register_autoload :FromField, 'mail/fields/from_field'
-
1
register_autoload :InReplyToField, 'mail/fields/in_reply_to_field'
-
1
register_autoload :KeywordsField, 'mail/fields/keywords_field'
-
1
register_autoload :MessageIdField, 'mail/fields/message_id_field'
-
1
register_autoload :MimeVersionField, 'mail/fields/mime_version_field'
-
1
register_autoload :ReceivedField, 'mail/fields/received_field'
-
1
register_autoload :ReferencesField, 'mail/fields/references_field'
-
1
register_autoload :ReplyToField, 'mail/fields/reply_to_field'
-
1
register_autoload :ResentBccField, 'mail/fields/resent_bcc_field'
-
1
register_autoload :ResentCcField, 'mail/fields/resent_cc_field'
-
1
register_autoload :ResentDateField, 'mail/fields/resent_date_field'
-
1
register_autoload :ResentFromField, 'mail/fields/resent_from_field'
-
1
register_autoload :ResentMessageIdField, 'mail/fields/resent_message_id_field'
-
1
register_autoload :ResentSenderField, 'mail/fields/resent_sender_field'
-
1
register_autoload :ResentToField, 'mail/fields/resent_to_field'
-
1
register_autoload :ReturnPathField, 'mail/fields/return_path_field'
-
1
register_autoload :SenderField, 'mail/fields/sender_field'
-
1
register_autoload :SubjectField, 'mail/fields/subject_field'
-
1
register_autoload :ToField, 'mail/fields/to_field'
-
end
-
# encoding: utf-8
-
#
-
# = Blind Carbon Copy Field
-
#
-
# The Bcc field inherits from StructuredField and handles the Bcc: header
-
# field in the email.
-
#
-
# Sending bcc to a mail message will instantiate a Mail::Field object that
-
# has a BccField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Bcc field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.bcc = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:bcc] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::BccField:0x180e1c4
-
# mail['bcc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::BccField:0x180e1c4
-
# mail['Bcc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::BccField:0x180e1c4
-
#
-
# mail[:bcc].encoded #=> '' # Bcc field does not get output into an email
-
# mail[:bcc].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:bcc].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:bcc].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
1
require 'mail/fields/common/common_address'
-
-
1
module Mail
-
1
class BccField < StructuredField
-
-
1
include Mail::CommonAddress
-
-
1
FIELD_NAME = 'bcc'
-
1
CAPITALIZED_FIELD = 'Bcc'
-
-
1
def initialize(value = '', charset = 'utf-8')
-
@charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
# Bcc field should never be :encoded
-
1
def encoded
-
''
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Carbon Copy Field
-
#
-
# The Cc field inherits from StructuredField and handles the Cc: header
-
# field in the email.
-
#
-
# Sending cc to a mail message will instantiate a Mail::Field object that
-
# has a CcField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Cc field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.cc = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:cc] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::CcField:0x180e1c4
-
# mail['cc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::CcField:0x180e1c4
-
# mail['Cc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::CcField:0x180e1c4
-
#
-
# mail[:cc].encoded #=> 'Cc: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:cc].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:cc].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:cc].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
1
require 'mail/fields/common/common_address'
-
-
1
module Mail
-
1
class CcField < StructuredField
-
-
1
include Mail::CommonAddress
-
-
1
FIELD_NAME = 'cc'
-
1
CAPITALIZED_FIELD = 'Cc'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Comments Field
-
#
-
# The Comments field inherits from UnstructuredField and handles the Comments:
-
# header field in the email.
-
#
-
# Sending comments to a mail message will instantiate a Mail::Field object that
-
# has a CommentsField as its field type.
-
#
-
# An email header can have as many comments fields as it wants. There is no upper
-
# limit, the comments field is also optional (that is, no comment is needed)
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.comments = 'This is a comment'
-
# mail.comments #=> 'This is a comment'
-
# mail[:comments] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::CommentsField:0x180e1c4
-
# mail['comments'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::CommentsField:0x180e1c4
-
# mail['comments'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::CommentsField:0x180e1c4
-
#
-
# mail.comments = "This is another comment"
-
# mail[:comments].map { |c| c.to_s }
-
# #=> ['This is a comment', "This is another comment"]
-
#
-
1
module Mail
-
1
class CommentsField < UnstructuredField
-
-
1
FIELD_NAME = 'comments'
-
1
CAPITALIZED_FIELD = 'Comments'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
@charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value))
-
self.parse
-
self
-
end
-
-
end
-
end
-
1
module Mail
-
-
1
class AddressContainer < Array
-
-
1
def initialize(field, list = [])
-
@field = field
-
super(list)
-
end
-
-
1
def << (address)
-
@field << address
-
end
-
-
end
-
-
end
-
# encoding: utf-8
-
1
require 'mail/fields/common/address_container'
-
-
1
module Mail
-
1
module CommonAddress # :nodoc:
-
-
1
def parse(val = value)
-
unless val.blank?
-
@tree = AddressList.new(encode_if_needed(val))
-
else
-
nil
-
end
-
end
-
-
1
def charset
-
@charset
-
end
-
-
1
def encode_if_needed(val)
-
Encodings.address_encode(val, charset)
-
end
-
-
# Allows you to iterate through each address object in the syntax tree
-
1
def each
-
tree.addresses.each do |address|
-
yield(address)
-
end
-
end
-
-
# Returns the address string of all the addresses in the address list
-
1
def addresses
-
list = tree.addresses.map { |a| a.address }
-
Mail::AddressContainer.new(self, list)
-
end
-
-
# Returns the formatted string of all the addresses in the address list
-
1
def formatted
-
list = tree.addresses.map { |a| a.format }
-
Mail::AddressContainer.new(self, list)
-
end
-
-
# Returns the display name of all the addresses in the address list
-
1
def display_names
-
list = tree.addresses.map { |a| a.display_name }
-
Mail::AddressContainer.new(self, list)
-
end
-
-
# Returns the actual address objects in the address list
-
1
def addrs
-
list = tree.addresses
-
Mail::AddressContainer.new(self, list)
-
end
-
-
# Returns a hash of group name => address strings for the address list
-
1
def groups
-
@groups = Hash.new
-
tree.group_recipients.each do |group|
-
@groups[group.group_name.text_value.to_str] = get_group_addresses(group.group_list)
-
end
-
@groups
-
end
-
-
# Returns the addresses that are part of groups
-
1
def group_addresses
-
decoded_group_addresses
-
end
-
-
# Returns a list of decoded group addresses
-
1
def decoded_group_addresses
-
groups.map { |k,v| v.map { |a| a.decoded } }.flatten
-
end
-
-
# Returns a list of encoded group addresses
-
1
def encoded_group_addresses
-
groups.map { |k,v| v.map { |a| a.encoded } }.flatten
-
end
-
-
# Returns the name of all the groups in a string
-
1
def group_names # :nodoc:
-
tree.group_names
-
end
-
-
1
def default
-
addresses
-
end
-
-
1
def <<(val)
-
case
-
when val.nil?
-
raise ArgumentError, "Need to pass an address to <<"
-
when val.blank?
-
parse(encoded)
-
else
-
self.value = [self.value, val].reject {|a| a.blank? }.join(", ")
-
end
-
end
-
-
1
def value=(val)
-
super
-
parse(self.value)
-
end
-
-
1
private
-
-
1
def do_encode(field_name)
-
return '' if value.blank?
-
address_array = tree.addresses.reject { |a| encoded_group_addresses.include?(a.encoded) }.compact.map { |a| a.encoded }
-
address_text = address_array.join(", \r\n\s")
-
group_array = groups.map { |k,v| "#{k}: #{v.map { |a| a.encoded }.join(", \r\n\s")};" }
-
group_text = group_array.join(" \r\n\s")
-
return_array = [address_text, group_text].reject { |a| a.blank? }
-
"#{field_name}: #{return_array.join(", \r\n\s")}\r\n"
-
end
-
-
1
def do_decode
-
return nil if value.blank?
-
address_array = tree.addresses.reject { |a| decoded_group_addresses.include?(a.decoded) }.map { |a| a.decoded }
-
address_text = address_array.join(", ")
-
group_array = groups.map { |k,v| "#{k}: #{v.map { |a| a.decoded }.join(", ")};" }
-
group_text = group_array.join(" ")
-
return_array = [address_text, group_text].reject { |a| a.blank? }
-
return_array.join(", ")
-
end
-
-
# Returns the syntax tree of the Addresses
-
1
def tree # :nodoc:
-
@tree ||= AddressList.new(value)
-
end
-
-
1
def get_group_addresses(group_list)
-
if group_list.respond_to?(:addresses)
-
group_list.addresses.map do |address_tree|
-
Mail::Address.new(address_tree)
-
end
-
else
-
[]
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
1
module Mail
-
1
module CommonDate # :nodoc:
-
# Returns a date time object of the parsed date
-
1
def date_time
-
::DateTime.parse("#{element.date_string} #{element.time_string}")
-
end
-
-
1
def default
-
date_time
-
end
-
-
1
def parse(val = value)
-
unless val.blank?
-
@element = Mail::DateTimeElement.new(val)
-
@tree = @element.tree
-
else
-
nil
-
end
-
end
-
-
1
private
-
-
1
def do_encode(field_name)
-
"#{field_name}: #{value}\r\n"
-
end
-
-
1
def do_decode
-
"#{value}"
-
end
-
-
1
def element
-
@element ||= Mail::DateTimeElement.new(value)
-
end
-
-
# Returns the syntax tree of the Date
-
1
def tree
-
@tree ||= element.tree
-
end
-
-
end
-
end
-
# encoding: utf-8
-
1
module Mail
-
1
module CommonField # :nodoc:
-
-
1
def name=(value)
-
@name = value
-
end
-
-
1
def name
-
@name ||= nil
-
end
-
-
1
def value=(value)
-
@length = nil
-
@tree = nil
-
@element = nil
-
@value = value
-
end
-
-
1
def value
-
@value
-
end
-
-
1
def to_s
-
decoded.to_s
-
end
-
-
1
def default
-
decoded
-
end
-
-
1
def field_length
-
@length ||= "#{name}: #{encode(decoded)}".length
-
end
-
-
1
def responsible_for?( val )
-
name.to_s.casecmp(val.to_s) == 0
-
end
-
-
1
private
-
-
1
def strip_field(field_name, value)
-
if value.is_a?(Array)
-
value
-
else
-
value.to_s.gsub(/#{field_name}:\s+/i, '')
-
end
-
end
-
-
1
FILENAME_RE = /\b(filename|name)=([^;"\r\n]+\s[^;"\r\n]+)/
-
1
def ensure_filename_quoted(value)
-
if value.is_a?(String)
-
value.sub! FILENAME_RE, '\1="\2"'
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
1
module Mail
-
1
module CommonMessageId # :nodoc:
-
1
def element
-
@element ||= Mail::MessageIdsElement.new(value) unless value.blank?
-
end
-
-
1
def parse(val = value)
-
unless val.blank?
-
@element = Mail::MessageIdsElement.new(val)
-
else
-
nil
-
end
-
end
-
-
1
def message_id
-
element.message_id if element
-
end
-
-
1
def message_ids
-
element.message_ids if element
-
end
-
-
1
def default
-
return nil unless message_ids
-
if message_ids.length == 1
-
message_ids[0]
-
else
-
message_ids
-
end
-
end
-
-
1
private
-
-
1
def do_encode(field_name)
-
%Q{#{field_name}: #{formated_message_ids("\r\n ")}\r\n}
-
end
-
-
1
def do_decode
-
formated_message_ids(' ')
-
end
-
-
1
def formated_message_ids(join)
-
message_ids.map{ |m| "<#{m}>" }.join(join) if message_ids
-
end
-
-
end
-
end
-
# encoding: utf-8
-
1
module Mail
-
-
# ParameterHash is an intelligent Hash that allows you to add
-
# parameter values including the MIME extension paramaters that
-
# have the name*0="blah", name*1="bleh" keys, and will just return
-
# a single key called name="blahbleh" and do any required un-encoding
-
# to make that happen
-
# Parameters are defined in RFC2045, split keys are in RFC2231
-
-
1
class ParameterHash < IndifferentHash
-
-
1
include Mail::Utilities
-
-
1
def [](key_name)
-
key_pattern = Regexp.escape(key_name.to_s)
-
pairs = []
-
exact = nil
-
each do |k,v|
-
if k =~ /^#{key_pattern}(\*|$)/i
-
if $1 == '*'
-
pairs << [k, v]
-
else
-
exact = k
-
end
-
end
-
end
-
if pairs.empty? # Just dealing with a single value pair
-
super(exact || key_name)
-
else # Dealing with a multiple value pair or a single encoded value pair
-
string = pairs.sort { |a,b| a.first.to_s <=> b.first.to_s }.map { |v| v.last }.join('')
-
if mt = string.match(/([\w\-]+)'(\w\w)'(.*)/)
-
string = mt[3]
-
encoding = mt[1]
-
else
-
encoding = nil
-
end
-
Mail::Encodings.param_decode(string, encoding)
-
end
-
end
-
-
1
def encoded
-
map.sort { |a,b| a.first.to_s <=> b.first.to_s }.map do |key_name, value|
-
unless value.ascii_only?
-
value = Mail::Encodings.param_encode(value)
-
key_name = "#{key_name}*"
-
end
-
%Q{#{key_name}=#{quote_token(value)}}
-
end.join(";\r\n\s")
-
end
-
-
1
def decoded
-
map.sort { |a,b| a.first.to_s <=> b.first.to_s }.map do |key_name, value|
-
%Q{#{key_name}=#{quote_token(value)}}
-
end.join("; ")
-
end
-
end
-
end
-
# encoding: utf-8
-
#
-
#
-
#
-
1
module Mail
-
1
class ContentDescriptionField < UnstructuredField
-
-
1
FIELD_NAME = 'content-description'
-
1
CAPITALIZED_FIELD = 'Content-Description'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
end
-
end
-
# encoding: utf-8
-
1
require 'mail/fields/common/parameter_hash'
-
-
1
module Mail
-
1
class ContentDispositionField < StructuredField
-
-
1
FIELD_NAME = 'content-disposition'
-
1
CAPITALIZED_FIELD = 'Content-Disposition'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
ensure_filename_quoted(value)
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
1
def parse(val = value)
-
unless val.blank?
-
@element = Mail::ContentDispositionElement.new(val)
-
end
-
end
-
-
1
def element
-
@element ||= Mail::ContentDispositionElement.new(value)
-
end
-
-
1
def disposition_type
-
element.disposition_type
-
end
-
-
1
def parameters
-
@parameters = ParameterHash.new
-
element.parameters.each { |p| @parameters.merge!(p) }
-
@parameters
-
end
-
-
1
def filename
-
case
-
when !parameters['filename'].blank?
-
@filename = parameters['filename']
-
when !parameters['name'].blank?
-
@filename = parameters['name']
-
else
-
@filename = nil
-
end
-
@filename
-
end
-
-
# TODO: Fix this up
-
1
def encoded
-
if parameters.length > 0
-
p = ";\r\n\s#{parameters.encoded}\r\n"
-
else
-
p = "\r\n"
-
end
-
"#{CAPITALIZED_FIELD}: #{disposition_type}" + p
-
end
-
-
1
def decoded
-
if parameters.length > 0
-
p = "; #{parameters.decoded}"
-
else
-
p = ""
-
end
-
"#{disposition_type}" + p
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
#
-
#
-
1
module Mail
-
1
class ContentIdField < StructuredField
-
-
1
FIELD_NAME = 'content-id'
-
1
CAPITALIZED_FIELD = "Content-ID"
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
@uniq = 1
-
if value.blank?
-
value = generate_content_id
-
else
-
value = strip_field(FIELD_NAME, value)
-
end
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
1
def parse(val = value)
-
unless val.blank?
-
@element = Mail::MessageIdsElement.new(val)
-
end
-
end
-
-
1
def element
-
@element ||= Mail::MessageIdsElement.new(value)
-
end
-
-
1
def name
-
'Content-ID'
-
end
-
-
1
def content_id
-
element.message_id
-
end
-
-
1
def to_s
-
"<#{content_id}>"
-
end
-
-
# TODO: Fix this up
-
1
def encoded
-
"#{CAPITALIZED_FIELD}: #{to_s}\r\n"
-
end
-
-
1
def decoded
-
"#{to_s}"
-
end
-
-
1
private
-
-
1
def generate_content_id
-
"<#{Mail.random_tag}@#{::Socket.gethostname}.mail>"
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
#
-
#
-
1
module Mail
-
1
class ContentLocationField < StructuredField
-
-
1
FIELD_NAME = 'content-location'
-
1
CAPITALIZED_FIELD = 'Content-Location'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
1
def parse(val = value)
-
unless val.blank?
-
@element = Mail::ContentLocationElement.new(val)
-
end
-
end
-
-
1
def element
-
@element ||= Mail::ContentLocationElement.new(value)
-
end
-
-
1
def location
-
element.location
-
end
-
-
# TODO: Fix this up
-
1
def encoded
-
"#{CAPITALIZED_FIELD}: #{location}\r\n"
-
end
-
-
1
def decoded
-
location
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
#
-
#
-
1
module Mail
-
1
class ContentTransferEncodingField < StructuredField
-
-
1
FIELD_NAME = 'content-transfer-encoding'
-
1
CAPITALIZED_FIELD = 'Content-Transfer-Encoding'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
value = '7bit' if value.to_s =~ /7-?bits?/i
-
value = '8bit' if value.to_s =~ /8-?bits?/i
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
1
def parse(val = value)
-
unless val.blank?
-
@element = Mail::ContentTransferEncodingElement.new(val)
-
end
-
end
-
-
1
def tree
-
STDERR.puts("tree is deprecated. Please use encoding to get parse result\n#{caller}")
-
@element ||= Mail::ContentTransferEncodingElement.new(value)
-
@tree ||= @element.tree
-
end
-
-
1
def element
-
@element ||= Mail::ContentTransferEncodingElement.new(value)
-
end
-
-
1
def encoding
-
element.encoding
-
end
-
-
# TODO: Fix this up
-
1
def encoded
-
"#{CAPITALIZED_FIELD}: #{encoding}\r\n"
-
end
-
-
1
def decoded
-
encoding
-
end
-
-
end
-
end
-
# encoding: utf-8
-
1
require 'mail/fields/common/parameter_hash'
-
-
1
module Mail
-
1
class ContentTypeField < StructuredField
-
-
1
FIELD_NAME = 'content-type'
-
1
CAPITALIZED_FIELD = 'Content-Type'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
if value.class == Array
-
@main_type = value[0]
-
@sub_type = value[1]
-
@parameters = ParameterHash.new.merge!(value.last)
-
else
-
@main_type = nil
-
@sub_type = nil
-
@parameters = nil
-
value = strip_field(FIELD_NAME, value)
-
end
-
ensure_filename_quoted(value)
-
super(CAPITALIZED_FIELD, value, charset)
-
self.parse
-
self
-
end
-
-
1
def parse(val = value)
-
unless val.blank?
-
self.value = val
-
@element = nil
-
element
-
end
-
end
-
-
1
def element
-
begin
-
@element ||= Mail::ContentTypeElement.new(value)
-
rescue
-
attempt_to_clean
-
end
-
end
-
-
1
def attempt_to_clean
-
# Sanitize the value, handle special cases
-
@element ||= Mail::ContentTypeElement.new(sanatize(value))
-
rescue
-
# All else fails, just get the MIME media type
-
@element ||= Mail::ContentTypeElement.new(get_mime_type(value))
-
end
-
-
1
def main_type
-
@main_type ||= element.main_type
-
end
-
-
1
def sub_type
-
@sub_type ||= element.sub_type
-
end
-
-
1
def string
-
"#{main_type}/#{sub_type}"
-
end
-
-
1
def default
-
decoded
-
end
-
-
1
alias :content_type :string
-
-
1
def parameters
-
unless @parameters
-
@parameters = ParameterHash.new
-
element.parameters.each { |p| @parameters.merge!(p) }
-
end
-
@parameters
-
end
-
-
1
def ContentTypeField.with_boundary(type)
-
new("#{type}; boundary=#{generate_boundary}")
-
end
-
-
1
def ContentTypeField.generate_boundary
-
"--==_mimepart_#{Mail.random_tag}"
-
end
-
-
1
def value
-
if @value.class == Array
-
"#{@main_type}/#{@sub_type}; #{stringify(parameters)}"
-
else
-
@value
-
end
-
end
-
-
1
def stringify(params)
-
params.map { |k,v| "#{k}=#{Encodings.param_encode(v)}" }.join("; ")
-
end
-
-
1
def filename
-
case
-
when parameters['filename']
-
@filename = parameters['filename']
-
when parameters['name']
-
@filename = parameters['name']
-
else
-
@filename = nil
-
end
-
@filename
-
end
-
-
# TODO: Fix this up
-
1
def encoded
-
if parameters.length > 0
-
p = ";\r\n\s#{parameters.encoded}"
-
else
-
p = ""
-
end
-
"#{CAPITALIZED_FIELD}: #{content_type}#{p}\r\n"
-
end
-
-
1
def decoded
-
if parameters.length > 0
-
p = "; #{parameters.decoded}"
-
else
-
p = ""
-
end
-
"#{content_type}" + p
-
end
-
-
1
private
-
-
1
def method_missing(name, *args, &block)
-
if name.to_s =~ /(\w+)=/
-
self.parameters[$1] = args.first
-
@value = "#{content_type}; #{stringify(parameters)}"
-
else
-
super
-
end
-
end
-
-
# Various special cases from random emails found that I am not going to change
-
# the parser for
-
1
def sanatize( val )
-
-
# TODO: check if there are cases where whitespace is not a separator
-
val = val.
-
gsub(/\s*=\s*/,'='). # remove whitespaces around equal sign
-
tr(' ',';').
-
squeeze(';').
-
gsub(';', '; '). #use '; ' as a separator (or EOL)
-
gsub(/;\s*$/,'') #remove trailing to keep examples below
-
-
if val =~ /(boundary=(\S*))/i
-
val = "#{$`.downcase}boundary=#{$2}#{$'.downcase}"
-
else
-
val.downcase!
-
end
-
-
case
-
when val.chomp =~ /^\s*([\w\-]+)\/([\w\-]+)\s*;;+(.*)$/i
-
# Handles 'text/plain;; format="flowed"' (double semi colon)
-
"#{$1}/#{$2}; #{$3}"
-
when val.chomp =~ /^\s*([\w\-]+)\/([\w\-]+)\s*;\s?(ISO[\w\-]+)$/i
-
# Microsoft helper:
-
# Handles 'type/subtype;ISO-8559-1'
-
"#{$1}/#{$2}; charset=#{quote_atom($3)}"
-
when val.chomp =~ /^text;?$/i
-
# Handles 'text;' and 'text'
-
"text/plain;"
-
when val.chomp =~ /^(\w+);\s(.*)$/i
-
# Handles 'text; <parameters>'
-
"text/plain; #{$2}"
-
when val =~ /([\w\-]+\/[\w\-]+);\scharset="charset="(\w+)""/i
-
# Handles text/html; charset="charset="GB2312""
-
"#{$1}; charset=#{quote_atom($2)}"
-
when val =~ /([\w\-]+\/[\w\-]+);\s+(.*)/i
-
type = $1
-
# Handles misquoted param values
-
# e.g: application/octet-stream; name=archiveshelp1[1].htm
-
# and: audio/x-midi;\r\n\sname=Part .exe
-
params = $2.to_s.split(/\s+/)
-
params = params.map { |i| i.to_s.chomp.strip }
-
params = params.map { |i| i.split(/\s*\=\s*/) }
-
params = params.map { |i| "#{i[0]}=#{dquote(i[1].to_s.gsub(/;$/,""))}" }.join('; ')
-
"#{type}; #{params}"
-
when val =~ /^\s*$/
-
'text/plain'
-
else
-
''
-
end
-
end
-
-
1
def get_mime_type( val )
-
case
-
when val =~ /^([\w\-]+)\/([\w\-]+);.+$/i
-
"#{$1}/#{$2}"
-
else
-
'text/plain'
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Date Field
-
#
-
# The Date field inherits from StructuredField and handles the Date: header
-
# field in the email.
-
#
-
# Sending date to a mail message will instantiate a Mail::Field object that
-
# has a DateField as its field type. This includes all Mail::CommonAddress
-
# module instance methods.
-
#
-
# There must be excatly one Date field in an RFC2822 email.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.date = 'Mon, 24 Nov 1997 14:22:01 -0800'
-
# mail.date #=> #<DateTime: 211747170121/86400,-1/3,2299161>
-
# mail.date.to_s #=> 'Mon, 24 Nov 1997 14:22:01 -0800'
-
# mail[:date] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::DateField:0x180e1c4
-
# mail['date'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::DateField:0x180e1c4
-
# mail['Date'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::DateField:0x180e1c4
-
#
-
1
require 'mail/fields/common/common_date'
-
-
1
module Mail
-
1
class DateField < StructuredField
-
-
1
include Mail::CommonDate
-
-
1
FIELD_NAME = 'date'
-
1
CAPITALIZED_FIELD = "Date"
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
if value.blank?
-
value = ::DateTime.now.strftime('%a, %d %b %Y %H:%M:%S %z')
-
else
-
value = strip_field(FIELD_NAME, value)
-
value.to_s.gsub!(/\(.*?\)/, '')
-
value = ::DateTime.parse(value.to_s.squeeze(" ")).strftime('%a, %d %b %Y %H:%M:%S %z')
-
end
-
super(CAPITALIZED_FIELD, value, charset)
-
rescue ArgumentError => e
-
raise e unless "invalid date"==e.message
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = From Field
-
#
-
# The From field inherits from StructuredField and handles the From: header
-
# field in the email.
-
#
-
# Sending from to a mail message will instantiate a Mail::Field object that
-
# has a FromField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one From field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.from = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:from] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::FromField:0x180e1c4
-
# mail['from'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::FromField:0x180e1c4
-
# mail['From'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::FromField:0x180e1c4
-
#
-
# mail[:from].encoded #=> 'from: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:from].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:from].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:from].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
1
require 'mail/fields/common/common_address'
-
-
1
module Mail
-
1
class FromField < StructuredField
-
-
1
include Mail::CommonAddress
-
-
1
FIELD_NAME = 'from'
-
1
CAPITALIZED_FIELD = 'From'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = In-Reply-To Field
-
#
-
# The In-Reply-To field inherits from StructuredField and handles the
-
# In-Reply-To: header field in the email.
-
#
-
# Sending in_reply_to to a mail message will instantiate a Mail::Field object that
-
# has a InReplyToField as its field type. This includes all Mail::CommonMessageId
-
# module instance metods.
-
#
-
# Note that, the #message_ids method will return an array of message IDs without the
-
# enclosing angle brackets which per RFC are not syntactically part of the message id.
-
#
-
# Only one InReplyTo field can appear in a header, though it can have multiple
-
# Message IDs.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.in_reply_to = '<F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom>'
-
# mail.in_reply_to #=> '<F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom>'
-
# mail[:in_reply_to] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::InReplyToField:0x180e1c4
-
# mail['in_reply_to'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::InReplyToField:0x180e1c4
-
# mail['In-Reply-To'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::InReplyToField:0x180e1c4
-
#
-
# mail[:in_reply_to].message_ids #=> ['F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom']
-
#
-
1
require 'mail/fields/common/common_message_id'
-
-
1
module Mail
-
1
class InReplyToField < StructuredField
-
-
1
include Mail::CommonMessageId
-
-
1
FIELD_NAME = 'in-reply-to'
-
1
CAPITALIZED_FIELD = 'In-Reply-To'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
value = value.join("\r\n\s") if value.is_a?(Array)
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# keywords = "Keywords:" phrase *("," phrase) CRLF
-
1
module Mail
-
1
class KeywordsField < StructuredField
-
-
1
FIELD_NAME = 'keywords'
-
1
CAPITALIZED_FIELD = 'Keywords'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
1
def parse(val = value)
-
unless val.blank?
-
@phrase_list ||= PhraseList.new(value)
-
end
-
end
-
-
1
def phrase_list
-
@phrase_list ||= PhraseList.new(value)
-
end
-
-
1
def keywords
-
phrase_list.phrases
-
end
-
-
1
def encoded
-
"#{CAPITALIZED_FIELD}: #{keywords.join(",\r\n ")}\r\n"
-
end
-
-
1
def decoded
-
keywords.join(', ')
-
end
-
-
1
def default
-
keywords
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Message-ID Field
-
#
-
# The Message-ID field inherits from StructuredField and handles the
-
# Message-ID: header field in the email.
-
#
-
# Sending message_id to a mail message will instantiate a Mail::Field object that
-
# has a MessageIdField as its field type. This includes all Mail::CommonMessageId
-
# module instance metods.
-
#
-
# Only one MessageId field can appear in a header, and syntactically it can only have
-
# one Message ID. The message_ids method call has been left in however as it will only
-
# return the one message id, ie, an array of length 1.
-
#
-
# Note that, the #message_ids method will return an array of message IDs without the
-
# enclosing angle brackets which per RFC are not syntactically part of the message id.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.message_id = '<F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom>'
-
# mail.message_id #=> '<F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom>'
-
# mail[:message_id] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::MessageIdField:0x180e1c4
-
# mail['message_id'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::MessageIdField:0x180e1c4
-
# mail['Message-ID'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::MessageIdField:0x180e1c4
-
#
-
# mail[:message_id].message_id #=> 'F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom'
-
# mail[:message_id].message_ids #=> ['F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom']
-
#
-
1
require 'mail/fields/common/common_message_id'
-
-
1
module Mail
-
1
class MessageIdField < StructuredField
-
-
1
include Mail::CommonMessageId
-
-
1
FIELD_NAME = 'message-id'
-
1
CAPITALIZED_FIELD = 'Message-ID'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
@uniq = 1
-
if value.blank?
-
self.name = CAPITALIZED_FIELD
-
self.value = generate_message_id
-
else
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
end
-
self.parse
-
self
-
-
end
-
-
1
def name
-
'Message-ID'
-
end
-
-
1
def message_ids
-
[message_id]
-
end
-
-
1
def to_s
-
"<#{message_id}>"
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
1
private
-
-
1
def generate_message_id
-
"<#{Mail.random_tag}@#{::Socket.gethostname}.mail>"
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
#
-
#
-
1
module Mail
-
1
class MimeVersionField < StructuredField
-
-
1
FIELD_NAME = 'mime-version'
-
1
CAPITALIZED_FIELD = 'Mime-Version'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
if value.blank?
-
value = '1.0'
-
end
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
-
end
-
-
1
def parse(val = value)
-
unless val.blank?
-
@element = Mail::MimeVersionElement.new(val)
-
end
-
end
-
-
1
def element
-
@element ||= Mail::MimeVersionElement.new(value)
-
end
-
-
1
def version
-
"#{element.major}.#{element.minor}"
-
end
-
-
1
def major
-
element.major.to_i
-
end
-
-
1
def minor
-
element.minor.to_i
-
end
-
-
1
def encoded
-
"#{CAPITALIZED_FIELD}: #{version}\r\n"
-
end
-
-
1
def decoded
-
version
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# trace = [return]
-
# 1*received
-
#
-
# return = "Return-Path:" path CRLF
-
#
-
# path = ([CFWS] "<" ([CFWS] / addr-spec) ">" [CFWS]) /
-
# obs-path
-
#
-
# received = "Received:" name-val-list ";" date-time CRLF
-
#
-
# name-val-list = [CFWS] [name-val-pair *(CFWS name-val-pair)]
-
#
-
# name-val-pair = item-name CFWS item-value
-
#
-
# item-name = ALPHA *(["-"] (ALPHA / DIGIT))
-
#
-
# item-value = 1*angle-addr / addr-spec /
-
# atom / domain / msg-id
-
#
-
1
module Mail
-
1
class ReceivedField < StructuredField
-
-
1
FIELD_NAME = 'received'
-
1
CAPITALIZED_FIELD = 'Received'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
-
end
-
-
1
def parse(val = value)
-
unless val.blank?
-
@element = Mail::ReceivedElement.new(val)
-
end
-
end
-
-
1
def element
-
@element ||= Mail::ReceivedElement.new(value)
-
end
-
-
1
def date_time
-
@datetime ||= ::DateTime.parse("#{element.date_time}")
-
end
-
-
1
def info
-
element.info
-
end
-
-
1
def formatted_date
-
date_time.strftime("%a, %d %b %Y %H:%M:%S ") + date_time.zone.delete(':')
-
end
-
-
1
def encoded
-
if value.blank?
-
"#{CAPITALIZED_FIELD}: \r\n"
-
else
-
"#{CAPITALIZED_FIELD}: #{info}; #{formatted_date}\r\n"
-
end
-
end
-
-
1
def decoded
-
if value.blank?
-
""
-
else
-
"#{info}; #{formatted_date}"
-
end
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = References Field
-
#
-
# The References field inherits references StructuredField and handles the References: header
-
# field in the email.
-
#
-
# Sending references to a mail message will instantiate a Mail::Field object that
-
# has a ReferencesField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Note that, the #message_ids method will return an array of message IDs without the
-
# enclosing angle brackets which per RFC are not syntactically part of the message id.
-
#
-
# Only one References field can appear in a header, though it can have multiple
-
# Message IDs.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.references = '<F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom>'
-
# mail.references #=> '<F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom>'
-
# mail[:references] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ReferencesField:0x180e1c4
-
# mail['references'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ReferencesField:0x180e1c4
-
# mail['References'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ReferencesField:0x180e1c4
-
#
-
# mail[:references].message_ids #=> ['F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom']
-
#
-
1
require 'mail/fields/common/common_message_id'
-
-
1
module Mail
-
1
class ReferencesField < StructuredField
-
-
1
include CommonMessageId
-
-
1
FIELD_NAME = 'references'
-
1
CAPITALIZED_FIELD = 'References'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
value = value.join("\r\n\s") if value.is_a?(Array)
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Reply-To Field
-
#
-
# The Reply-To field inherits reply-to StructuredField and handles the Reply-To: header
-
# field in the email.
-
#
-
# Sending reply_to to a mail message will instantiate a Mail::Field object that
-
# has a ReplyToField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Reply-To field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.reply_to = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.reply_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:reply_to] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ReplyToField:0x180e1c4
-
# mail['reply-to'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ReplyToField:0x180e1c4
-
# mail['Reply-To'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ReplyToField:0x180e1c4
-
#
-
# mail[:reply_to].encoded #=> 'Reply-To: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:reply_to].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:reply_to].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:reply_to].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
1
require 'mail/fields/common/common_address'
-
-
1
module Mail
-
1
class ReplyToField < StructuredField
-
-
1
include Mail::CommonAddress
-
-
1
FIELD_NAME = 'reply-to'
-
1
CAPITALIZED_FIELD = 'Reply-To'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Resent-Bcc Field
-
#
-
# The Resent-Bcc field inherits resent-bcc StructuredField and handles the
-
# Resent-Bcc: header field in the email.
-
#
-
# Sending resent_bcc to a mail message will instantiate a Mail::Field object that
-
# has a ResentBccField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Resent-Bcc field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.resent_bcc = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_bcc] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentBccField:0x180e1c4
-
# mail['resent-bcc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentBccField:0x180e1c4
-
# mail['Resent-Bcc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentBccField:0x180e1c4
-
#
-
# mail[:resent_bcc].encoded #=> 'Resent-Bcc: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:resent_bcc].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:resent_bcc].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_bcc].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
1
require 'mail/fields/common/common_address'
-
-
1
module Mail
-
1
class ResentBccField < StructuredField
-
-
1
include Mail::CommonAddress
-
-
1
FIELD_NAME = 'resent-bcc'
-
1
CAPITALIZED_FIELD = 'Resent-Bcc'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Resent-Cc Field
-
#
-
# The Resent-Cc field inherits resent-cc StructuredField and handles the Resent-Cc: header
-
# field in the email.
-
#
-
# Sending resent_cc to a mail message will instantiate a Mail::Field object that
-
# has a ResentCcField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Resent-Cc field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.resent_cc = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_cc] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentCcField:0x180e1c4
-
# mail['resent-cc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentCcField:0x180e1c4
-
# mail['Resent-Cc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentCcField:0x180e1c4
-
#
-
# mail[:resent_cc].encoded #=> 'Resent-Cc: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:resent_cc].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:resent_cc].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_cc].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
1
require 'mail/fields/common/common_address'
-
-
1
module Mail
-
1
class ResentCcField < StructuredField
-
-
1
include Mail::CommonAddress
-
-
1
FIELD_NAME = 'resent-cc'
-
1
CAPITALIZED_FIELD = 'Resent-Cc'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# resent-date = "Resent-Date:" date-time CRLF
-
1
require 'mail/fields/common/common_date'
-
-
1
module Mail
-
1
class ResentDateField < StructuredField
-
-
1
include Mail::CommonDate
-
-
1
FIELD_NAME = 'resent-date'
-
1
CAPITALIZED_FIELD = 'Resent-Date'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
if value.blank?
-
value = ::DateTime.now.strftime('%a, %d %b %Y %H:%M:%S %z')
-
else
-
value = strip_field(FIELD_NAME, value)
-
value = ::DateTime.parse(value.to_s).strftime('%a, %d %b %Y %H:%M:%S %z')
-
end
-
super(CAPITALIZED_FIELD, value, charset)
-
self
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Resent-From Field
-
#
-
# The Resent-From field inherits resent-from StructuredField and handles the Resent-From: header
-
# field in the email.
-
#
-
# Sending resent_from to a mail message will instantiate a Mail::Field object that
-
# has a ResentFromField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Resent-From field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.resent_from = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_from] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentFromField:0x180e1c4
-
# mail['resent-from'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentFromField:0x180e1c4
-
# mail['Resent-From'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentFromField:0x180e1c4
-
#
-
# mail[:resent_from].encoded #=> 'Resent-From: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:resent_from].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:resent_from].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_from].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
1
require 'mail/fields/common/common_address'
-
-
1
module Mail
-
1
class ResentFromField < StructuredField
-
-
1
include Mail::CommonAddress
-
-
1
FIELD_NAME = 'resent-from'
-
1
CAPITALIZED_FIELD = 'Resent-From'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# resent-msg-id = "Resent-Message-ID:" msg-id CRLF
-
1
require 'mail/fields/common/common_message_id'
-
-
1
module Mail
-
1
class ResentMessageIdField < StructuredField
-
-
1
include CommonMessageId
-
-
1
FIELD_NAME = 'resent-message-id'
-
1
CAPITALIZED_FIELD = 'Resent-Message-ID'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
1
def name
-
'Resent-Message-ID'
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Resent-Sender Field
-
#
-
# The Resent-Sender field inherits resent-sender StructuredField and handles the Resent-Sender: header
-
# field in the email.
-
#
-
# Sending resent_sender to a mail message will instantiate a Mail::Field object that
-
# has a ResentSenderField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Resent-Sender field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.resent_sender = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_sender #=> ['mikel@test.lindsaar.net']
-
# mail[:resent_sender] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentSenderField:0x180e1c4
-
# mail['resent-sender'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentSenderField:0x180e1c4
-
# mail['Resent-Sender'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentSenderField:0x180e1c4
-
#
-
# mail.resent_sender.to_s #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_sender.addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail.resent_sender.formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
1
require 'mail/fields/common/common_address'
-
-
1
module Mail
-
1
class ResentSenderField < StructuredField
-
-
1
include Mail::CommonAddress
-
-
1
FIELD_NAME = 'resent-sender'
-
1
CAPITALIZED_FIELD = 'Resent-Sender'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
1
def addresses
-
[address.address]
-
end
-
-
1
def address
-
tree.addresses.first
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Resent-To Field
-
#
-
# The Resent-To field inherits resent-to StructuredField and handles the Resent-To: header
-
# field in the email.
-
#
-
# Sending resent_to to a mail message will instantiate a Mail::Field object that
-
# has a ResentToField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Resent-To field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.resent_to = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_to] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentToField:0x180e1c4
-
# mail['resent-to'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentToField:0x180e1c4
-
# mail['Resent-To'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentToField:0x180e1c4
-
#
-
# mail[:resent_to].encoded #=> 'Resent-To: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:resent_to].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:resent_to].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_to].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
1
require 'mail/fields/common/common_address'
-
-
1
module Mail
-
1
class ResentToField < StructuredField
-
-
1
include Mail::CommonAddress
-
-
1
FIELD_NAME = 'resent-to'
-
1
CAPITALIZED_FIELD = 'Resent-To'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# 4.4.3. REPLY-TO / RESENT-REPLY-TO
-
#
-
# Note: The "Return-Path" field is added by the mail transport
-
# service, at the time of final deliver. It is intended
-
# to identify a path back to the orginator of the mes-
-
# sage. The "Reply-To" field is added by the message
-
# originator and is intended to direct replies.
-
#
-
# trace = [return]
-
# 1*received
-
#
-
# return = "Return-Path:" path CRLF
-
#
-
# path = ([CFWS] "<" ([CFWS] / addr-spec) ">" [CFWS]) /
-
# obs-path
-
#
-
# received = "Received:" name-val-list ";" date-time CRLF
-
#
-
# name-val-list = [CFWS] [name-val-pair *(CFWS name-val-pair)]
-
#
-
# name-val-pair = item-name CFWS item-value
-
#
-
# item-name = ALPHA *(["-"] (ALPHA / DIGIT))
-
#
-
# item-value = 1*angle-addr / addr-spec /
-
# atom / domain / msg-id
-
#
-
1
require 'mail/fields/common/common_address'
-
-
1
module Mail
-
1
class ReturnPathField < StructuredField
-
-
1
include Mail::CommonAddress
-
-
1
FIELD_NAME = 'return-path'
-
1
CAPITALIZED_FIELD = 'Return-Path'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
value = nil if value == '<>'
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
1
def encoded
-
"#{CAPITALIZED_FIELD}: <#{address}>\r\n"
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
1
def address
-
addresses.first
-
end
-
-
1
def default
-
address
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Sender Field
-
#
-
# The Sender field inherits sender StructuredField and handles the Sender: header
-
# field in the email.
-
#
-
# Sending sender to a mail message will instantiate a Mail::Field object that
-
# has a SenderField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Sender field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.sender = 'Mikel Lindsaar <mikel@test.lindsaar.net>'
-
# mail.sender #=> 'mikel@test.lindsaar.net'
-
# mail[:sender] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::SenderField:0x180e1c4
-
# mail['sender'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::SenderField:0x180e1c4
-
# mail['Sender'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::SenderField:0x180e1c4
-
#
-
# mail[:sender].encoded #=> "Sender: Mikel Lindsaar <mikel@test.lindsaar.net>\r\n"
-
# mail[:sender].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>'
-
# mail[:sender].addresses #=> ['mikel@test.lindsaar.net']
-
# mail[:sender].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>']
-
#
-
1
require 'mail/fields/common/common_address'
-
-
1
module Mail
-
1
class SenderField < StructuredField
-
-
1
include Mail::CommonAddress
-
-
1
FIELD_NAME = 'sender'
-
1
CAPITALIZED_FIELD = 'Sender'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
1
def addresses
-
[address.address]
-
end
-
-
1
def address
-
tree.addresses.first
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
1
def default
-
address.address
-
end
-
-
end
-
end
-
# encoding: utf-8
-
1
require 'mail/fields/common/common_field'
-
-
1
module Mail
-
# Provides access to a structured header field
-
#
-
# ===Per RFC 2822:
-
# 2.2.2. Structured Header Field Bodies
-
#
-
# Some field bodies in this standard have specific syntactical
-
# structure more restrictive than the unstructured field bodies
-
# described above. These are referred to as "structured" field bodies.
-
# Structured field bodies are sequences of specific lexical tokens as
-
# described in sections 3 and 4 of this standard. Many of these tokens
-
# are allowed (according to their syntax) to be introduced or end with
-
# comments (as described in section 3.2.3) as well as the space (SP,
-
# ASCII value 32) and horizontal tab (HTAB, ASCII value 9) characters
-
# (together known as the white space characters, WSP), and those WSP
-
# characters are subject to header "folding" and "unfolding" as
-
# described in section 2.2.3. Semantic analysis of structured field
-
# bodies is given along with their syntax.
-
1
class StructuredField
-
-
1
include Mail::CommonField
-
1
include Mail::Utilities
-
-
1
def initialize(name = nil, value = nil, charset = nil)
-
self.name = name
-
self.value = value
-
self.charset = charset
-
self
-
end
-
-
1
def charset
-
@charset
-
end
-
-
1
def charset=(val)
-
@charset = val
-
end
-
-
1
def default
-
decoded
-
end
-
-
1
def errors
-
[]
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# subject = "Subject:" unstructured CRLF
-
1
module Mail
-
1
class SubjectField < UnstructuredField
-
-
1
FIELD_NAME = 'subject'
-
1
CAPITALIZED_FIELD = "Subject"
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = To Field
-
#
-
# The To field inherits to StructuredField and handles the To: header
-
# field in the email.
-
#
-
# Sending to to a mail message will instantiate a Mail::Field object that
-
# has a ToField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one To field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.to = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:to] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ToField:0x180e1c4
-
# mail['to'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ToField:0x180e1c4
-
# mail['To'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ToField:0x180e1c4
-
#
-
# mail[:to].encoded #=> 'To: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:to].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:to].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:to].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
1
require 'mail/fields/common/common_address'
-
-
1
module Mail
-
1
class ToField < StructuredField
-
-
1
include Mail::CommonAddress
-
-
1
FIELD_NAME = 'to'
-
1
CAPITALIZED_FIELD = 'To'
-
-
1
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
1
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
1
require 'mail/fields/common/common_field'
-
-
1
module Mail
-
# Provides access to an unstructured header field
-
#
-
# ===Per RFC 2822:
-
# 2.2.1. Unstructured Header Field Bodies
-
#
-
# Some field bodies in this standard are defined simply as
-
# "unstructured" (which is specified below as any US-ASCII characters,
-
# except for CR and LF) with no further restrictions. These are
-
# referred to as unstructured field bodies. Semantically, unstructured
-
# field bodies are simply to be treated as a single line of characters
-
# with no further processing (except for header "folding" and
-
# "unfolding" as described in section 2.2.3).
-
1
class UnstructuredField
-
-
1
include Mail::CommonField
-
1
include Mail::Utilities
-
-
1
attr_accessor :charset
-
1
attr_reader :errors
-
-
1
def initialize(name, value, charset = nil)
-
@errors = []
-
-
if value.is_a?(Array)
-
# Probably has arrived here from a failed parse of an AddressList Field
-
value = value.join(', ')
-
else
-
# Ensure we are dealing with a string
-
value = value.to_s
-
end
-
-
if charset
-
self.charset = charset
-
else
-
if value.respond_to?(:encoding)
-
self.charset = value.encoding
-
else
-
self.charset = $KCODE
-
end
-
end
-
self.name = name
-
self.value = value
-
self
-
end
-
-
1
def encoded
-
do_encode
-
end
-
-
1
def decoded
-
do_decode
-
end
-
-
1
def default
-
decoded
-
end
-
-
1
def parse # An unstructured field does not parse
-
self
-
end
-
-
1
private
-
-
1
def do_encode
-
value.nil? ? '' : "#{wrapped_value}\r\n"
-
end
-
-
1
def do_decode
-
value.blank? ? nil : Encodings.decode_encode(value, :decode)
-
end
-
-
# 2.2.3. Long Header Fields
-
#
-
# Each header field is logically a single line of characters comprising
-
# the field name, the colon, and the field body. For convenience
-
# however, and to deal with the 998/78 character limitations per line,
-
# the field body portion of a header field can be split into a multiple
-
# line representation; this is called "folding". The general rule is
-
# that wherever this standard allows for folding white space (not
-
# simply WSP characters), a CRLF may be inserted before any WSP. For
-
# example, the header field:
-
#
-
# Subject: This is a test
-
#
-
# can be represented as:
-
#
-
# Subject: This
-
# is a test
-
#
-
# Note: Though structured field bodies are defined in such a way that
-
# folding can take place between many of the lexical tokens (and even
-
# within some of the lexical tokens), folding SHOULD be limited to
-
# placing the CRLF at higher-level syntactic breaks. For instance, if
-
# a field body is defined as comma-separated values, it is recommended
-
# that folding occur after the comma separating the structured items in
-
# preference to other places where the field could be folded, even if
-
# it is allowed elsewhere.
-
1
def wrapped_value # :nodoc:
-
wrap_lines(name, fold("#{name}: ".length))
-
end
-
-
# 6.2. Display of 'encoded-word's
-
#
-
# When displaying a particular header field that contains multiple
-
# 'encoded-word's, any 'linear-white-space' that separates a pair of
-
# adjacent 'encoded-word's is ignored. (This is to allow the use of
-
# multiple 'encoded-word's to represent long strings of unencoded text,
-
# without having to separate 'encoded-word's where spaces occur in the
-
# unencoded text.)
-
1
def wrap_lines(name, folded_lines)
-
result = ["#{name}: #{folded_lines.shift}"]
-
result.concat(folded_lines)
-
result.join("\r\n\s")
-
end
-
-
1
def fold(prepend = 0) # :nodoc:
-
encoding = normalized_encoding
-
decoded_string = decoded.to_s
-
should_encode = decoded_string.not_ascii_only?
-
if should_encode
-
first = true
-
words = decoded_string.split(/[ \t]/).map do |word|
-
if first
-
first = !first
-
else
-
word = " " << word
-
end
-
if word.not_ascii_only?
-
word
-
else
-
word.scan(/.{7}|.+$/)
-
end
-
end.flatten
-
else
-
words = decoded_string.split(/[ \t]/)
-
end
-
-
folded_lines = []
-
while !words.empty?
-
limit = 78 - prepend
-
limit = limit - 7 - encoding.length if should_encode
-
line = ""
-
while !words.empty?
-
break unless word = words.first.dup
-
word.encode!(charset) if charset && word.respond_to?(:encode!)
-
word = encode(word) if should_encode
-
word = encode_crlf(word)
-
# Skip to next line if we're going to go past the limit
-
# Unless this is the first word, in which case we're going to add it anyway
-
# Note: This means that a word that's longer than 998 characters is going to break the spec. Please fix if this is a problem for you.
-
# (The fix, it seems, would be to use encoded-word encoding on it, because that way you can break it across multiple lines and
-
# the linebreak will be ignored)
-
break if !line.empty? && (line.length + word.length + 1 > limit)
-
# Remove the word from the queue ...
-
words.shift
-
# Add word separator
-
line << " " unless (line.empty? || should_encode)
-
# ... add it in encoded form to the current line
-
line << word
-
end
-
# Encode the line if necessary
-
line = "=?#{encoding}?Q?#{line}?=" if should_encode
-
# Add the line to the output and reset the prepend
-
folded_lines << line
-
prepend = 0
-
end
-
folded_lines
-
end
-
-
1
def encode(value)
-
value = [value].pack("M").gsub("=\n", '')
-
value.gsub!(/"/, '=22')
-
value.gsub!(/\(/, '=28')
-
value.gsub!(/\)/, '=29')
-
value.gsub!(/\?/, '=3F')
-
value.gsub!(/_/, '=5F')
-
value.gsub!(/ /, '_')
-
value
-
end
-
-
1
def encode_crlf(value)
-
value.gsub!("\r", '=0D')
-
value.gsub!("\n", '=0A')
-
value
-
end
-
-
1
def normalized_encoding
-
encoding = charset.to_s.upcase.gsub('_', '-')
-
encoding = 'UTF-8' if encoding == 'UTF8' # Ruby 1.8.x and $KCODE == 'u'
-
encoding
-
end
-
-
end
-
end
-
# encoding: utf-8
-
1
module Mail
-
-
# Provides access to a header object.
-
#
-
# ===Per RFC2822
-
#
-
# 2.2. Header Fields
-
#
-
# Header fields are lines composed of a field name, followed by a colon
-
# (":"), followed by a field body, and terminated by CRLF. A field
-
# name MUST be composed of printable US-ASCII characters (i.e.,
-
# characters that have values between 33 and 126, inclusive), except
-
# colon. A field body may be composed of any US-ASCII characters,
-
# except for CR and LF. However, a field body may contain CRLF when
-
# used in header "folding" and "unfolding" as described in section
-
# 2.2.3. All field bodies MUST conform to the syntax described in
-
# sections 3 and 4 of this standard.
-
1
class Header
-
1
include Patterns
-
1
include Utilities
-
1
include Enumerable
-
-
1
@@maximum_amount = 1000
-
-
# Large amount of headers in Email might create extra high CPU load
-
# Use this parameter to limit number of headers that will be parsed by
-
# mail library.
-
# Default: 1000
-
1
def self.maximum_amount
-
@@maximum_amount
-
end
-
-
1
def self.maximum_amount=(value)
-
@@maximum_amount = value
-
end
-
-
# Creates a new header object.
-
#
-
# Accepts raw text or nothing. If given raw text will attempt to parse
-
# it and split it into the various fields, instantiating each field as
-
# it goes.
-
#
-
# If it finds a field that should be a structured field (such as content
-
# type), but it fails to parse it, it will simply make it an unstructured
-
# field and leave it alone. This will mean that the data is preserved but
-
# no automatic processing of that field will happen. If you find one of
-
# these cases, please make a patch and send it in, or at the least, send
-
# me the example so we can fix it.
-
1
def initialize(header_text = nil, charset = nil)
-
@errors = []
-
@charset = charset
-
self.raw_source = header_text.to_crlf.lstrip
-
split_header if header_text
-
end
-
-
# The preserved raw source of the header as you passed it in, untouched
-
# for your Regexing glory.
-
1
def raw_source
-
@raw_source
-
end
-
-
# Returns an array of all the fields in the header in order that they
-
# were read in.
-
1
def fields
-
@fields ||= FieldList.new
-
end
-
-
# 3.6. Field definitions
-
#
-
# It is important to note that the header fields are not guaranteed to
-
# be in a particular order. They may appear in any order, and they
-
# have been known to be reordered occasionally when transported over
-
# the Internet. However, for the purposes of this standard, header
-
# fields SHOULD NOT be reordered when a message is transported or
-
# transformed. More importantly, the trace header fields and resent
-
# header fields MUST NOT be reordered, and SHOULD be kept in blocks
-
# prepended to the message. See sections 3.6.6 and 3.6.7 for more
-
# information.
-
#
-
# Populates the fields container with Field objects in the order it
-
# receives them in.
-
#
-
# Acceps an array of field string values, for example:
-
#
-
# h = Header.new
-
# h.fields = ['From: mikel@me.com', 'To: bob@you.com']
-
1
def fields=(unfolded_fields)
-
@fields = Mail::FieldList.new
-
warn "Warning: more than #{self.class.maximum_amount} header fields only using the first #{self.class.maximum_amount}" if unfolded_fields.length > self.class.maximum_amount
-
unfolded_fields[0..(self.class.maximum_amount-1)].each do |field|
-
-
field = Field.new(field, nil, charset)
-
field.errors.each { |error| self.errors << error }
-
if limited_field?(field.name) && (selected = select_field_for(field.name)) && selected.any?
-
selected.first.update(field.name, field.value)
-
else
-
@fields << field
-
end
-
end
-
-
end
-
-
1
def errors
-
@errors
-
end
-
-
# 3.6. Field definitions
-
#
-
# The following table indicates limits on the number of times each
-
# field may occur in a message header as well as any special
-
# limitations on the use of those fields. An asterisk next to a value
-
# in the minimum or maximum column indicates that a special restriction
-
# appears in the Notes column.
-
#
-
# <snip table from 3.6>
-
#
-
# As per RFC, many fields can appear more than once, we will return a string
-
# of the value if there is only one header, or if there is more than one
-
# matching header, will return an array of values in order that they appear
-
# in the header ordered from top to bottom.
-
#
-
# Example:
-
#
-
# h = Header.new
-
# h.fields = ['To: mikel@me.com', 'X-Mail-SPAM: 15', 'X-Mail-SPAM: 20']
-
# h['To'] #=> 'mikel@me.com'
-
# h['X-Mail-SPAM'] #=> ['15', '20']
-
1
def [](name)
-
name = dasherize(name).downcase
-
selected = select_field_for(name)
-
case
-
when selected.length > 1
-
selected.map { |f| f }
-
when !selected.blank?
-
selected.first
-
else
-
nil
-
end
-
end
-
-
# Sets the FIRST matching field in the header to passed value, or deletes
-
# the FIRST field matched from the header if passed nil
-
#
-
# Example:
-
#
-
# h = Header.new
-
# h.fields = ['To: mikel@me.com', 'X-Mail-SPAM: 15', 'X-Mail-SPAM: 20']
-
# h['To'] = 'bob@you.com'
-
# h['To'] #=> 'bob@you.com'
-
# h['X-Mail-SPAM'] = '10000'
-
# h['X-Mail-SPAM'] # => ['15', '20', '10000']
-
# h['X-Mail-SPAM'] = nil
-
# h['X-Mail-SPAM'] # => nil
-
1
def []=(name, value)
-
name = dasherize(name)
-
if name.include?(':')
-
raise ArgumentError, "Header names may not contain a colon: #{name.inspect}"
-
end
-
fn = name.downcase
-
selected = select_field_for(fn)
-
-
case
-
# User wants to delete the field
-
when !selected.blank? && value == nil
-
fields.delete_if { |f| selected.include?(f) }
-
-
# User wants to change the field
-
when !selected.blank? && limited_field?(fn)
-
selected.first.update(fn, value)
-
-
# User wants to create the field
-
else
-
# Need to insert in correct order for trace fields
-
self.fields << Field.new(name.to_s, value, charset)
-
end
-
if dasherize(fn) == "content-type"
-
# Update charset if specified in Content-Type
-
params = self[:content_type].parameters rescue nil
-
@charset = params && params[:charset]
-
end
-
end
-
-
1
def charset
-
@charset
-
end
-
-
1
def charset=(val)
-
params = self[:content_type].parameters rescue nil
-
if params
-
params[:charset] = val
-
end
-
@charset = val
-
end
-
-
1
LIMITED_FIELDS = %w[ date from sender reply-to to cc bcc
-
message-id in-reply-to references subject
-
return-path content-type mime-version
-
content-transfer-encoding content-description
-
content-id content-disposition content-location]
-
-
1
def encoded
-
buffer = ''
-
buffer.force_encoding('us-ascii') if buffer.respond_to?(:force_encoding)
-
fields.each do |field|
-
buffer << field.encoded
-
end
-
buffer
-
end
-
-
1
def to_s
-
encoded
-
end
-
-
1
def decoded
-
raise NoMethodError, 'Can not decode an entire header as there could be character set conflicts, try calling #decoded on the various fields.'
-
end
-
-
1
def field_summary
-
fields.map { |f| "<#{f.name}: #{f.value}>" }.join(", ")
-
end
-
-
# Returns true if the header has a Message-ID defined (empty or not)
-
1
def has_message_id?
-
!fields.select { |f| f.responsible_for?('Message-ID') }.empty?
-
end
-
-
# Returns true if the header has a Content-ID defined (empty or not)
-
1
def has_content_id?
-
!fields.select { |f| f.responsible_for?('Content-ID') }.empty?
-
end
-
-
# Returns true if the header has a Date defined (empty or not)
-
1
def has_date?
-
!fields.select { |f| f.responsible_for?('Date') }.empty?
-
end
-
-
# Returns true if the header has a MIME version defined (empty or not)
-
1
def has_mime_version?
-
!fields.select { |f| f.responsible_for?('Mime-Version') }.empty?
-
end
-
-
1
private
-
-
1
def raw_source=(val)
-
@raw_source = val
-
end
-
-
# 2.2.3. Long Header Fields
-
#
-
# The process of moving from this folded multiple-line representation
-
# of a header field to its single line representation is called
-
# "unfolding". Unfolding is accomplished by simply removing any CRLF
-
# that is immediately followed by WSP. Each header field should be
-
# treated in its unfolded form for further syntactic and semantic
-
# evaluation.
-
1
def unfold(string)
-
string.gsub(/#{CRLF}#{WSP}+/, ' ').gsub(/#{WSP}+/, ' ')
-
end
-
-
# Returns the header with all the folds removed
-
1
def unfolded_header
-
@unfolded_header ||= unfold(raw_source)
-
end
-
-
# Splits an unfolded and line break cleaned header into individual field
-
# strings.
-
1
def split_header
-
self.fields = unfolded_header.split(CRLF)
-
end
-
-
1
def select_field_for(name)
-
fields.select { |f| f.responsible_for?(name) }
-
end
-
-
1
def limited_field?(name)
-
LIMITED_FIELDS.include?(name.to_s.downcase)
-
end
-
-
# Enumerable support; yield each field in order to the block if there is one,
-
# or return an Enumerator for them if there isn't.
-
1
def each( &block )
-
return self.fields.each( &block ) if block
-
self.fields.each
-
end
-
-
end
-
end
-
# encoding: utf-8
-
-
# This is an almost cut and paste from ActiveSupport v3.0.6, copied in here so that Mail
-
# itself does not depend on ActiveSupport to avoid versioning conflicts
-
-
1
module Mail
-
1
class IndifferentHash < Hash
-
-
1
def initialize(constructor = {})
-
if constructor.is_a?(Hash)
-
super()
-
update(constructor)
-
else
-
super(constructor)
-
end
-
end
-
-
1
def default(key = nil)
-
if key.is_a?(Symbol) && include?(key = key.to_s)
-
self[key]
-
else
-
super
-
end
-
end
-
-
1
def self.new_from_hash_copying_default(hash)
-
IndifferentHash.new(hash).tap do |new_hash|
-
new_hash.default = hash.default
-
end
-
end
-
-
1
alias_method :regular_writer, :[]= unless method_defined?(:regular_writer)
-
1
alias_method :regular_update, :update unless method_defined?(:regular_update)
-
-
# Assigns a new value to the hash:
-
#
-
# hash = HashWithIndifferentAccess.new
-
# hash[:key] = "value"
-
#
-
1
def []=(key, value)
-
regular_writer(convert_key(key), convert_value(value))
-
end
-
-
1
alias_method :store, :[]=
-
-
# Updates the instantized hash with values from the second:
-
#
-
# hash_1 = HashWithIndifferentAccess.new
-
# hash_1[:key] = "value"
-
#
-
# hash_2 = HashWithIndifferentAccess.new
-
# hash_2[:key] = "New Value!"
-
#
-
# hash_1.update(hash_2) # => {"key"=>"New Value!"}
-
#
-
1
def update(other_hash)
-
other_hash.each_pair { |key, value| regular_writer(convert_key(key), convert_value(value)) }
-
self
-
end
-
-
1
alias_method :merge!, :update
-
-
# Checks the hash for a key matching the argument passed in:
-
#
-
# hash = HashWithIndifferentAccess.new
-
# hash["key"] = "value"
-
# hash.key? :key # => true
-
# hash.key? "key" # => true
-
#
-
1
def key?(key)
-
super(convert_key(key))
-
end
-
-
1
alias_method :include?, :key?
-
1
alias_method :has_key?, :key?
-
1
alias_method :member?, :key?
-
-
# Fetches the value for the specified key, same as doing hash[key]
-
1
def fetch(key, *extras)
-
super(convert_key(key), *extras)
-
end
-
-
# Returns an array of the values at the specified indices:
-
#
-
# hash = HashWithIndifferentAccess.new
-
# hash[:a] = "x"
-
# hash[:b] = "y"
-
# hash.values_at("a", "b") # => ["x", "y"]
-
#
-
1
def values_at(*indices)
-
indices.collect {|key| self[convert_key(key)]}
-
end
-
-
# Returns an exact copy of the hash.
-
1
def dup
-
IndifferentHash.new(self)
-
end
-
-
# Merges the instantized and the specified hashes together, giving precedence to the values from the second hash
-
# Does not overwrite the existing hash.
-
1
def merge(hash)
-
self.dup.update(hash)
-
end
-
-
# Performs the opposite of merge, with the keys and values from the first hash taking precedence over the second.
-
# This overloaded definition prevents returning a regular hash, if reverse_merge is called on a HashWithDifferentAccess.
-
1
def reverse_merge(other_hash)
-
super self.class.new_from_hash_copying_default(other_hash)
-
end
-
-
1
def reverse_merge!(other_hash)
-
replace(reverse_merge( other_hash ))
-
end
-
-
# Removes a specified key from the hash.
-
1
def delete(key)
-
super(convert_key(key))
-
end
-
-
1
def stringify_keys!; self end
-
1
def stringify_keys; dup end
-
1
def symbolize_keys; to_hash.symbolize_keys end
-
1
def to_options!; self end
-
-
1
def to_hash
-
Hash.new(default).merge!(self)
-
end
-
-
1
protected
-
-
1
def convert_key(key)
-
key.kind_of?(Symbol) ? key.to_s : key
-
end
-
-
1
def convert_value(value)
-
if value.class == Hash
-
self.class.new_from_hash_copying_default(value)
-
elsif value.is_a?(Array)
-
value.dup.replace(value.map { |e| convert_value(e) })
-
else
-
value
-
end
-
end
-
-
end
-
end
-
# encoding: utf-8
-
1
module Mail
-
-
# Allows you to create a new Mail::Message object.
-
#
-
# You can make an email via passing a string or passing a block.
-
#
-
# For example, the following two examples will create the same email
-
# message:
-
#
-
# Creating via a string:
-
#
-
# string = "To: mikel@test.lindsaar.net\r\n"
-
# string << "From: bob@test.lindsaar.net\r\n"
-
# string << "Subject: This is an email\r\n"
-
# string << "\r\n"
-
# string << "This is the body"
-
# Mail.new(string)
-
#
-
# Or creating via a block:
-
#
-
# message = Mail.new do
-
# to 'mikel@test.lindsaar.net'
-
# from 'bob@test.lindsaar.net'
-
# subject 'This is an email'
-
# body 'This is the body'
-
# end
-
#
-
# Or creating via a hash (or hash like object):
-
#
-
# message = Mail.new({:to => 'mikel@test.lindsaar.net',
-
# 'from' => 'bob@test.lindsaar.net',
-
# :subject => 'This is an email',
-
# :body => 'This is the body' })
-
#
-
# Note, the hash keys can be strings or symbols, the passed in object
-
# does not need to be a hash, it just needs to respond to :each_pair
-
# and yield each key value pair.
-
#
-
# As a side note, you can also create a new email through creating
-
# a Mail::Message object directly and then passing in values via string,
-
# symbol or direct method calls. See Mail::Message for more information.
-
#
-
# mail = Mail.new
-
# mail.to = 'mikel@test.lindsaar.net'
-
# mail[:from] = 'bob@test.lindsaar.net'
-
# mail['subject'] = 'This is an email'
-
# mail.body = 'This is the body'
-
1
def self.new(*args, &block)
-
Message.new(args, &block)
-
end
-
-
# Sets the default delivery method and retriever method for all new Mail objects.
-
# The delivery_method and retriever_method default to :smtp and :pop3, with defaults
-
# set.
-
#
-
# So sending a new email, if you have an SMTP server running on localhost is
-
# as easy as:
-
#
-
# Mail.deliver do
-
# to 'mikel@test.lindsaar.net'
-
# from 'bob@test.lindsaar.net'
-
# subject 'hi there!'
-
# body 'this is a body'
-
# end
-
#
-
# If you do not specify anything, you will get the following equivalent code set in
-
# every new mail object:
-
#
-
# Mail.defaults do
-
# delivery_method :smtp, { :address => "localhost",
-
# :port => 25,
-
# :domain => 'localhost.localdomain',
-
# :user_name => nil,
-
# :password => nil,
-
# :authentication => nil,
-
# :enable_starttls_auto => true }
-
#
-
# retriever_method :pop3, { :address => "localhost",
-
# :port => 995,
-
# :user_name => nil,
-
# :password => nil,
-
# :enable_ssl => true }
-
# end
-
#
-
# Mail.delivery_method.new #=> Mail::SMTP instance
-
# Mail.retriever_method.new #=> Mail::POP3 instance
-
#
-
# Each mail object inherits the default set in Mail.delivery_method, however, on
-
# a per email basis, you can override the method:
-
#
-
# mail.delivery_method :sendmail
-
#
-
# Or you can override the method and pass in settings:
-
#
-
# mail.delivery_method :sendmail, { :address => 'some.host' }
-
#
-
# You can also just modify the settings:
-
#
-
# mail.delivery_settings = { :address => 'some.host' }
-
#
-
# The passed in hash is just merged against the defaults with +merge!+ and the result
-
# assigned the mail object. So the above example will change only the :address value
-
# of the global smtp_settings to be 'some.host', keeping all other values
-
1
def self.defaults(&block)
-
Configuration.instance.instance_eval(&block)
-
end
-
-
# Returns the delivery method selected, defaults to an instance of Mail::SMTP
-
1
def self.delivery_method
-
Configuration.instance.delivery_method
-
end
-
-
# Returns the retriever method selected, defaults to an instance of Mail::POP3
-
1
def self.retriever_method
-
Configuration.instance.retriever_method
-
end
-
-
# Send an email using the default configuration. You do need to set a default
-
# configuration first before you use self.deliver, if you don't, an appropriate
-
# error will be raised telling you to.
-
#
-
# If you do not specify a delivery type, SMTP will be used.
-
#
-
# Mail.deliver do
-
# to 'mikel@test.lindsaar.net'
-
# from 'ada@test.lindsaar.net'
-
# subject 'This is a test email'
-
# body 'Not much to say here'
-
# end
-
#
-
# You can also do:
-
#
-
# mail = Mail.read('email.eml')
-
# mail.deliver!
-
#
-
# And your email object will be created and sent.
-
1
def self.deliver(*args, &block)
-
mail = self.new(args, &block)
-
mail.deliver
-
mail
-
end
-
-
# Find emails from the default retriever
-
# See Mail::Retriever for a complete documentation.
-
1
def self.find(*args, &block)
-
retriever_method.find(*args, &block)
-
end
-
-
# Finds and then deletes retrieved emails from the default retriever
-
# See Mail::Retriever for a complete documentation.
-
1
def self.find_and_delete(*args, &block)
-
retriever_method.find_and_delete(*args, &block)
-
end
-
-
# Receive the first email(s) from the default retriever
-
# See Mail::Retriever for a complete documentation.
-
1
def self.first(*args, &block)
-
retriever_method.first(*args, &block)
-
end
-
-
# Receive the first email(s) from the default retriever
-
# See Mail::Retriever for a complete documentation.
-
1
def self.last(*args, &block)
-
retriever_method.last(*args, &block)
-
end
-
-
# Receive all emails from the default retriever
-
# See Mail::Retriever for a complete documentation.
-
1
def self.all(*args, &block)
-
retriever_method.all(*args, &block)
-
end
-
-
# Reads in an email message from a path and instantiates it as a new Mail::Message
-
1
def self.read(filename)
-
self.new(File.open(filename, 'rb') { |f| f.read })
-
end
-
-
# Delete all emails from the default retriever
-
# See Mail::Retriever for a complete documentation.
-
1
def self.delete_all(*args, &block)
-
retriever_method.delete_all(*args, &block)
-
end
-
-
# Instantiates a new Mail::Message using a string
-
1
def Mail.read_from_string(mail_as_string)
-
Mail.new(mail_as_string)
-
end
-
-
1
def Mail.connection(&block)
-
retriever_method.connection(&block)
-
end
-
-
# Initialize the observers and interceptors arrays
-
1
@@delivery_notification_observers = []
-
1
@@delivery_interceptors = []
-
-
# You can register an object to be informed of every email that is sent through
-
# this method.
-
#
-
# Your object needs to respond to a single method #delivered_email(mail)
-
# which receives the email that is sent.
-
1
def self.register_observer(observer)
-
unless @@delivery_notification_observers.include?(observer)
-
@@delivery_notification_observers << observer
-
end
-
end
-
-
# You can register an object to be given every mail object that will be sent,
-
# before it is sent. So if you want to add special headers or modify any
-
# email that gets sent through the Mail library, you can do so.
-
#
-
# Your object needs to respond to a single method #delivering_email(mail)
-
# which receives the email that is about to be sent. Make your modifications
-
# directly to this object.
-
1
def self.register_interceptor(interceptor)
-
unless @@delivery_interceptors.include?(interceptor)
-
@@delivery_interceptors << interceptor
-
end
-
end
-
-
1
def self.inform_observers(mail)
-
@@delivery_notification_observers.each do |observer|
-
observer.delivered_email(mail)
-
end
-
end
-
-
1
def self.inform_interceptors(mail)
-
@@delivery_interceptors.each do |interceptor|
-
interceptor.delivering_email(mail)
-
end
-
end
-
-
1
protected
-
-
1
def self.random_tag
-
t = Time.now
-
sprintf('%x%x_%x%x%d%x',
-
t.to_i, t.tv_usec,
-
$$, Thread.current.object_id.abs, self.uniq, rand(255))
-
end
-
-
1
private
-
-
1
def self.something_random
-
1
(Thread.current.object_id * rand(255) / Time.now.to_f).to_s.slice(-3..-1).to_i
-
end
-
-
1
def self.uniq
-
@@uniq += 1
-
end
-
-
1
@@uniq = self.something_random
-
-
end
-
# encoding: utf-8
-
1
require "yaml"
-
-
1
module Mail
-
# The Message class provides a single point of access to all things to do with an
-
# email message.
-
#
-
# You create a new email message by calling the Mail::Message.new method, or just
-
# Mail.new
-
#
-
# A Message object by default has the following objects inside it:
-
#
-
# * A Header object which contains all information and settings of the header of the email
-
# * Body object which contains all parts of the email that are not part of the header, this
-
# includes any attachments, body text, MIME parts etc.
-
#
-
# ==Per RFC2822
-
#
-
# 2.1. General Description
-
#
-
# At the most basic level, a message is a series of characters. A
-
# message that is conformant with this standard is comprised of
-
# characters with values in the range 1 through 127 and interpreted as
-
# US-ASCII characters [ASCII]. For brevity, this document sometimes
-
# refers to this range of characters as simply "US-ASCII characters".
-
#
-
# Note: This standard specifies that messages are made up of characters
-
# in the US-ASCII range of 1 through 127. There are other documents,
-
# specifically the MIME document series [RFC2045, RFC2046, RFC2047,
-
# RFC2048, RFC2049], that extend this standard to allow for values
-
# outside of that range. Discussion of those mechanisms is not within
-
# the scope of this standard.
-
#
-
# Messages are divided into lines of characters. A line is a series of
-
# characters that is delimited with the two characters carriage-return
-
# and line-feed; that is, the carriage return (CR) character (ASCII
-
# value 13) followed immediately by the line feed (LF) character (ASCII
-
# value 10). (The carriage-return/line-feed pair is usually written in
-
# this document as "CRLF".)
-
#
-
# A message consists of header fields (collectively called "the header
-
# of the message") followed, optionally, by a body. The header is a
-
# sequence of lines of characters with special syntax as defined in
-
# this standard. The body is simply a sequence of characters that
-
# follows the header and is separated from the header by an empty line
-
# (i.e., a line with nothing preceding the CRLF).
-
1
class Message
-
-
1
include Patterns
-
1
include Utilities
-
-
# ==Making an email
-
#
-
# You can make an new mail object via a block, passing a string, file or direct assignment.
-
#
-
# ===Making an email via a block
-
#
-
# mail = Mail.new do
-
# from 'mikel@test.lindsaar.net'
-
# to 'you@test.lindsaar.net'
-
# subject 'This is a test email'
-
# body File.read('body.txt')
-
# end
-
#
-
# mail.to_s #=> "From: mikel@test.lindsaar.net\r\nTo: you@...
-
#
-
# ===Making an email via passing a string
-
#
-
# mail = Mail.new("To: mikel@test.lindsaar.net\r\nSubject: Hello\r\n\r\nHi there!")
-
# mail.body.to_s #=> 'Hi there!'
-
# mail.subject #=> 'Hello'
-
# mail.to #=> 'mikel@test.lindsaar.net'
-
#
-
# ===Making an email from a file
-
#
-
# mail = Mail.read('path/to/file.eml')
-
# mail.body.to_s #=> 'Hi there!'
-
# mail.subject #=> 'Hello'
-
# mail.to #=> 'mikel@test.lindsaar.net'
-
#
-
# ===Making an email via assignment
-
#
-
# You can assign values to a mail object via four approaches:
-
#
-
# * Message#field_name=(value)
-
# * Message#field_name(value)
-
# * Message#['field_name']=(value)
-
# * Message#[:field_name]=(value)
-
#
-
# Examples:
-
#
-
# mail = Mail.new
-
# mail['from'] = 'mikel@test.lindsaar.net'
-
# mail[:to] = 'you@test.lindsaar.net'
-
# mail.subject 'This is a test email'
-
# mail.body = 'This is a body'
-
#
-
# mail.to_s #=> "From: mikel@test.lindsaar.net\r\nTo: you@...
-
#
-
1
def initialize(*args, &block)
-
@body = nil
-
@body_raw = nil
-
@separate_parts = false
-
@text_part = nil
-
@html_part = nil
-
@errors = nil
-
@header = nil
-
@charset = 'UTF-8'
-
@defaulted_charset = true
-
-
@smtp_envelope_from = nil
-
@smtp_envelope_to = nil
-
-
@perform_deliveries = true
-
@raise_delivery_errors = true
-
-
@delivery_handler = nil
-
-
@delivery_method = Mail.delivery_method.dup
-
-
@transport_encoding = Mail::Encodings.get_encoding('7bit')
-
-
@mark_for_delete = false
-
-
if args.flatten.first.respond_to?(:each_pair)
-
init_with_hash(args.flatten.first)
-
else
-
init_with_string(args.flatten[0].to_s)
-
end
-
-
if block_given?
-
instance_eval(&block)
-
end
-
-
self
-
end
-
-
# If you assign a delivery handler, mail will call :deliver_mail on the
-
# object you assign to delivery_handler, it will pass itself as the
-
# single argument.
-
#
-
# If you define a delivery_handler, then you are responsible for the
-
# following actions in the delivery cycle:
-
#
-
# * Appending the mail object to Mail.deliveries as you see fit.
-
# * Checking the mail.perform_deliveries flag to decide if you should
-
# actually call :deliver! the mail object or not.
-
# * Checking the mail.raise_delivery_errors flag to decide if you
-
# should raise delivery errors if they occur.
-
# * Actually calling :deliver! (with the bang) on the mail object to
-
# get it to deliver itself.
-
#
-
# A simplest implementation of a delivery_handler would be
-
#
-
# class MyObject
-
#
-
# def initialize
-
# @mail = Mail.new('To: mikel@test.lindsaar.net')
-
# @mail.delivery_handler = self
-
# end
-
#
-
# attr_accessor :mail
-
#
-
# def deliver_mail(mail)
-
# yield
-
# end
-
# end
-
#
-
# Then doing:
-
#
-
# obj = MyObject.new
-
# obj.mail.deliver
-
#
-
# Would cause Mail to call obj.deliver_mail passing itself as a parameter,
-
# which then can just yield and let Mail do its own private do_delivery
-
# method.
-
1
attr_accessor :delivery_handler
-
-
# If set to false, mail will go through the motions of doing a delivery,
-
# but not actually call the delivery method or append the mail object to
-
# the Mail.deliveries collection. Useful for testing.
-
#
-
# Mail.deliveries.size #=> 0
-
# mail.delivery_method :smtp
-
# mail.perform_deliveries = false
-
# mail.deliver # Mail::SMTP not called here
-
# Mail.deliveries.size #=> 0
-
#
-
# If you want to test and query the Mail.deliveries collection to see what
-
# mail you sent, you should set perform_deliveries to true and use
-
# the :test mail delivery_method:
-
#
-
# Mail.deliveries.size #=> 0
-
# mail.delivery_method :test
-
# mail.perform_deliveries = true
-
# mail.deliver
-
# Mail.deliveries.size #=> 1
-
#
-
# This setting is ignored by mail (though still available as a flag) if you
-
# define a delivery_handler
-
1
attr_accessor :perform_deliveries
-
-
# If set to false, mail will silently catch and ignore any exceptions
-
# raised through attempting to deliver an email.
-
#
-
# This setting is ignored by mail (though still available as a flag) if you
-
# define a delivery_handler
-
1
attr_accessor :raise_delivery_errors
-
-
1
def register_for_delivery_notification(observer)
-
STDERR.puts("Message#register_for_delivery_notification is deprecated, please call Mail.register_observer instead")
-
Mail.register_observer(observer)
-
end
-
-
1
def inform_observers
-
Mail.inform_observers(self)
-
end
-
-
1
def inform_interceptors
-
Mail.inform_interceptors(self)
-
end
-
-
# Delivers an mail object.
-
#
-
# Examples:
-
#
-
# mail = Mail.read('file.eml')
-
# mail.deliver
-
1
def deliver
-
inform_interceptors
-
if delivery_handler
-
delivery_handler.deliver_mail(self) { do_delivery }
-
else
-
do_delivery
-
end
-
inform_observers
-
self
-
end
-
-
# This method bypasses checking perform_deliveries and raise_delivery_errors,
-
# so use with caution.
-
#
-
# It still however fires off the intercepters and calls the observers callbacks if they are defined.
-
#
-
# Returns self
-
1
def deliver!
-
inform_interceptors
-
response = delivery_method.deliver!(self)
-
inform_observers
-
delivery_method.settings[:return_response] ? response : self
-
end
-
-
1
def delivery_method(method = nil, settings = {})
-
unless method
-
@delivery_method
-
else
-
@delivery_method = Configuration.instance.lookup_delivery_method(method).new(settings)
-
end
-
end
-
-
1
def reply(*args, &block)
-
self.class.new.tap do |reply|
-
if message_id
-
bracketed_message_id = "<#{message_id}>"
-
reply.in_reply_to = bracketed_message_id
-
if !references.nil?
-
refs = [references].flatten.map { |r| "<#{r}>" }
-
refs << bracketed_message_id
-
reply.references = refs.join(' ')
-
elsif !in_reply_to.nil? && !in_reply_to.kind_of?(Array)
-
reply.references = "<#{in_reply_to}> #{bracketed_message_id}"
-
end
-
reply.references ||= bracketed_message_id
-
end
-
if subject
-
reply.subject = subject =~ /^Re:/i ? subject : "RE: #{subject}"
-
end
-
if reply_to || from
-
reply.to = self[reply_to ? :reply_to : :from].to_s
-
end
-
if to
-
reply.from = self[:to].formatted.first.to_s
-
end
-
-
unless args.empty?
-
if args.flatten.first.respond_to?(:each_pair)
-
reply.send(:init_with_hash, args.flatten.first)
-
else
-
reply.send(:init_with_string, args.flatten[0].to_s.strip)
-
end
-
end
-
-
if block_given?
-
reply.instance_eval(&block)
-
end
-
end
-
end
-
-
# Provides the operator needed for sort et al.
-
#
-
# Compares this mail object with another mail object, this is done by date, so an
-
# email that is older than another will appear first.
-
#
-
# Example:
-
#
-
# mail1 = Mail.new do
-
# date(Time.now)
-
# end
-
# mail2 = Mail.new do
-
# date(Time.now - 86400) # 1 day older
-
# end
-
# [mail2, mail1].sort #=> [mail2, mail1]
-
1
def <=>(other)
-
if other.nil?
-
1
-
else
-
self.date <=> other.date
-
end
-
end
-
-
# Two emails are the same if they have the same fields and body contents. One
-
# gotcha here is that Mail will insert Message-IDs when calling encoded, so doing
-
# mail1.encoded == mail2.encoded is most probably not going to return what you think
-
# as the assigned Message-IDs by Mail (if not already defined as the same) will ensure
-
# that the two objects are unique, and this comparison will ALWAYS return false.
-
#
-
# So the == operator has been defined like so: Two messages are the same if they have
-
# the same content, ignoring the Message-ID field, unless BOTH emails have a defined and
-
# different Message-ID value, then they are false.
-
#
-
# So, in practice the == operator works like this:
-
#
-
# m1 = Mail.new("Subject: Hello\r\n\r\nHello")
-
# m2 = Mail.new("Subject: Hello\r\n\r\nHello")
-
# m1 == m2 #=> true
-
#
-
# m1 = Mail.new("Subject: Hello\r\n\r\nHello")
-
# m2 = Mail.new("Message-ID: <1234@test>\r\nSubject: Hello\r\n\r\nHello")
-
# m1 == m2 #=> true
-
#
-
# m1 = Mail.new("Message-ID: <1234@test>\r\nSubject: Hello\r\n\r\nHello")
-
# m2 = Mail.new("Subject: Hello\r\n\r\nHello")
-
# m1 == m2 #=> true
-
#
-
# m1 = Mail.new("Message-ID: <1234@test>\r\nSubject: Hello\r\n\r\nHello")
-
# m2 = Mail.new("Message-ID: <1234@test>\r\nSubject: Hello\r\n\r\nHello")
-
# m1 == m2 #=> true
-
#
-
# m1 = Mail.new("Message-ID: <1234@test>\r\nSubject: Hello\r\n\r\nHello")
-
# m2 = Mail.new("Message-ID: <DIFFERENT@test>\r\nSubject: Hello\r\n\r\nHello")
-
# m1 == m2 #=> false
-
1
def ==(other)
-
return false unless other.respond_to?(:encoded)
-
-
if self.message_id && other.message_id
-
result = (self.encoded == other.encoded)
-
else
-
self_message_id, other_message_id = self.message_id, other.message_id
-
self.message_id, other.message_id = '<temp@test>', '<temp@test>'
-
result = self.encoded == other.encoded
-
self.message_id = "<#{self_message_id}>" if self_message_id
-
other.message_id = "<#{other_message_id}>" if other_message_id
-
result
-
end
-
end
-
-
# Provides access to the raw source of the message as it was when it
-
# was instantiated. This is set at initialization and so is untouched
-
# by the parsers or decoder / encoders
-
#
-
# Example:
-
#
-
# mail = Mail.new('This is an invalid email message')
-
# mail.raw_source #=> "This is an invalid email message"
-
1
def raw_source
-
@raw_source
-
end
-
-
# Sets the envelope from for the email
-
1
def set_envelope( val )
-
@raw_envelope = val
-
@envelope = Mail::Envelope.new( val )
-
end
-
-
# The raw_envelope is the From mikel@test.lindsaar.net Mon May 2 16:07:05 2009
-
# type field that you can see at the top of any email that has come
-
# from a mailbox
-
1
def raw_envelope
-
@raw_envelope
-
end
-
-
1
def envelope_from
-
@envelope ? @envelope.from : nil
-
end
-
-
1
def envelope_date
-
@envelope ? @envelope.date : nil
-
end
-
-
# Sets the header of the message object.
-
#
-
# Example:
-
#
-
# mail.header = 'To: mikel@test.lindsaar.net\r\nFrom: Bob@bob.com'
-
# mail.header #=> <#Mail::Header
-
1
def header=(value)
-
@header = Mail::Header.new(value, charset)
-
end
-
-
# Returns the header object of the message object. Or, if passed
-
# a parameter sets the value.
-
#
-
# Example:
-
#
-
# mail = Mail::Message.new('To: mikel\r\nFrom: you')
-
# mail.header #=> #<Mail::Header:0x13ce14 @raw_source="To: mikel\r\nFr...
-
#
-
# mail.header #=> nil
-
# mail.header 'To: mikel\r\nFrom: you'
-
# mail.header #=> #<Mail::Header:0x13ce14 @raw_source="To: mikel\r\nFr...
-
1
def header(value = nil)
-
value ? self.header = value : @header
-
end
-
-
# Provides a way to set custom headers, by passing in a hash
-
1
def headers(hash = {})
-
hash.each_pair do |k,v|
-
header[k] = v
-
end
-
end
-
-
# Returns a list of parser errors on the header, each field that had an error
-
# will be reparsed as an unstructured field to preserve the data inside, but
-
# will not be used for further processing.
-
#
-
# It returns a nested array of [field_name, value, original_error_message]
-
# per error found.
-
#
-
# Example:
-
#
-
# message = Mail.new("Content-Transfer-Encoding: weirdo\r\n")
-
# message.errors.size #=> 1
-
# message.errors.first[0] #=> "Content-Transfer-Encoding"
-
# message.errors.first[1] #=> "weirdo"
-
# message.errors.first[3] #=> <The original error message exception>
-
#
-
# This is a good first defence on detecting spam by the way. Some spammers send
-
# invalid emails to try and get email parsers to give up parsing them.
-
1
def errors
-
header.errors
-
end
-
-
# Returns the Bcc value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.bcc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.bcc #=> ['mikel@test.lindsaar.net']
-
# mail.bcc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.bcc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.bcc #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.bcc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.bcc << 'ada@test.lindsaar.net'
-
# mail.bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def bcc( val = nil )
-
default :bcc, val
-
end
-
-
# Sets the Bcc value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.bcc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.bcc #=> ['mikel@test.lindsaar.net']
-
# mail.bcc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def bcc=( val )
-
header[:bcc] = val
-
end
-
-
# Returns the Cc value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.cc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.cc #=> ['mikel@test.lindsaar.net']
-
# mail.cc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.cc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.cc #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.cc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.cc << 'ada@test.lindsaar.net'
-
# mail.cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def cc( val = nil )
-
default :cc, val
-
end
-
-
# Sets the Cc value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.cc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.cc #=> ['mikel@test.lindsaar.net']
-
# mail.cc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def cc=( val )
-
header[:cc] = val
-
end
-
-
1
def comments( val = nil )
-
default :comments, val
-
end
-
-
1
def comments=( val )
-
header[:comments] = val
-
end
-
-
1
def content_description( val = nil )
-
default :content_description, val
-
end
-
-
1
def content_description=( val )
-
header[:content_description] = val
-
end
-
-
1
def content_disposition( val = nil )
-
default :content_disposition, val
-
end
-
-
1
def content_disposition=( val )
-
header[:content_disposition] = val
-
end
-
-
1
def content_id( val = nil )
-
default :content_id, val
-
end
-
-
1
def content_id=( val )
-
header[:content_id] = val
-
end
-
-
1
def content_location( val = nil )
-
default :content_location, val
-
end
-
-
1
def content_location=( val )
-
header[:content_location] = val
-
end
-
-
1
def content_transfer_encoding( val = nil )
-
default :content_transfer_encoding, val
-
end
-
-
1
def content_transfer_encoding=( val )
-
header[:content_transfer_encoding] = val
-
end
-
-
1
def content_type( val = nil )
-
default :content_type, val
-
end
-
-
1
def content_type=( val )
-
header[:content_type] = val
-
end
-
-
1
def date( val = nil )
-
default :date, val
-
end
-
-
1
def date=( val )
-
header[:date] = val
-
end
-
-
1
def transport_encoding( val = nil)
-
if val
-
self.transport_encoding = val
-
else
-
@transport_encoding
-
end
-
end
-
-
1
def transport_encoding=( val )
-
@transport_encoding = Mail::Encodings.get_encoding(val)
-
end
-
-
# Returns the From value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.from = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.from #=> ['mikel@test.lindsaar.net']
-
# mail.from = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.from 'Mikel <mikel@test.lindsaar.net>'
-
# mail.from #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.from 'Mikel <mikel@test.lindsaar.net>'
-
# mail.from << 'ada@test.lindsaar.net'
-
# mail.from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def from( val = nil )
-
default :from, val
-
end
-
-
# Sets the From value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.from = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.from #=> ['mikel@test.lindsaar.net']
-
# mail.from = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def from=( val )
-
header[:from] = val
-
end
-
-
1
def in_reply_to( val = nil )
-
default :in_reply_to, val
-
end
-
-
1
def in_reply_to=( val )
-
header[:in_reply_to] = val
-
end
-
-
1
def keywords( val = nil )
-
default :keywords, val
-
end
-
-
1
def keywords=( val )
-
header[:keywords] = val
-
end
-
-
# Returns the Message-ID of the mail object. Note, per RFC 2822 the Message ID
-
# consists of what is INSIDE the < > usually seen in the mail header, so this method
-
# will return only what is inside.
-
#
-
# Example:
-
#
-
# mail.message_id = '<1234@message.id>'
-
# mail.message_id #=> '1234@message.id'
-
#
-
# Also allows you to set the Message-ID by passing a string as a parameter
-
#
-
# mail.message_id '<1234@message.id>'
-
# mail.message_id #=> '1234@message.id'
-
1
def message_id( val = nil )
-
default :message_id, val
-
end
-
-
# Sets the Message-ID. Note, per RFC 2822 the Message ID consists of what is INSIDE
-
# the < > usually seen in the mail header, so this method will return only what is inside.
-
#
-
# mail.message_id = '<1234@message.id>'
-
# mail.message_id #=> '1234@message.id'
-
1
def message_id=( val )
-
header[:message_id] = val
-
end
-
-
# Returns the MIME version of the email as a string
-
#
-
# Example:
-
#
-
# mail.mime_version = '1.0'
-
# mail.mime_version #=> '1.0'
-
#
-
# Also allows you to set the MIME version by passing a string as a parameter.
-
#
-
# Example:
-
#
-
# mail.mime_version '1.0'
-
# mail.mime_version #=> '1.0'
-
1
def mime_version( val = nil )
-
default :mime_version, val
-
end
-
-
# Sets the MIME version of the email by accepting a string
-
#
-
# Example:
-
#
-
# mail.mime_version = '1.0'
-
# mail.mime_version #=> '1.0'
-
1
def mime_version=( val )
-
header[:mime_version] = val
-
end
-
-
1
def received( val = nil )
-
if val
-
header[:received] = val
-
else
-
header[:received]
-
end
-
end
-
-
1
def received=( val )
-
header[:received] = val
-
end
-
-
1
def references( val = nil )
-
default :references, val
-
end
-
-
1
def references=( val )
-
header[:references] = val
-
end
-
-
# Returns the Reply-To value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.reply_to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.reply_to #=> ['mikel@test.lindsaar.net']
-
# mail.reply_to = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.reply_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.reply_to 'Mikel <mikel@test.lindsaar.net>'
-
# mail.reply_to #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.reply_to 'Mikel <mikel@test.lindsaar.net>'
-
# mail.reply_to << 'ada@test.lindsaar.net'
-
# mail.reply_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def reply_to( val = nil )
-
default :reply_to, val
-
end
-
-
# Sets the Reply-To value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.reply_to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.reply_to #=> ['mikel@test.lindsaar.net']
-
# mail.reply_to = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.reply_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def reply_to=( val )
-
header[:reply_to] = val
-
end
-
-
# Returns the Resent-Bcc value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.resent_bcc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_bcc #=> ['mikel@test.lindsaar.net']
-
# mail.resent_bcc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.resent_bcc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_bcc #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.resent_bcc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_bcc << 'ada@test.lindsaar.net'
-
# mail.resent_bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def resent_bcc( val = nil )
-
default :resent_bcc, val
-
end
-
-
# Sets the Resent-Bcc value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.resent_bcc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_bcc #=> ['mikel@test.lindsaar.net']
-
# mail.resent_bcc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def resent_bcc=( val )
-
header[:resent_bcc] = val
-
end
-
-
# Returns the Resent-Cc value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.resent_cc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_cc #=> ['mikel@test.lindsaar.net']
-
# mail.resent_cc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.resent_cc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_cc #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.resent_cc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_cc << 'ada@test.lindsaar.net'
-
# mail.resent_cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def resent_cc( val = nil )
-
default :resent_cc, val
-
end
-
-
# Sets the Resent-Cc value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.resent_cc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_cc #=> ['mikel@test.lindsaar.net']
-
# mail.resent_cc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def resent_cc=( val )
-
header[:resent_cc] = val
-
end
-
-
1
def resent_date( val = nil )
-
default :resent_date, val
-
end
-
-
1
def resent_date=( val )
-
header[:resent_date] = val
-
end
-
-
# Returns the Resent-From value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.resent_from = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_from #=> ['mikel@test.lindsaar.net']
-
# mail.resent_from = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.resent_from ['Mikel <mikel@test.lindsaar.net>']
-
# mail.resent_from #=> 'mikel@test.lindsaar.net'
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.resent_from 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_from << 'ada@test.lindsaar.net'
-
# mail.resent_from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def resent_from( val = nil )
-
default :resent_from, val
-
end
-
-
# Sets the Resent-From value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.resent_from = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_from #=> ['mikel@test.lindsaar.net']
-
# mail.resent_from = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def resent_from=( val )
-
header[:resent_from] = val
-
end
-
-
1
def resent_message_id( val = nil )
-
default :resent_message_id, val
-
end
-
-
1
def resent_message_id=( val )
-
header[:resent_message_id] = val
-
end
-
-
# Returns the Resent-Sender value of the mail object, as a single string of an address
-
# spec. A sender per RFC 2822 must be a single address, so you can not append to
-
# this address.
-
#
-
# Example:
-
#
-
# mail.resent_sender = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_sender #=> 'mikel@test.lindsaar.net'
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.resent_sender 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_sender #=> 'mikel@test.lindsaar.net'
-
1
def resent_sender( val = nil )
-
default :resent_sender, val
-
end
-
-
# Sets the Resent-Sender value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.resent_sender = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_sender #=> 'mikel@test.lindsaar.net'
-
1
def resent_sender=( val )
-
header[:resent_sender] = val
-
end
-
-
# Returns the Resent-To value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.resent_to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_to #=> ['mikel@test.lindsaar.net']
-
# mail.resent_to = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.resent_to 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_to #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.resent_to 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_to << 'ada@test.lindsaar.net'
-
# mail.resent_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def resent_to( val = nil )
-
default :resent_to, val
-
end
-
-
# Sets the Resent-To value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.resent_to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_to #=> ['mikel@test.lindsaar.net']
-
# mail.resent_to = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def resent_to=( val )
-
header[:resent_to] = val
-
end
-
-
# Returns the return path of the mail object, or sets it if you pass a string
-
1
def return_path( val = nil )
-
default :return_path, val
-
end
-
-
# Sets the return path of the object
-
1
def return_path=( val )
-
header[:return_path] = val
-
end
-
-
# Returns the Sender value of the mail object, as a single string of an address
-
# spec. A sender per RFC 2822 must be a single address.
-
#
-
# Example:
-
#
-
# mail.sender = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.sender #=> 'mikel@test.lindsaar.net'
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.sender 'Mikel <mikel@test.lindsaar.net>'
-
# mail.sender #=> 'mikel@test.lindsaar.net'
-
1
def sender( val = nil )
-
default :sender, val
-
end
-
-
# Sets the Sender value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.sender = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.sender #=> 'mikel@test.lindsaar.net'
-
1
def sender=( val )
-
header[:sender] = val
-
end
-
-
# Returns the SMTP Envelope From value of the mail object, as a single
-
# string of an address spec.
-
#
-
# Defaults to Return-Path, Sender, or the first From address.
-
#
-
# Example:
-
#
-
# mail.smtp_envelope_from = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.smtp_envelope_from #=> 'mikel@test.lindsaar.net'
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.smtp_envelope_from 'Mikel <mikel@test.lindsaar.net>'
-
# mail.smtp_envelope_from #=> 'mikel@test.lindsaar.net'
-
1
def smtp_envelope_from( val = nil )
-
if val
-
self.smtp_envelope_from = val
-
else
-
@smtp_envelope_from || return_path || sender || from_addrs.first
-
end
-
end
-
-
# Sets the From address on the SMTP Envelope.
-
#
-
# Example:
-
#
-
# mail.smtp_envelope_from = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.smtp_envelope_from #=> 'mikel@test.lindsaar.net'
-
1
def smtp_envelope_from=( val )
-
@smtp_envelope_from = val
-
end
-
-
# Returns the SMTP Envelope To value of the mail object.
-
#
-
# Defaults to #destinations: To, Cc, and Bcc addresses.
-
#
-
# Example:
-
#
-
# mail.smtp_envelope_to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.smtp_envelope_to #=> 'mikel@test.lindsaar.net'
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.smtp_envelope_to ['Mikel <mikel@test.lindsaar.net>', 'Lindsaar <lindsaar@test.lindsaar.net>']
-
# mail.smtp_envelope_to #=> ['mikel@test.lindsaar.net', 'lindsaar@test.lindsaar.net']
-
1
def smtp_envelope_to( val = nil )
-
if val
-
self.smtp_envelope_to = val
-
else
-
@smtp_envelope_to || destinations
-
end
-
end
-
-
# Sets the To addresses on the SMTP Envelope.
-
#
-
# Example:
-
#
-
# mail.smtp_envelope_to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.smtp_envelope_to #=> 'mikel@test.lindsaar.net'
-
#
-
# mail.smtp_envelope_to = ['Mikel <mikel@test.lindsaar.net>', 'Lindsaar <lindsaar@test.lindsaar.net>']
-
# mail.smtp_envelope_to #=> ['mikel@test.lindsaar.net', 'lindsaar@test.lindsaar.net']
-
1
def smtp_envelope_to=( val )
-
@smtp_envelope_to =
-
case val
-
when Array, NilClass
-
val
-
else
-
[val]
-
end
-
end
-
-
# Returns the decoded value of the subject field, as a single string.
-
#
-
# Example:
-
#
-
# mail.subject = "G'Day mate"
-
# mail.subject #=> "G'Day mate"
-
# mail.subject = '=?UTF-8?Q?This_is_=E3=81=82_string?='
-
# mail.subject #=> "This is あ string"
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.subject "G'Day mate"
-
# mail.subject #=> "G'Day mate"
-
1
def subject( val = nil )
-
default :subject, val
-
end
-
-
# Sets the Subject value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.subject = '=?UTF-8?Q?This_is_=E3=81=82_string?='
-
# mail.subject #=> "This is あ string"
-
1
def subject=( val )
-
header[:subject] = val
-
end
-
-
# Returns the To value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.to #=> ['mikel@test.lindsaar.net']
-
# mail.to = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.to 'Mikel <mikel@test.lindsaar.net>'
-
# mail.to #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.to 'Mikel <mikel@test.lindsaar.net>'
-
# mail.to << 'ada@test.lindsaar.net'
-
# mail.to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def to( val = nil )
-
default :to, val
-
end
-
-
# Sets the To value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.to #=> ['mikel@test.lindsaar.net']
-
# mail.to = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
1
def to=( val )
-
header[:to] = val
-
end
-
-
# Returns the default value of the field requested as a symbol.
-
#
-
# Each header field has a :default method which returns the most common use case for
-
# that field, for example, the date field types will return a DateTime object when
-
# sent :default, the subject, or unstructured fields will return a decoded string of
-
# their value, the address field types will return a single addr_spec or an array of
-
# addr_specs if there is more than one.
-
1
def default( sym, val = nil )
-
if val
-
header[sym] = val
-
else
-
header[sym].default if header[sym]
-
end
-
end
-
-
# Sets the body object of the message object.
-
#
-
# Example:
-
#
-
# mail.body = 'This is the body'
-
# mail.body #=> #<Mail::Body:0x13919c @raw_source="This is the bo...
-
#
-
# You can also reset the body of an Message object by setting body to nil
-
#
-
# Example:
-
#
-
# mail.body = 'this is the body'
-
# mail.body.encoded #=> 'this is the body'
-
# mail.body = nil
-
# mail.body.encoded #=> ''
-
#
-
# If you try and set the body of an email that is a multipart email, then instead
-
# of deleting all the parts of your email, mail will add a text/plain part to
-
# your email:
-
#
-
# mail.add_file 'somefilename.png'
-
# mail.parts.length #=> 1
-
# mail.body = "This is a body"
-
# mail.parts.length #=> 2
-
# mail.parts.last.content_type.content_type #=> 'This is a body'
-
1
def body=(value)
-
body_lazy(value)
-
end
-
-
# Returns the body of the message object. Or, if passed
-
# a parameter sets the value.
-
#
-
# Example:
-
#
-
# mail = Mail::Message.new('To: mikel\r\n\r\nThis is the body')
-
# mail.body #=> #<Mail::Body:0x13919c @raw_source="This is the bo...
-
#
-
# mail.body 'This is another body'
-
# mail.body #=> #<Mail::Body:0x13919c @raw_source="This is anothe...
-
1
def body(value = nil)
-
if value
-
self.body = value
-
# add_encoding_to_body
-
else
-
process_body_raw if @body_raw
-
@body
-
end
-
end
-
-
1
def body_encoding(value)
-
if value.nil?
-
body.encoding
-
else
-
body.encoding = value
-
end
-
end
-
-
1
def body_encoding=(value)
-
body.encoding = value
-
end
-
-
# Returns the list of addresses this message should be sent to by
-
# collecting the addresses off the to, cc and bcc fields.
-
#
-
# Example:
-
#
-
# mail.to = 'mikel@test.lindsaar.net'
-
# mail.cc = 'sam@test.lindsaar.net'
-
# mail.bcc = 'bob@test.lindsaar.net'
-
# mail.destinations.length #=> 3
-
# mail.destinations.first #=> 'mikel@test.lindsaar.net'
-
1
def destinations
-
[to_addrs, cc_addrs, bcc_addrs].compact.flatten
-
end
-
-
# Returns an array of addresses (the encoded value) in the From field,
-
# if no From field, returns an empty array
-
1
def from_addrs
-
from ? [from].flatten : []
-
end
-
-
# Returns an array of addresses (the encoded value) in the To field,
-
# if no To field, returns an empty array
-
1
def to_addrs
-
to ? [to].flatten : []
-
end
-
-
# Returns an array of addresses (the encoded value) in the Cc field,
-
# if no Cc field, returns an empty array
-
1
def cc_addrs
-
cc ? [cc].flatten : []
-
end
-
-
# Returns an array of addresses (the encoded value) in the Bcc field,
-
# if no Bcc field, returns an empty array
-
1
def bcc_addrs
-
bcc ? [bcc].flatten : []
-
end
-
-
# Allows you to add an arbitrary header
-
#
-
# Example:
-
#
-
# mail['foo'] = '1234'
-
# mail['foo'].to_s #=> '1234'
-
1
def []=(name, value)
-
if name.to_s == 'body'
-
self.body = value
-
elsif name.to_s =~ /content[-_]type/i
-
header[name] = value
-
elsif name.to_s == 'charset'
-
self.charset = value
-
else
-
header[name] = value
-
end
-
end
-
-
# Allows you to read an arbitrary header
-
#
-
# Example:
-
#
-
# mail['foo'] = '1234'
-
# mail['foo'].to_s #=> '1234'
-
1
def [](name)
-
header[underscoreize(name)]
-
end
-
-
# Method Missing in this implementation allows you to set any of the
-
# standard fields directly as you would the "to", "subject" etc.
-
#
-
# Those fields used most often (to, subject et al) are given their
-
# own method for ease of documentation and also to avoid the hook
-
# call to method missing.
-
#
-
# This will only catch the known fields listed in:
-
#
-
# Mail::Field::KNOWN_FIELDS
-
#
-
# as per RFC 2822, any ruby string or method name could pretty much
-
# be a field name, so we don't want to just catch ANYTHING sent to
-
# a message object and interpret it as a header.
-
#
-
# This method provides all three types of header call to set, read
-
# and explicitly set with the = operator
-
#
-
# Examples:
-
#
-
# mail.comments = 'These are some comments'
-
# mail.comments #=> 'These are some comments'
-
#
-
# mail.comments 'These are other comments'
-
# mail.comments #=> 'These are other comments'
-
#
-
#
-
# mail.date = 'Tue, 1 Jul 2003 10:52:37 +0200'
-
# mail.date.to_s #=> 'Tue, 1 Jul 2003 10:52:37 +0200'
-
#
-
# mail.date 'Tue, 1 Jul 2003 10:52:37 +0200'
-
# mail.date.to_s #=> 'Tue, 1 Jul 2003 10:52:37 +0200'
-
#
-
#
-
# mail.resent_msg_id = '<1234@resent_msg_id.lindsaar.net>'
-
# mail.resent_msg_id #=> '<1234@resent_msg_id.lindsaar.net>'
-
#
-
# mail.resent_msg_id '<4567@resent_msg_id.lindsaar.net>'
-
# mail.resent_msg_id #=> '<4567@resent_msg_id.lindsaar.net>'
-
1
def method_missing(name, *args, &block)
-
#:nodoc:
-
# Only take the structured fields, as we could take _anything_ really
-
# as it could become an optional field... "but therin lies the dark side"
-
field_name = underscoreize(name).chomp("=")
-
if Mail::Field::KNOWN_FIELDS.include?(field_name)
-
if args.empty?
-
header[field_name]
-
else
-
header[field_name] = args.first
-
end
-
else
-
super # otherwise pass it on
-
end
-
#:startdoc:
-
end
-
-
# Returns an FieldList of all the fields in the header in the order that
-
# they appear in the header
-
1
def header_fields
-
header.fields
-
end
-
-
# Returns true if the message has a message ID field, the field may or may
-
# not have a value, but the field exists or not.
-
1
def has_message_id?
-
header.has_message_id?
-
end
-
-
# Returns true if the message has a Date field, the field may or may
-
# not have a value, but the field exists or not.
-
1
def has_date?
-
header.has_date?
-
end
-
-
# Returns true if the message has a Date field, the field may or may
-
# not have a value, but the field exists or not.
-
1
def has_mime_version?
-
header.has_mime_version?
-
end
-
-
1
def has_content_type?
-
tmp = header[:content_type].main_type rescue nil
-
!!tmp
-
end
-
-
1
def has_charset?
-
tmp = header[:content_type].parameters rescue nil
-
!!(has_content_type? && tmp && tmp['charset'])
-
end
-
-
1
def has_content_transfer_encoding?
-
header[:content_transfer_encoding] && header[:content_transfer_encoding].errors.blank?
-
end
-
-
1
def has_transfer_encoding? # :nodoc:
-
STDERR.puts(":has_transfer_encoding? is deprecated in Mail 1.4.3. Please use has_content_transfer_encoding?\n#{caller}")
-
has_content_transfer_encoding?
-
end
-
-
# Creates a new empty Message-ID field and inserts it in the correct order
-
# into the Header. The MessageIdField object will automatically generate
-
# a unique message ID if you try and encode it or output it to_s without
-
# specifying a message id.
-
#
-
# It will preserve the message ID you specify if you do.
-
1
def add_message_id(msg_id_val = '')
-
header['message-id'] = msg_id_val
-
end
-
-
# Creates a new empty Date field and inserts it in the correct order
-
# into the Header. The DateField object will automatically generate
-
# DateTime.now's date if you try and encode it or output it to_s without
-
# specifying a date yourself.
-
#
-
# It will preserve any date you specify if you do.
-
1
def add_date(date_val = '')
-
header['date'] = date_val
-
end
-
-
# Creates a new empty Mime Version field and inserts it in the correct order
-
# into the Header. The MimeVersion object will automatically generate
-
# set itself to '1.0' if you try and encode it or output it to_s without
-
# specifying a version yourself.
-
#
-
# It will preserve any date you specify if you do.
-
1
def add_mime_version(ver_val = '')
-
header['mime-version'] = ver_val
-
end
-
-
# Adds a content type and charset if the body is US-ASCII
-
#
-
# Otherwise raises a warning
-
1
def add_content_type
-
header[:content_type] = 'text/plain'
-
end
-
-
# Adds a content type and charset if the body is US-ASCII
-
#
-
# Otherwise raises a warning
-
1
def add_charset
-
if !body.empty?
-
# Only give a warning if this isn't an attachment, has non US-ASCII and the user
-
# has not specified an encoding explicitly.
-
if @defaulted_charset && body.raw_source.not_ascii_only? && !self.attachment?
-
warning = "Non US-ASCII detected and no charset defined.\nDefaulting to UTF-8, set your own if this is incorrect.\n"
-
STDERR.puts(warning)
-
end
-
header[:content_type].parameters['charset'] = @charset
-
end
-
end
-
-
# Adds a content transfer encoding
-
#
-
# Otherwise raises a warning
-
1
def add_content_transfer_encoding
-
if body.only_us_ascii?
-
header[:content_transfer_encoding] = '7bit'
-
else
-
warning = "Non US-ASCII detected and no content-transfer-encoding defined.\nDefaulting to 8bit, set your own if this is incorrect.\n"
-
STDERR.puts(warning)
-
header[:content_transfer_encoding] = '8bit'
-
end
-
end
-
-
1
def add_transfer_encoding # :nodoc:
-
STDERR.puts(":add_transfer_encoding is deprecated in Mail 1.4.3. Please use add_content_transfer_encoding\n#{caller}")
-
add_content_transfer_encoding
-
end
-
-
1
def transfer_encoding # :nodoc:
-
STDERR.puts(":transfer_encoding is deprecated in Mail 1.4.3. Please use content_transfer_encoding\n#{caller}")
-
content_transfer_encoding
-
end
-
-
# Returns the MIME media type of part we are on, this is taken from the content-type header
-
1
def mime_type
-
has_content_type? ? header[:content_type].string : nil rescue nil
-
end
-
-
1
def message_content_type
-
STDERR.puts(":message_content_type is deprecated in Mail 1.4.3. Please use mime_type\n#{caller}")
-
mime_type
-
end
-
-
# Returns the character set defined in the content type field
-
1
def charset
-
if @header
-
has_content_type? ? content_type_parameters['charset'] : @charset
-
else
-
@charset
-
end
-
end
-
-
# Sets the charset to the supplied value.
-
1
def charset=(value)
-
@defaulted_charset = false
-
@charset = value
-
@header.charset = value
-
end
-
-
# Returns the main content type
-
1
def main_type
-
has_content_type? ? header[:content_type].main_type : nil rescue nil
-
end
-
-
# Returns the sub content type
-
1
def sub_type
-
has_content_type? ? header[:content_type].sub_type : nil rescue nil
-
end
-
-
# Returns the content type parameters
-
1
def mime_parameters
-
STDERR.puts(':mime_parameters is deprecated in Mail 1.4.3, please use :content_type_parameters instead')
-
content_type_parameters
-
end
-
-
# Returns the content type parameters
-
1
def content_type_parameters
-
has_content_type? ? header[:content_type].parameters : nil rescue nil
-
end
-
-
# Returns true if the message is multipart
-
1
def multipart?
-
has_content_type? ? !!(main_type =~ /^multipart$/i) : false
-
end
-
-
# Returns true if the message is a multipart/report
-
1
def multipart_report?
-
multipart? && sub_type =~ /^report$/i
-
end
-
-
# Returns true if the message is a multipart/report; report-type=delivery-status;
-
1
def delivery_status_report?
-
multipart_report? && content_type_parameters['report-type'] =~ /^delivery-status$/i
-
end
-
-
# returns the part in a multipart/report email that has the content-type delivery-status
-
1
def delivery_status_part
-
@delivery_stats_part ||= parts.select { |p| p.delivery_status_report_part? }.first
-
end
-
-
1
def bounced?
-
delivery_status_part and delivery_status_part.bounced?
-
end
-
-
1
def action
-
delivery_status_part and delivery_status_part.action
-
end
-
-
1
def final_recipient
-
delivery_status_part and delivery_status_part.final_recipient
-
end
-
-
1
def error_status
-
delivery_status_part and delivery_status_part.error_status
-
end
-
-
1
def diagnostic_code
-
delivery_status_part and delivery_status_part.diagnostic_code
-
end
-
-
1
def remote_mta
-
delivery_status_part and delivery_status_part.remote_mta
-
end
-
-
1
def retryable?
-
delivery_status_part and delivery_status_part.retryable?
-
end
-
-
# Returns the current boundary for this message part
-
1
def boundary
-
content_type_parameters ? content_type_parameters['boundary'] : nil
-
end
-
-
# Returns a parts list object of all the parts in the message
-
1
def parts
-
body.parts
-
end
-
-
# Returns an AttachmentsList object, which holds all of the attachments in
-
# the receiver object (either the entier email or a part within) and all
-
# of its descendants.
-
#
-
# It also allows you to add attachments to the mail object directly, like so:
-
#
-
# mail.attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
-
#
-
# If you do this, then Mail will take the file name and work out the MIME media type
-
# set the Content-Type, Content-Disposition, Content-Transfer-Encoding and
-
# base64 encode the contents of the attachment all for you.
-
#
-
# You can also specify overrides if you want by passing a hash instead of a string:
-
#
-
# mail.attachments['filename.jpg'] = {:mime_type => 'application/x-gzip',
-
# :content => File.read('/path/to/filename.jpg')}
-
#
-
# If you want to use a different encoding than Base64, you can pass an encoding in,
-
# but then it is up to you to pass in the content pre-encoded, and don't expect
-
# Mail to know how to decode this data:
-
#
-
# file_content = SpecialEncode(File.read('/path/to/filename.jpg'))
-
# mail.attachments['filename.jpg'] = {:mime_type => 'application/x-gzip',
-
# :encoding => 'SpecialEncoding',
-
# :content => file_content }
-
#
-
# You can also search for specific attachments:
-
#
-
# # By Filename
-
# mail.attachments['filename.jpg'] #=> Mail::Part object or nil
-
#
-
# # or by index
-
# mail.attachments[0] #=> Mail::Part (first attachment)
-
#
-
1
def attachments
-
parts.attachments
-
end
-
-
1
def has_attachments?
-
!attachments.empty?
-
end
-
-
# Accessor for html_part
-
1
def html_part(&block)
-
if block_given?
-
self.html_part = Mail::Part.new(:content_type => 'text/html', &block)
-
else
-
@html_part || find_first_mime_type('text/html')
-
end
-
end
-
-
# Accessor for text_part
-
1
def text_part(&block)
-
if block_given?
-
self.text_part = Mail::Part.new(:content_type => 'text/plain', &block)
-
else
-
@text_part || find_first_mime_type('text/plain')
-
end
-
end
-
-
# Helper to add a html part to a multipart/alternative email. If this and
-
# text_part are both defined in a message, then it will be a multipart/alternative
-
# message and set itself that way.
-
1
def html_part=(msg)
-
# Assign the html part and set multipart/alternative if there's a text part.
-
if msg
-
@html_part = msg
-
@html_part.content_type = 'text/html' unless @html_part.has_content_type?
-
add_multipart_alternate_header if text_part
-
add_part @html_part
-
-
# If nil, delete the html part and back out of multipart/alternative.
-
elsif @html_part
-
parts.delete_if { |p| p.object_id == @html_part.object_id }
-
@html_part = nil
-
if text_part
-
self.content_type = nil
-
body.boundary = nil
-
end
-
end
-
end
-
-
# Helper to add a text part to a multipart/alternative email. If this and
-
# html_part are both defined in a message, then it will be a multipart/alternative
-
# message and set itself that way.
-
1
def text_part=(msg)
-
# Assign the text part and set multipart/alternative if there's an html part.
-
if msg
-
@text_part = msg
-
@text_part.content_type = 'text/plain' unless @text_part.has_content_type?
-
add_multipart_alternate_header if html_part
-
add_part @text_part
-
-
# If nil, delete the text part and back out of multipart/alternative.
-
elsif @text_part
-
parts.delete_if { |p| p.object_id == @text_part.object_id }
-
@text_part = nil
-
if html_part
-
self.content_type = nil
-
body.boundary = nil
-
end
-
end
-
end
-
-
# Adds a part to the parts list or creates the part list
-
1
def add_part(part)
-
if !body.multipart? && !self.body.decoded.blank?
-
@text_part = Mail::Part.new('Content-Type: text/plain;')
-
@text_part.body = body.decoded
-
self.body << @text_part
-
add_multipart_alternate_header
-
end
-
add_boundary
-
self.body << part
-
end
-
-
# Allows you to add a part in block form to an existing mail message object
-
#
-
# Example:
-
#
-
# mail = Mail.new do
-
# part :content_type => "multipart/alternative", :content_disposition => "inline" do |p|
-
# p.part :content_type => "text/plain", :body => "test text\nline #2"
-
# p.part :content_type => "text/html", :body => "<b>test</b> HTML<br/>\nline #2"
-
# end
-
# end
-
1
def part(params = {})
-
new_part = Part.new(params)
-
yield new_part if block_given?
-
add_part(new_part)
-
end
-
-
# Adds a file to the message. You have two options with this method, you can
-
# just pass in the absolute path to the file you want and Mail will read the file,
-
# get the filename from the path you pass in and guess the MIME media type, or you
-
# can pass in the filename as a string, and pass in the file content as a blob.
-
#
-
# Example:
-
#
-
# m = Mail.new
-
# m.add_file('/path/to/filename.png')
-
#
-
# m = Mail.new
-
# m.add_file(:filename => 'filename.png', :content => File.read('/path/to/file.jpg'))
-
#
-
# Note also that if you add a file to an existing message, Mail will convert that message
-
# to a MIME multipart email, moving whatever plain text body you had into its own text
-
# plain part.
-
#
-
# Example:
-
#
-
# m = Mail.new do
-
# body 'this is some text'
-
# end
-
# m.multipart? #=> false
-
# m.add_file('/path/to/filename.png')
-
# m.multipart? #=> true
-
# m.parts.first.content_type.content_type #=> 'text/plain'
-
# m.parts.last.content_type.content_type #=> 'image/png'
-
#
-
# See also #attachments
-
1
def add_file(values)
-
convert_to_multipart unless self.multipart? || self.body.decoded.blank?
-
add_multipart_mixed_header
-
if values.is_a?(String)
-
basename = File.basename(values)
-
filedata = File.open(values, 'rb') { |f| f.read }
-
else
-
basename = values[:filename]
-
filedata = values[:content] || File.open(values[:filename], 'rb') { |f| f.read }
-
end
-
self.attachments[basename] = filedata
-
end
-
-
1
def convert_to_multipart
-
text = body.decoded
-
self.body = ''
-
text_part = Mail::Part.new({:content_type => 'text/plain;',
-
:body => text})
-
text_part.charset = charset unless @defaulted_charset
-
self.body << text_part
-
end
-
-
# Encodes the message, calls encode on all its parts, gets an email message
-
# ready to send
-
1
def ready_to_send!
-
identify_and_set_transfer_encoding
-
parts.sort!([ "text/plain", "text/enriched", "text/html", "multipart/alternative" ])
-
parts.each do |part|
-
part.transport_encoding = transport_encoding
-
part.ready_to_send!
-
end
-
add_required_fields
-
end
-
-
1
def encode!
-
STDERR.puts("Deprecated in 1.1.0 in favour of :ready_to_send! as it is less confusing with encoding and decoding.")
-
ready_to_send!
-
end
-
-
# Outputs an encoded string representation of the mail message including
-
# all headers, attachments, etc. This is an encoded email in US-ASCII,
-
# so it is able to be directly sent to an email server.
-
1
def encoded
-
ready_to_send!
-
buffer = header.encoded
-
buffer << "\r\n"
-
buffer << body.encoded(content_transfer_encoding)
-
buffer
-
end
-
-
1
def without_attachments!
-
return self unless has_attachments?
-
-
parts.delete_if { |p| p.attachment? }
-
body_raw = if parts.empty?
-
''
-
else
-
body.encoded
-
end
-
-
@body = Mail::Body.new(body_raw)
-
-
self
-
end
-
-
1
def to_yaml(opts = {})
-
hash = {}
-
hash['headers'] = {}
-
header.fields.each do |field|
-
hash['headers'][field.name] = field.value
-
end
-
hash['delivery_handler'] = delivery_handler.to_s if delivery_handler
-
hash['transport_encoding'] = transport_encoding.to_s
-
special_variables = [:@header, :@delivery_handler, :@transport_encoding]
-
if multipart?
-
hash['multipart_body'] = []
-
body.parts.map { |part| hash['multipart_body'] << part.to_yaml }
-
special_variables.push(:@body, :@text_part, :@html_part)
-
end
-
(instance_variables.map(&:to_sym) - special_variables).each do |var|
-
hash[var.to_s] = instance_variable_get(var)
-
end
-
hash.to_yaml(opts)
-
end
-
-
1
def self.from_yaml(str)
-
hash = YAML.load(str)
-
m = self.new(:headers => hash['headers'])
-
hash.delete('headers')
-
hash.each do |k,v|
-
case
-
when k == 'delivery_handler'
-
begin
-
m.delivery_handler = Object.const_get(v) unless v.blank?
-
rescue NameError
-
end
-
when k == 'transport_encoding'
-
m.transport_encoding(v)
-
when k == 'multipart_body'
-
v.map {|part| m.add_part Mail::Part.from_yaml(part) }
-
when k =~ /^@/
-
m.instance_variable_set(k.to_sym, v)
-
end
-
end
-
m
-
end
-
-
1
def self.from_hash(hash)
-
Mail::Message.new(hash)
-
end
-
-
1
def to_s
-
encoded
-
end
-
-
1
def inspect
-
"#<#{self.class}:#{self.object_id}, Multipart: #{multipart?}, Headers: #{header.field_summary}>"
-
end
-
-
1
def decoded
-
case
-
when self.text?
-
decode_body_as_text
-
when self.attachment?
-
decode_body
-
when !self.multipart?
-
body.decoded
-
else
-
raise NoMethodError, 'Can not decode an entire message, try calling #decoded on the various fields and body or parts if it is a multipart message.'
-
end
-
end
-
-
1
def read
-
if self.attachment?
-
decode_body
-
else
-
raise NoMethodError, 'Can not call read on a part unless it is an attachment.'
-
end
-
end
-
-
1
def decode_body
-
body.decoded
-
end
-
-
# Returns true if this part is an attachment,
-
# false otherwise.
-
1
def attachment?
-
!!find_attachment
-
end
-
-
# Returns the attachment data if there is any
-
1
def attachment
-
@attachment
-
end
-
-
# Returns the filename of the attachment
-
1
def filename
-
find_attachment
-
end
-
-
1
def all_parts
-
parts.map { |p| [p, p.all_parts] }.flatten
-
end
-
-
1
def find_first_mime_type(mt)
-
all_parts.detect { |p| p.mime_type == mt && !p.attachment? }
-
end
-
-
# Skips the deletion of this message. All other messages
-
# flagged for delete still will be deleted at session close (i.e. when
-
# #find exits). Only has an effect if you're using #find_and_delete
-
# or #find with :delete_after_find set to true.
-
1
def skip_deletion
-
@mark_for_delete = false
-
end
-
-
# Sets whether this message should be deleted at session close (i.e.
-
# after #find). Message will only be deleted if messages are retrieved
-
# using the #find_and_delete method, or by calling #find with
-
# :delete_after_find set to true.
-
1
def mark_for_delete=(value = true)
-
@mark_for_delete = value
-
end
-
-
# Returns whether message will be marked for deletion.
-
# If so, the message will be deleted at session close (i.e. after #find
-
# exits), but only if also using the #find_and_delete method, or by
-
# calling #find with :delete_after_find set to true.
-
#
-
# Side-note: Just to be clear, this method will return true even if
-
# the message hasn't yet been marked for delete on the mail server.
-
# However, if this method returns true, it *will be* marked on the
-
# server after each block yields back to #find or #find_and_delete.
-
1
def is_marked_for_delete?
-
return @mark_for_delete
-
end
-
-
1
def text?
-
has_content_type? ? !!(main_type =~ /^text$/i) : false
-
end
-
-
1
private
-
-
# 2.1. General Description
-
# A message consists of header fields (collectively called "the header
-
# of the message") followed, optionally, by a body. The header is a
-
# sequence of lines of characters with special syntax as defined in
-
# this standard. The body is simply a sequence of characters that
-
# follows the header and is separated from the header by an empty line
-
# (i.e., a line with nothing preceding the CRLF).
-
#
-
# Additionally, I allow for the case where someone might have put whitespace
-
# on the "gap line"
-
1
def parse_message
-
header_part, body_part = raw_source.lstrip.split(/#{CRLF}#{CRLF}|#{CRLF}#{WSP}*#{CRLF}(?!#{WSP})/m, 2)
-
self.header = header_part
-
self.body = body_part
-
end
-
-
1
def raw_source=(value)
-
value.force_encoding("binary") if RUBY_VERSION >= "1.9.1"
-
@raw_source = value.to_crlf
-
end
-
-
# see comments to body=. We take data and process it lazily
-
1
def body_lazy(value)
-
process_body_raw if @body_raw && value
-
case
-
when value == nil || value.length<=0
-
@body = Mail::Body.new('')
-
@body_raw = nil
-
add_encoding_to_body
-
when @body && @body.multipart?
-
@body << Mail::Part.new(value)
-
add_encoding_to_body
-
else
-
@body_raw = value
-
# process_body_raw
-
end
-
end
-
-
-
1
def process_body_raw
-
@body = Mail::Body.new(@body_raw)
-
@body_raw = nil
-
separate_parts if @separate_parts
-
-
add_encoding_to_body
-
end
-
-
1
def set_envelope_header
-
raw_string = raw_source.to_s
-
if match_data = raw_source.to_s.match(/\AFrom\s(#{TEXT}+)#{CRLF}/m)
-
set_envelope(match_data[1])
-
self.raw_source = raw_string.sub(match_data[0], "")
-
end
-
end
-
-
1
def separate_parts
-
body.split!(boundary)
-
end
-
-
1
def add_encoding_to_body
-
if has_content_transfer_encoding?
-
@body.encoding = content_transfer_encoding
-
end
-
end
-
-
1
def identify_and_set_transfer_encoding
-
if body && body.multipart?
-
self.content_transfer_encoding = @transport_encoding
-
else
-
self.content_transfer_encoding = body.get_best_encoding(@transport_encoding)
-
end
-
end
-
-
1
def add_required_fields
-
add_required_message_fields
-
add_multipart_mixed_header if body.multipart?
-
add_content_type unless has_content_type?
-
add_charset unless has_charset?
-
add_content_transfer_encoding unless has_content_transfer_encoding?
-
end
-
-
1
def add_required_message_fields
-
add_date unless has_date?
-
add_mime_version unless has_mime_version?
-
add_message_id unless has_message_id?
-
end
-
-
1
def add_multipart_alternate_header
-
header['content-type'] = ContentTypeField.with_boundary('multipart/alternative').value
-
header['content_type'].parameters[:charset] = @charset
-
body.boundary = boundary
-
end
-
-
1
def add_boundary
-
unless body.boundary && boundary
-
header['content-type'] = 'multipart/mixed' unless header['content-type']
-
header['content-type'].parameters[:boundary] = ContentTypeField.generate_boundary
-
header['content_type'].parameters[:charset] = @charset
-
body.boundary = boundary
-
end
-
end
-
-
1
def add_multipart_mixed_header
-
unless header['content-type']
-
header['content-type'] = ContentTypeField.with_boundary('multipart/mixed').value
-
header['content_type'].parameters[:charset] = @charset
-
body.boundary = boundary
-
end
-
end
-
-
1
def init_with_hash(hash)
-
passed_in_options = IndifferentHash.new(hash)
-
self.raw_source = ''
-
-
@header = Mail::Header.new
-
@body = Mail::Body.new
-
@body_raw = nil
-
-
# We need to store the body until last, as we need all headers added first
-
body_content = nil
-
-
passed_in_options.each_pair do |k,v|
-
k = underscoreize(k).to_sym if k.class == String
-
if k == :headers
-
self.headers(v)
-
elsif k == :body
-
body_content = v
-
else
-
self[k] = v
-
end
-
end
-
-
if body_content
-
self.body = body_content
-
if has_content_transfer_encoding?
-
body.encoding = content_transfer_encoding
-
end
-
end
-
end
-
-
1
def init_with_string(string)
-
self.raw_source = string
-
set_envelope_header
-
parse_message
-
@separate_parts = multipart?
-
end
-
-
# Returns the filename of the attachment (if it exists) or returns nil
-
1
def find_attachment
-
content_type_name = header[:content_type].filename rescue nil
-
content_disp_name = header[:content_disposition].filename rescue nil
-
content_loc_name = header[:content_location].location rescue nil
-
case
-
when content_type && content_type_name
-
filename = content_type_name
-
when content_disposition && content_disp_name
-
filename = content_disp_name
-
when content_location && content_loc_name
-
filename = content_loc_name
-
else
-
filename = nil
-
end
-
filename = Mail::Encodings.decode_encode(filename, :decode) if filename rescue filename
-
filename
-
end
-
-
1
def do_delivery
-
begin
-
if perform_deliveries
-
delivery_method.deliver!(self)
-
end
-
rescue Exception => e # Net::SMTP errors or sendmail pipe errors
-
raise e if raise_delivery_errors
-
end
-
end
-
-
1
def decode_body_as_text
-
body_text = decode_body
-
if charset
-
if RUBY_VERSION < '1.9'
-
require 'iconv'
-
return Iconv.conv("UTF-8//TRANSLIT//IGNORE", charset, body_text)
-
else
-
if encoding = Encoding.find(charset) rescue nil
-
body_text.force_encoding(encoding)
-
return body_text.encode(Encoding::UTF_8, :undef => :replace, :invalid => :replace, :replace => '')
-
end
-
end
-
end
-
body_text
-
end
-
-
end
-
end
-
1
require 'mail/network/retriever_methods/base'
-
-
1
module Mail
-
1
register_autoload :SMTP, 'mail/network/delivery_methods/smtp'
-
1
register_autoload :FileDelivery, 'mail/network/delivery_methods/file_delivery'
-
1
register_autoload :Sendmail, 'mail/network/delivery_methods/sendmail'
-
1
register_autoload :Exim, 'mail/network/delivery_methods/exim'
-
1
register_autoload :SMTPConnection, 'mail/network/delivery_methods/smtp_connection'
-
1
register_autoload :TestMailer, 'mail/network/delivery_methods/test_mailer'
-
-
1
register_autoload :POP3, 'mail/network/retriever_methods/pop3'
-
1
register_autoload :IMAP, 'mail/network/retriever_methods/imap'
-
1
register_autoload :TestRetriever, 'mail/network/retriever_methods/test_retriever'
-
end
-
1
require 'mail/check_delivery_params'
-
-
1
module Mail
-
-
# FileDelivery class delivers emails into multiple files based on the destination
-
# address. Each file is appended to if it already exists.
-
#
-
# So if you have an email going to fred@test, bob@test, joe@anothertest, and you
-
# set your location path to /path/to/mails then FileDelivery will create the directory
-
# if it does not exist, and put one copy of the email in three files, called
-
# by their message id
-
#
-
# Make sure the path you specify with :location is writable by the Ruby process
-
# running Mail.
-
1
class FileDelivery
-
1
include Mail::CheckDeliveryParams
-
-
1
if RUBY_VERSION >= '1.9.1'
-
1
require 'fileutils'
-
else
-
require 'ftools'
-
end
-
-
1
def initialize(values)
-
self.settings = { :location => './mails' }.merge!(values)
-
end
-
-
1
attr_accessor :settings
-
-
1
def deliver!(mail)
-
check_delivery_params(mail)
-
-
if ::File.respond_to?(:makedirs)
-
::File.makedirs settings[:location]
-
else
-
::FileUtils.mkdir_p settings[:location]
-
end
-
-
mail.destinations.uniq.each do |to|
-
::File.open(::File.join(settings[:location], File.basename(to.to_s)), 'a') { |f| "#{f.write(mail.encoded)}\r\n\r\n" }
-
end
-
end
-
-
end
-
end
-
1
require 'mail/check_delivery_params'
-
-
1
module Mail
-
# A delivery method implementation which sends via sendmail.
-
#
-
# To use this, first find out where the sendmail binary is on your computer,
-
# if you are on a mac or unix box, it is usually in /usr/sbin/sendmail, this will
-
# be your sendmail location.
-
#
-
# Mail.defaults do
-
# delivery_method :sendmail
-
# end
-
#
-
# Or if your sendmail binary is not at '/usr/sbin/sendmail'
-
#
-
# Mail.defaults do
-
# delivery_method :sendmail, :location => '/absolute/path/to/your/sendmail'
-
# end
-
#
-
# Then just deliver the email as normal:
-
#
-
# Mail.deliver do
-
# to 'mikel@test.lindsaar.net'
-
# from 'ada@test.lindsaar.net'
-
# subject 'testing sendmail'
-
# body 'testing sendmail'
-
# end
-
#
-
# Or by calling deliver on a Mail message
-
#
-
# mail = Mail.new do
-
# to 'mikel@test.lindsaar.net'
-
# from 'ada@test.lindsaar.net'
-
# subject 'testing sendmail'
-
# body 'testing sendmail'
-
# end
-
#
-
# mail.deliver!
-
1
class Sendmail
-
1
include Mail::CheckDeliveryParams
-
-
1
def initialize(values)
-
self.settings = { :location => '/usr/sbin/sendmail',
-
:arguments => '-i' }.merge(values)
-
end
-
-
1
attr_accessor :settings
-
-
1
def deliver!(mail)
-
smtp_from, smtp_to, message = check_delivery_params(mail)
-
-
from = "-f #{self.class.shellquote(smtp_from)}"
-
to = smtp_to.map { |to| self.class.shellquote(to) }.join(' ')
-
-
arguments = "#{settings[:arguments]} #{from} --"
-
self.class.call(settings[:location], arguments, to, message)
-
end
-
-
1
def self.call(path, arguments, destinations, encoded_message)
-
popen "#{path} #{arguments} #{destinations}" do |io|
-
io.puts encoded_message.to_lf
-
io.flush
-
end
-
end
-
-
1
if RUBY_VERSION < '1.9.0'
-
def self.popen(command, &block)
-
IO.popen "#{command} 2>&1", 'w+', &block
-
end
-
else
-
1
def self.popen(command, &block)
-
IO.popen command, 'w+', :err => :out, &block
-
end
-
end
-
-
# The following is an adaptation of ruby 1.9.2's shellwords.rb file,
-
# it is modified to include '+' in the allowed list to allow for
-
# sendmail to accept email addresses as the sender with a + in them.
-
1
def self.shellquote(address)
-
# Process as a single byte sequence because not all shell
-
# implementations are multibyte aware.
-
#
-
# A LF cannot be escaped with a backslash because a backslash + LF
-
# combo is regarded as line continuation and simply ignored. Strip it.
-
escaped = address.gsub(/([^A-Za-z0-9_\s\+\-.,:\/@])/n, "\\\\\\1").gsub("\n", '')
-
%("#{escaped}")
-
end
-
end
-
end
-
1
require 'mail/check_delivery_params'
-
-
1
module Mail
-
# == Sending Email with SMTP
-
#
-
# Mail allows you to send emails using SMTP. This is done by wrapping Net::SMTP in
-
# an easy to use manner.
-
#
-
# === Sending via SMTP server on Localhost
-
#
-
# Sending locally (to a postfix or sendmail server running on localhost) requires
-
# no special setup. Just to Mail.deliver &block or message.deliver! and it will
-
# be sent in this method.
-
#
-
# === Sending via MobileMe
-
#
-
# Mail.defaults do
-
# delivery_method :smtp, { :address => "smtp.me.com",
-
# :port => 587,
-
# :domain => 'your.host.name',
-
# :user_name => '<username>',
-
# :password => '<password>',
-
# :authentication => 'plain',
-
# :enable_starttls_auto => true }
-
# end
-
#
-
# === Sending via GMail
-
#
-
# Mail.defaults do
-
# delivery_method :smtp, { :address => "smtp.gmail.com",
-
# :port => 587,
-
# :domain => 'your.host.name',
-
# :user_name => '<username>',
-
# :password => '<password>',
-
# :authentication => 'plain',
-
# :enable_starttls_auto => true }
-
# end
-
#
-
# === Certificate verification
-
#
-
# When using TLS, some mail servers provide certificates that are self-signed
-
# or whose names do not exactly match the hostname given in the address.
-
# OpenSSL will reject these by default. The best remedy is to use the correct
-
# hostname or update the certificate authorities trusted by your ruby. If
-
# that isn't possible, you can control this behavior with
-
# an :openssl_verify_mode setting. Its value may be either an OpenSSL
-
# verify mode constant (OpenSSL::SSL::VERIFY_NONE), or a string containing
-
# the name of an OpenSSL verify mode (none, peer, client_once,
-
# fail_if_no_peer_cert).
-
#
-
# === Others
-
#
-
# Feel free to send me other examples that were tricky
-
#
-
# === Delivering the email
-
#
-
# Once you have the settings right, sending the email is done by:
-
#
-
# Mail.deliver do
-
# to 'mikel@test.lindsaar.net'
-
# from 'ada@test.lindsaar.net'
-
# subject 'testing sendmail'
-
# body 'testing sendmail'
-
# end
-
#
-
# Or by calling deliver on a Mail message
-
#
-
# mail = Mail.new do
-
# to 'mikel@test.lindsaar.net'
-
# from 'ada@test.lindsaar.net'
-
# subject 'testing sendmail'
-
# body 'testing sendmail'
-
# end
-
#
-
# mail.deliver!
-
1
class SMTP
-
1
include Mail::CheckDeliveryParams
-
-
1
def initialize(values)
-
self.settings = { :address => "localhost",
-
:port => 25,
-
:domain => 'localhost.localdomain',
-
:user_name => nil,
-
:password => nil,
-
:authentication => nil,
-
:enable_starttls_auto => true,
-
:openssl_verify_mode => nil,
-
:ssl => nil,
-
:tls => nil
-
}.merge!(values)
-
end
-
-
1
attr_accessor :settings
-
-
# Send the message via SMTP.
-
# The from and to attributes are optional. If not set, they are retrieve from the Message.
-
1
def deliver!(mail)
-
smtp_from, smtp_to, message = check_delivery_params(mail)
-
-
smtp = Net::SMTP.new(settings[:address], settings[:port])
-
if settings[:tls] || settings[:ssl]
-
if smtp.respond_to?(:enable_tls)
-
smtp.enable_tls(ssl_context)
-
end
-
elsif settings[:enable_starttls_auto]
-
if smtp.respond_to?(:enable_starttls_auto)
-
smtp.enable_starttls_auto(ssl_context)
-
end
-
end
-
-
response = nil
-
smtp.start(settings[:domain], settings[:user_name], settings[:password], settings[:authentication]) do |smtp_obj|
-
response = smtp_obj.sendmail(message, smtp_from, smtp_to)
-
end
-
-
if settings[:return_response]
-
response
-
else
-
self
-
end
-
end
-
-
-
1
private
-
-
# Allow SSL context to be configured via settings, for Ruby >= 1.9
-
# Just returns openssl verify mode for Ruby 1.8.x
-
1
def ssl_context
-
openssl_verify_mode = settings[:openssl_verify_mode]
-
-
if openssl_verify_mode.kind_of?(String)
-
openssl_verify_mode = "OpenSSL::SSL::VERIFY_#{openssl_verify_mode.upcase}".constantize
-
end
-
-
if RUBY_VERSION < '1.9.0'
-
openssl_verify_mode
-
else
-
context = Net::SMTP.default_ssl_context
-
context.verify_mode = openssl_verify_mode
-
context.ca_path = settings[:ca_path] if settings[:ca_path]
-
context.ca_file = settings[:ca_file] if settings[:ca_file]
-
context
-
end
-
end
-
end
-
end
-
1
require 'mail/check_delivery_params'
-
-
1
module Mail
-
# The TestMailer is a bare bones mailer that does nothing. It is useful
-
# when you are testing.
-
#
-
# It also provides a template of the minimum methods you require to implement
-
# if you want to make a custom mailer for Mail
-
1
class TestMailer
-
1
include Mail::CheckDeliveryParams
-
-
# Provides a store of all the emails sent with the TestMailer so you can check them.
-
1
def TestMailer.deliveries
-
@@deliveries ||= []
-
end
-
-
# Allows you to over write the default deliveries store from an array to some
-
# other object. If you just want to clear the store,
-
# call TestMailer.deliveries.clear.
-
#
-
# If you place another object here, please make sure it responds to:
-
#
-
# * << (message)
-
# * clear
-
# * length
-
# * size
-
# * and other common Array methods
-
1
def TestMailer.deliveries=(val)
-
@@deliveries = val
-
end
-
-
1
def initialize(values)
-
@settings = values.dup
-
end
-
-
1
attr_accessor :settings
-
-
1
def deliver!(mail)
-
check_delivery_params(mail)
-
Mail::TestMailer.deliveries << mail
-
end
-
-
end
-
end
-
# encoding: utf-8
-
-
1
module Mail
-
-
1
class Retriever
-
-
# Get the oldest received email(s)
-
#
-
# Possible options:
-
# count: number of emails to retrieve. The default value is 1.
-
# order: order of emails returned. Possible values are :asc or :desc. Default value is :asc.
-
#
-
1
def first(options = {}, &block)
-
options ||= {}
-
options[:what] = :first
-
options[:count] ||= 1
-
find(options, &block)
-
end
-
-
# Get the most recent received email(s)
-
#
-
# Possible options:
-
# count: number of emails to retrieve. The default value is 1.
-
# order: order of emails returned. Possible values are :asc or :desc. Default value is :asc.
-
#
-
1
def last(options = {}, &block)
-
options ||= {}
-
options[:what] = :last
-
options[:count] ||= 1
-
find(options, &block)
-
end
-
-
# Get all emails.
-
#
-
# Possible options:
-
# order: order of emails returned. Possible values are :asc or :desc. Default value is :asc.
-
#
-
1
def all(options = {}, &block)
-
options ||= {}
-
options[:count] = :all
-
find(options, &block)
-
end
-
-
# Find emails in the mailbox, and then deletes them. Without any options, the
-
# five last received emails are returned.
-
#
-
# Possible options:
-
# what: last or first emails. The default is :first.
-
# order: order of emails returned. Possible values are :asc or :desc. Default value is :asc.
-
# count: number of emails to retrieve. The default value is 10. A value of 1 returns an
-
# instance of Message, not an array of Message instances.
-
# delete_after_find: flag for whether to delete each retreived email after find. Default
-
# is true. Call #find if you would like this to default to false.
-
#
-
1
def find_and_delete(options = {}, &block)
-
options ||= {}
-
options[:delete_after_find] ||= true
-
find(options, &block)
-
end
-
-
end
-
-
end
-
# Autogenerated from a Treetop grammar. Edits may be lost.
-
-
-
1
module Mail
-
1
module AddressLists
-
1
include Treetop::Runtime
-
-
1
def root
-
@root ||= :primary_address
-
end
-
-
1
include RFC2822
-
-
1
module PrimaryAddress0
-
1
def addresses
-
([first_addr] + other_addr.elements.map { |o| o.addr_value }).reject { |e| e.empty? }
-
end
-
end
-
-
1
module PrimaryAddress1
-
1
def addresses
-
[first_addr] + other_addr.elements.map { |o| o.addr_value }
-
end
-
end
-
-
1
def _nt_primary_address
-
start_index = index
-
if node_cache[:primary_address].has_key?(index)
-
cached = node_cache[:primary_address][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_address_list
-
r1.extend(PrimaryAddress0)
-
if r1
-
r0 = r1
-
else
-
r2 = _nt_obs_addr_list
-
r2.extend(PrimaryAddress1)
-
if r2
-
r0 = r2
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:primary_address][start_index] = r0
-
-
r0
-
end
-
-
end
-
-
1
class AddressListsParser < Treetop::Runtime::CompiledParser
-
1
include AddressLists
-
end
-
-
end
-
# Autogenerated from a Treetop grammar. Edits may be lost.
-
-
-
1
module Mail
-
1
module ContentDisposition
-
1
include Treetop::Runtime
-
-
1
def root
-
@root ||= :content_disposition
-
end
-
-
1
include RFC2822
-
-
1
include RFC2045
-
-
1
module ContentDisposition0
-
1
def CFWS1
-
elements[0]
-
end
-
-
1
def parameter
-
elements[2]
-
end
-
-
1
def CFWS2
-
elements[3]
-
end
-
end
-
-
1
module ContentDisposition1
-
1
def disposition_type
-
elements[0]
-
end
-
-
1
def param_hashes
-
elements[1]
-
end
-
end
-
-
1
module ContentDisposition2
-
1
def parameters
-
param_hashes.elements.map do |param|
-
param.parameter.param_hash
-
end
-
end
-
end
-
-
1
def _nt_content_disposition
-
start_index = index
-
if node_cache[:content_disposition].has_key?(index)
-
cached = node_cache[:content_disposition][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_disposition_type
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
i3, s3 = index, []
-
r4 = _nt_CFWS
-
s3 << r4
-
if r4
-
if has_terminal?(";", false, index)
-
r5 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(";")
-
r5 = nil
-
end
-
s3 << r5
-
if r5
-
r6 = _nt_parameter
-
s3 << r6
-
if r6
-
r7 = _nt_CFWS
-
s3 << r7
-
end
-
end
-
end
-
if s3.last
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
r3.extend(ContentDisposition0)
-
else
-
@index = i3
-
r3 = nil
-
end
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ContentDisposition1)
-
r0.extend(ContentDisposition2)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:content_disposition][start_index] = r0
-
-
r0
-
end
-
-
1
module DispositionType0
-
end
-
-
1
module DispositionType1
-
end
-
-
1
def _nt_disposition_type
-
start_index = index
-
if node_cache[:disposition_type].has_key?(index)
-
cached = node_cache[:disposition_type][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
if has_terminal?('\G[iI]', true, index)
-
r2 = true
-
@index += 1
-
else
-
r2 = nil
-
end
-
s1 << r2
-
if r2
-
if has_terminal?('\G[nN]', true, index)
-
r3 = true
-
@index += 1
-
else
-
r3 = nil
-
end
-
s1 << r3
-
if r3
-
if has_terminal?('\G[lL]', true, index)
-
r4 = true
-
@index += 1
-
else
-
r4 = nil
-
end
-
s1 << r4
-
if r4
-
if has_terminal?('\G[iI]', true, index)
-
r5 = true
-
@index += 1
-
else
-
r5 = nil
-
end
-
s1 << r5
-
if r5
-
if has_terminal?('\G[nN]', true, index)
-
r6 = true
-
@index += 1
-
else
-
r6 = nil
-
end
-
s1 << r6
-
if r6
-
if has_terminal?('\G[eE]', true, index)
-
r7 = true
-
@index += 1
-
else
-
r7 = nil
-
end
-
s1 << r7
-
end
-
end
-
end
-
end
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(DispositionType0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
i8, s8 = index, []
-
if has_terminal?('\G[aA]', true, index)
-
r9 = true
-
@index += 1
-
else
-
r9 = nil
-
end
-
s8 << r9
-
if r9
-
if has_terminal?('\G[tT]', true, index)
-
r10 = true
-
@index += 1
-
else
-
r10 = nil
-
end
-
s8 << r10
-
if r10
-
if has_terminal?('\G[tT]', true, index)
-
r11 = true
-
@index += 1
-
else
-
r11 = nil
-
end
-
s8 << r11
-
if r11
-
if has_terminal?('\G[aA]', true, index)
-
r12 = true
-
@index += 1
-
else
-
r12 = nil
-
end
-
s8 << r12
-
if r12
-
if has_terminal?('\G[cC]', true, index)
-
r13 = true
-
@index += 1
-
else
-
r13 = nil
-
end
-
s8 << r13
-
if r13
-
if has_terminal?('\G[hH]', true, index)
-
r14 = true
-
@index += 1
-
else
-
r14 = nil
-
end
-
s8 << r14
-
if r14
-
if has_terminal?('\G[mM]', true, index)
-
r15 = true
-
@index += 1
-
else
-
r15 = nil
-
end
-
s8 << r15
-
if r15
-
if has_terminal?('\G[eE]', true, index)
-
r16 = true
-
@index += 1
-
else
-
r16 = nil
-
end
-
s8 << r16
-
if r16
-
if has_terminal?('\G[nN]', true, index)
-
r17 = true
-
@index += 1
-
else
-
r17 = nil
-
end
-
s8 << r17
-
if r17
-
if has_terminal?('\G[tT]', true, index)
-
r18 = true
-
@index += 1
-
else
-
r18 = nil
-
end
-
s8 << r18
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
if s8.last
-
r8 = instantiate_node(SyntaxNode,input, i8...index, s8)
-
r8.extend(DispositionType1)
-
else
-
@index = i8
-
r8 = nil
-
end
-
if r8
-
r0 = r8
-
else
-
r19 = _nt_extension_token
-
if r19
-
r0 = r19
-
else
-
if has_terminal?('', false, index)
-
r20 = instantiate_node(SyntaxNode,input, index...(index + 0))
-
@index += 0
-
else
-
terminal_parse_failure('')
-
r20 = nil
-
end
-
if r20
-
r0 = r20
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
-
node_cache[:disposition_type][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_extension_token
-
start_index = index
-
if node_cache[:extension_token].has_key?(index)
-
cached = node_cache[:extension_token][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_ietf_token
-
if r1
-
r0 = r1
-
else
-
r2 = _nt_custom_x_token
-
if r2
-
r0 = r2
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:extension_token][start_index] = r0
-
-
r0
-
end
-
-
1
module Parameter0
-
1
def attr
-
elements[1]
-
end
-
-
1
def val
-
elements[3]
-
end
-
-
end
-
-
1
module Parameter1
-
1
def param_hash
-
{attr.text_value => val.text_value}
-
end
-
end
-
-
1
def _nt_parameter
-
start_index = index
-
if node_cache[:parameter].has_key?(index)
-
cached = node_cache[:parameter][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r2 = _nt_CFWS
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
r3 = _nt_attribute
-
s0 << r3
-
if r3
-
if has_terminal?("=", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("=")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_value
-
s0 << r5
-
if r5
-
r7 = _nt_CFWS
-
if r7
-
r6 = r7
-
else
-
r6 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(Parameter0)
-
r0.extend(Parameter1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:parameter][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_attribute
-
start_index = index
-
if node_cache[:attribute].has_key?(index)
-
cached = node_cache[:attribute][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
s0, i0 = [], index
-
loop do
-
r1 = _nt_token
-
if r1
-
s0 << r1
-
else
-
break
-
end
-
end
-
if s0.empty?
-
@index = i0
-
r0 = nil
-
else
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
end
-
-
node_cache[:attribute][start_index] = r0
-
-
r0
-
end
-
-
1
module Value0
-
1
def text_value
-
quoted_content.text_value
-
end
-
end
-
-
1
def _nt_value
-
start_index = index
-
if node_cache[:value].has_key?(index)
-
cached = node_cache[:value][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_quoted_string
-
r1.extend(Value0)
-
if r1
-
r0 = r1
-
else
-
s2, i2 = [], index
-
loop do
-
i3 = index
-
r4 = _nt_token
-
if r4
-
r3 = r4
-
else
-
if has_terminal?('\G[\\x3d]', true, index)
-
r5 = true
-
@index += 1
-
else
-
r5 = nil
-
end
-
if r5
-
r3 = r5
-
else
-
@index = i3
-
r3 = nil
-
end
-
end
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
if s2.empty?
-
@index = i2
-
r2 = nil
-
else
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
end
-
if r2
-
r0 = r2
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:value][start_index] = r0
-
-
r0
-
end
-
-
end
-
-
1
class ContentDispositionParser < Treetop::Runtime::CompiledParser
-
1
include ContentDisposition
-
end
-
-
end
-
# Autogenerated from a Treetop grammar. Edits may be lost.
-
-
-
1
module Mail
-
1
module ContentLocation
-
1
include Treetop::Runtime
-
-
1
def root
-
@root ||= :primary
-
end
-
-
1
include RFC2822
-
-
1
include RFC2045
-
-
1
module Primary0
-
1
def CFWS1
-
elements[0]
-
end
-
-
1
def location
-
elements[1]
-
end
-
-
1
def CFWS2
-
elements[2]
-
end
-
end
-
-
1
def _nt_primary
-
start_index = index
-
if node_cache[:primary].has_key?(index)
-
cached = node_cache[:primary][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_CFWS
-
s0 << r1
-
if r1
-
r2 = _nt_location
-
s0 << r2
-
if r2
-
r3 = _nt_CFWS
-
s0 << r3
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(Primary0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:primary][start_index] = r0
-
-
r0
-
end
-
-
1
module Location0
-
1
def text_value
-
quoted_content.text_value
-
end
-
end
-
-
1
def _nt_location
-
start_index = index
-
if node_cache[:location].has_key?(index)
-
cached = node_cache[:location][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_quoted_string
-
r1.extend(Location0)
-
if r1
-
r0 = r1
-
else
-
s2, i2 = [], index
-
loop do
-
i3 = index
-
r4 = _nt_token
-
if r4
-
r3 = r4
-
else
-
if has_terminal?('\G[\\x3d]', true, index)
-
r5 = true
-
@index += 1
-
else
-
r5 = nil
-
end
-
if r5
-
r3 = r5
-
else
-
@index = i3
-
r3 = nil
-
end
-
end
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
if s2.empty?
-
@index = i2
-
r2 = nil
-
else
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
end
-
if r2
-
r0 = r2
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:location][start_index] = r0
-
-
r0
-
end
-
-
end
-
-
1
class ContentLocationParser < Treetop::Runtime::CompiledParser
-
1
include ContentLocation
-
end
-
-
end
-
# Autogenerated from a Treetop grammar. Edits may be lost.
-
-
-
1
module Mail
-
1
module ContentTransferEncoding
-
1
include Treetop::Runtime
-
-
1
def root
-
@root ||= :primary
-
end
-
-
1
include RFC2822
-
-
1
include RFC2045
-
-
1
module Primary0
-
1
def CFWS1
-
elements[0]
-
end
-
-
1
def encoding
-
elements[1]
-
end
-
-
1
def CFWS2
-
elements[2]
-
end
-
-
1
def CFWS3
-
elements[4]
-
end
-
end
-
-
1
def _nt_primary
-
start_index = index
-
if node_cache[:primary].has_key?(index)
-
cached = node_cache[:primary][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_CFWS
-
s0 << r1
-
if r1
-
r2 = _nt_encoding
-
s0 << r2
-
if r2
-
r3 = _nt_CFWS
-
s0 << r3
-
if r3
-
if has_terminal?(";", false, index)
-
r5 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(";")
-
r5 = nil
-
end
-
if r5
-
r4 = r5
-
else
-
r4 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r4
-
if r4
-
r6 = _nt_CFWS
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(Primary0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:primary][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_encoding
-
start_index = index
-
if node_cache[:encoding].has_key?(index)
-
cached = node_cache[:encoding][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
if has_terminal?("7bits", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 5))
-
@index += 5
-
else
-
terminal_parse_failure("7bits")
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
if has_terminal?("8bits", false, index)
-
r2 = instantiate_node(SyntaxNode,input, index...(index + 5))
-
@index += 5
-
else
-
terminal_parse_failure("8bits")
-
r2 = nil
-
end
-
if r2
-
r0 = r2
-
else
-
if has_terminal?("7bit", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 4))
-
@index += 4
-
else
-
terminal_parse_failure("7bit")
-
r3 = nil
-
end
-
if r3
-
r0 = r3
-
else
-
if has_terminal?("8bit", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 4))
-
@index += 4
-
else
-
terminal_parse_failure("8bit")
-
r4 = nil
-
end
-
if r4
-
r0 = r4
-
else
-
if has_terminal?("binary", false, index)
-
r5 = instantiate_node(SyntaxNode,input, index...(index + 6))
-
@index += 6
-
else
-
terminal_parse_failure("binary")
-
r5 = nil
-
end
-
if r5
-
r0 = r5
-
else
-
if has_terminal?("quoted-printable", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 16))
-
@index += 16
-
else
-
terminal_parse_failure("quoted-printable")
-
r6 = nil
-
end
-
if r6
-
r0 = r6
-
else
-
if has_terminal?("base64", false, index)
-
r7 = instantiate_node(SyntaxNode,input, index...(index + 6))
-
@index += 6
-
else
-
terminal_parse_failure("base64")
-
r7 = nil
-
end
-
if r7
-
r0 = r7
-
else
-
r8 = _nt_ietf_token
-
if r8
-
r0 = r8
-
else
-
r9 = _nt_custom_x_token
-
if r9
-
r0 = r9
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
-
node_cache[:encoding][start_index] = r0
-
-
r0
-
end
-
-
end
-
-
1
class ContentTransferEncodingParser < Treetop::Runtime::CompiledParser
-
1
include ContentTransferEncoding
-
end
-
-
end
-
# Autogenerated from a Treetop grammar. Edits may be lost.
-
-
-
1
module Mail
-
1
module ContentType
-
1
include Treetop::Runtime
-
-
1
def root
-
@root ||= :content_type
-
end
-
-
1
include RFC2822
-
-
1
include RFC2045
-
-
1
module ContentType0
-
1
def CFWS1
-
elements[0]
-
end
-
-
1
def parameter
-
elements[2]
-
end
-
-
1
def CFWS2
-
elements[3]
-
end
-
end
-
-
1
module ContentType1
-
1
def main_type
-
elements[0]
-
end
-
-
1
def sub_type
-
elements[2]
-
end
-
-
1
def param_hashes
-
elements[3]
-
end
-
end
-
-
1
module ContentType2
-
1
def parameters
-
param_hashes.elements.map do |param|
-
param.parameter.param_hash
-
end
-
end
-
end
-
-
1
def _nt_content_type
-
start_index = index
-
if node_cache[:content_type].has_key?(index)
-
cached = node_cache[:content_type][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_main_type
-
s0 << r1
-
if r1
-
if has_terminal?("/", false, index)
-
r2 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("/")
-
r2 = nil
-
end
-
s0 << r2
-
if r2
-
r3 = _nt_sub_type
-
s0 << r3
-
if r3
-
s4, i4 = [], index
-
loop do
-
i5, s5 = index, []
-
r6 = _nt_CFWS
-
s5 << r6
-
if r6
-
s7, i7 = [], index
-
loop do
-
if has_terminal?(";", false, index)
-
r8 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(";")
-
r8 = nil
-
end
-
if r8
-
s7 << r8
-
else
-
break
-
end
-
end
-
r7 = instantiate_node(SyntaxNode,input, i7...index, s7)
-
s5 << r7
-
if r7
-
r9 = _nt_parameter
-
s5 << r9
-
if r9
-
r10 = _nt_CFWS
-
s5 << r10
-
end
-
end
-
end
-
if s5.last
-
r5 = instantiate_node(SyntaxNode,input, i5...index, s5)
-
r5.extend(ContentType0)
-
else
-
@index = i5
-
r5 = nil
-
end
-
if r5
-
s4 << r5
-
else
-
break
-
end
-
end
-
r4 = instantiate_node(SyntaxNode,input, i4...index, s4)
-
s0 << r4
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ContentType1)
-
r0.extend(ContentType2)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:content_type][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_main_type
-
start_index = index
-
if node_cache[:main_type].has_key?(index)
-
cached = node_cache[:main_type][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_discrete_type
-
if r1
-
r0 = r1
-
else
-
r2 = _nt_composite_type
-
if r2
-
r0 = r2
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:main_type][start_index] = r0
-
-
r0
-
end
-
-
1
module DiscreteType0
-
end
-
-
1
module DiscreteType1
-
end
-
-
1
module DiscreteType2
-
end
-
-
1
module DiscreteType3
-
end
-
-
1
module DiscreteType4
-
end
-
-
1
def _nt_discrete_type
-
start_index = index
-
if node_cache[:discrete_type].has_key?(index)
-
cached = node_cache[:discrete_type][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
if has_terminal?('\G[tT]', true, index)
-
r2 = true
-
@index += 1
-
else
-
r2 = nil
-
end
-
s1 << r2
-
if r2
-
if has_terminal?('\G[eE]', true, index)
-
r3 = true
-
@index += 1
-
else
-
r3 = nil
-
end
-
s1 << r3
-
if r3
-
if has_terminal?('\G[xX]', true, index)
-
r4 = true
-
@index += 1
-
else
-
r4 = nil
-
end
-
s1 << r4
-
if r4
-
if has_terminal?('\G[tT]', true, index)
-
r5 = true
-
@index += 1
-
else
-
r5 = nil
-
end
-
s1 << r5
-
end
-
end
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(DiscreteType0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
i6, s6 = index, []
-
if has_terminal?('\G[iI]', true, index)
-
r7 = true
-
@index += 1
-
else
-
r7 = nil
-
end
-
s6 << r7
-
if r7
-
if has_terminal?('\G[mM]', true, index)
-
r8 = true
-
@index += 1
-
else
-
r8 = nil
-
end
-
s6 << r8
-
if r8
-
if has_terminal?('\G[aA]', true, index)
-
r9 = true
-
@index += 1
-
else
-
r9 = nil
-
end
-
s6 << r9
-
if r9
-
if has_terminal?('\G[gG]', true, index)
-
r10 = true
-
@index += 1
-
else
-
r10 = nil
-
end
-
s6 << r10
-
if r10
-
if has_terminal?('\G[eE]', true, index)
-
r11 = true
-
@index += 1
-
else
-
r11 = nil
-
end
-
s6 << r11
-
end
-
end
-
end
-
end
-
if s6.last
-
r6 = instantiate_node(SyntaxNode,input, i6...index, s6)
-
r6.extend(DiscreteType1)
-
else
-
@index = i6
-
r6 = nil
-
end
-
if r6
-
r0 = r6
-
else
-
i12, s12 = index, []
-
if has_terminal?('\G[aA]', true, index)
-
r13 = true
-
@index += 1
-
else
-
r13 = nil
-
end
-
s12 << r13
-
if r13
-
if has_terminal?('\G[uU]', true, index)
-
r14 = true
-
@index += 1
-
else
-
r14 = nil
-
end
-
s12 << r14
-
if r14
-
if has_terminal?('\G[dD]', true, index)
-
r15 = true
-
@index += 1
-
else
-
r15 = nil
-
end
-
s12 << r15
-
if r15
-
if has_terminal?('\G[iI]', true, index)
-
r16 = true
-
@index += 1
-
else
-
r16 = nil
-
end
-
s12 << r16
-
if r16
-
if has_terminal?('\G[oO]', true, index)
-
r17 = true
-
@index += 1
-
else
-
r17 = nil
-
end
-
s12 << r17
-
end
-
end
-
end
-
end
-
if s12.last
-
r12 = instantiate_node(SyntaxNode,input, i12...index, s12)
-
r12.extend(DiscreteType2)
-
else
-
@index = i12
-
r12 = nil
-
end
-
if r12
-
r0 = r12
-
else
-
i18, s18 = index, []
-
if has_terminal?('\G[vV]', true, index)
-
r19 = true
-
@index += 1
-
else
-
r19 = nil
-
end
-
s18 << r19
-
if r19
-
if has_terminal?('\G[iI]', true, index)
-
r20 = true
-
@index += 1
-
else
-
r20 = nil
-
end
-
s18 << r20
-
if r20
-
if has_terminal?('\G[dD]', true, index)
-
r21 = true
-
@index += 1
-
else
-
r21 = nil
-
end
-
s18 << r21
-
if r21
-
if has_terminal?('\G[eE]', true, index)
-
r22 = true
-
@index += 1
-
else
-
r22 = nil
-
end
-
s18 << r22
-
if r22
-
if has_terminal?('\G[oO]', true, index)
-
r23 = true
-
@index += 1
-
else
-
r23 = nil
-
end
-
s18 << r23
-
end
-
end
-
end
-
end
-
if s18.last
-
r18 = instantiate_node(SyntaxNode,input, i18...index, s18)
-
r18.extend(DiscreteType3)
-
else
-
@index = i18
-
r18 = nil
-
end
-
if r18
-
r0 = r18
-
else
-
i24, s24 = index, []
-
if has_terminal?('\G[aA]', true, index)
-
r25 = true
-
@index += 1
-
else
-
r25 = nil
-
end
-
s24 << r25
-
if r25
-
if has_terminal?('\G[pP]', true, index)
-
r26 = true
-
@index += 1
-
else
-
r26 = nil
-
end
-
s24 << r26
-
if r26
-
if has_terminal?('\G[pP]', true, index)
-
r27 = true
-
@index += 1
-
else
-
r27 = nil
-
end
-
s24 << r27
-
if r27
-
if has_terminal?('\G[lL]', true, index)
-
r28 = true
-
@index += 1
-
else
-
r28 = nil
-
end
-
s24 << r28
-
if r28
-
if has_terminal?('\G[iI]', true, index)
-
r29 = true
-
@index += 1
-
else
-
r29 = nil
-
end
-
s24 << r29
-
if r29
-
if has_terminal?('\G[cC]', true, index)
-
r30 = true
-
@index += 1
-
else
-
r30 = nil
-
end
-
s24 << r30
-
if r30
-
if has_terminal?('\G[aA]', true, index)
-
r31 = true
-
@index += 1
-
else
-
r31 = nil
-
end
-
s24 << r31
-
if r31
-
if has_terminal?('\G[tT]', true, index)
-
r32 = true
-
@index += 1
-
else
-
r32 = nil
-
end
-
s24 << r32
-
if r32
-
if has_terminal?('\G[iI]', true, index)
-
r33 = true
-
@index += 1
-
else
-
r33 = nil
-
end
-
s24 << r33
-
if r33
-
if has_terminal?('\G[oO]', true, index)
-
r34 = true
-
@index += 1
-
else
-
r34 = nil
-
end
-
s24 << r34
-
if r34
-
if has_terminal?('\G[nN]', true, index)
-
r35 = true
-
@index += 1
-
else
-
r35 = nil
-
end
-
s24 << r35
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
if s24.last
-
r24 = instantiate_node(SyntaxNode,input, i24...index, s24)
-
r24.extend(DiscreteType4)
-
else
-
@index = i24
-
r24 = nil
-
end
-
if r24
-
r0 = r24
-
else
-
r36 = _nt_extension_token
-
if r36
-
r0 = r36
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
end
-
end
-
-
node_cache[:discrete_type][start_index] = r0
-
-
r0
-
end
-
-
1
module CompositeType0
-
end
-
-
1
module CompositeType1
-
end
-
-
1
def _nt_composite_type
-
start_index = index
-
if node_cache[:composite_type].has_key?(index)
-
cached = node_cache[:composite_type][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
if has_terminal?('\G[mM]', true, index)
-
r2 = true
-
@index += 1
-
else
-
r2 = nil
-
end
-
s1 << r2
-
if r2
-
if has_terminal?('\G[eE]', true, index)
-
r3 = true
-
@index += 1
-
else
-
r3 = nil
-
end
-
s1 << r3
-
if r3
-
if has_terminal?('\G[sS]', true, index)
-
r4 = true
-
@index += 1
-
else
-
r4 = nil
-
end
-
s1 << r4
-
if r4
-
if has_terminal?('\G[sS]', true, index)
-
r5 = true
-
@index += 1
-
else
-
r5 = nil
-
end
-
s1 << r5
-
if r5
-
if has_terminal?('\G[aA]', true, index)
-
r6 = true
-
@index += 1
-
else
-
r6 = nil
-
end
-
s1 << r6
-
if r6
-
if has_terminal?('\G[gG]', true, index)
-
r7 = true
-
@index += 1
-
else
-
r7 = nil
-
end
-
s1 << r7
-
if r7
-
if has_terminal?('\G[eE]', true, index)
-
r8 = true
-
@index += 1
-
else
-
r8 = nil
-
end
-
s1 << r8
-
end
-
end
-
end
-
end
-
end
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(CompositeType0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
i9, s9 = index, []
-
if has_terminal?('\G[mM]', true, index)
-
r10 = true
-
@index += 1
-
else
-
r10 = nil
-
end
-
s9 << r10
-
if r10
-
if has_terminal?('\G[uU]', true, index)
-
r11 = true
-
@index += 1
-
else
-
r11 = nil
-
end
-
s9 << r11
-
if r11
-
if has_terminal?('\G[lL]', true, index)
-
r12 = true
-
@index += 1
-
else
-
r12 = nil
-
end
-
s9 << r12
-
if r12
-
if has_terminal?('\G[tT]', true, index)
-
r13 = true
-
@index += 1
-
else
-
r13 = nil
-
end
-
s9 << r13
-
if r13
-
if has_terminal?('\G[iI]', true, index)
-
r14 = true
-
@index += 1
-
else
-
r14 = nil
-
end
-
s9 << r14
-
if r14
-
if has_terminal?('\G[pP]', true, index)
-
r15 = true
-
@index += 1
-
else
-
r15 = nil
-
end
-
s9 << r15
-
if r15
-
if has_terminal?('\G[aA]', true, index)
-
r16 = true
-
@index += 1
-
else
-
r16 = nil
-
end
-
s9 << r16
-
if r16
-
if has_terminal?('\G[rR]', true, index)
-
r17 = true
-
@index += 1
-
else
-
r17 = nil
-
end
-
s9 << r17
-
if r17
-
if has_terminal?('\G[tT]', true, index)
-
r18 = true
-
@index += 1
-
else
-
r18 = nil
-
end
-
s9 << r18
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
if s9.last
-
r9 = instantiate_node(SyntaxNode,input, i9...index, s9)
-
r9.extend(CompositeType1)
-
else
-
@index = i9
-
r9 = nil
-
end
-
if r9
-
r0 = r9
-
else
-
r19 = _nt_extension_token
-
if r19
-
r0 = r19
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
-
node_cache[:composite_type][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_extension_token
-
start_index = index
-
if node_cache[:extension_token].has_key?(index)
-
cached = node_cache[:extension_token][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_ietf_token
-
if r1
-
r0 = r1
-
else
-
r2 = _nt_custom_x_token
-
if r2
-
r0 = r2
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:extension_token][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_sub_type
-
start_index = index
-
if node_cache[:sub_type].has_key?(index)
-
cached = node_cache[:sub_type][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_extension_token
-
if r1
-
r0 = r1
-
else
-
r2 = _nt_iana_token
-
if r2
-
r0 = r2
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:sub_type][start_index] = r0
-
-
r0
-
end
-
-
1
module Parameter0
-
1
def attr
-
elements[1]
-
end
-
-
1
def val
-
elements[3]
-
end
-
-
end
-
-
1
module Parameter1
-
1
def param_hash
-
{attr.text_value => val.text_value}
-
end
-
end
-
-
1
def _nt_parameter
-
start_index = index
-
if node_cache[:parameter].has_key?(index)
-
cached = node_cache[:parameter][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r2 = _nt_CFWS
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
r3 = _nt_attribute
-
s0 << r3
-
if r3
-
if has_terminal?("=", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("=")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_value
-
s0 << r5
-
if r5
-
r7 = _nt_CFWS
-
if r7
-
r6 = r7
-
else
-
r6 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(Parameter0)
-
r0.extend(Parameter1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:parameter][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_attribute
-
start_index = index
-
if node_cache[:attribute].has_key?(index)
-
cached = node_cache[:attribute][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
s0, i0 = [], index
-
loop do
-
r1 = _nt_token
-
if r1
-
s0 << r1
-
else
-
break
-
end
-
end
-
if s0.empty?
-
@index = i0
-
r0 = nil
-
else
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
end
-
-
node_cache[:attribute][start_index] = r0
-
-
r0
-
end
-
-
1
module Value0
-
1
def text_value
-
quoted_content.text_value
-
end
-
end
-
-
1
def _nt_value
-
start_index = index
-
if node_cache[:value].has_key?(index)
-
cached = node_cache[:value][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_quoted_string
-
r1.extend(Value0)
-
if r1
-
r0 = r1
-
else
-
s2, i2 = [], index
-
loop do
-
i3 = index
-
r4 = _nt_token
-
if r4
-
r3 = r4
-
else
-
if has_terminal?('\G[\\x3d]', true, index)
-
r5 = true
-
@index += 1
-
else
-
r5 = nil
-
end
-
if r5
-
r3 = r5
-
else
-
@index = i3
-
r3 = nil
-
end
-
end
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
if s2.empty?
-
@index = i2
-
r2 = nil
-
else
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
end
-
if r2
-
r0 = r2
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:value][start_index] = r0
-
-
r0
-
end
-
-
end
-
-
1
class ContentTypeParser < Treetop::Runtime::CompiledParser
-
1
include ContentType
-
end
-
-
end
-
# Autogenerated from a Treetop grammar. Edits may be lost.
-
-
-
1
module Mail
-
1
module DateTime
-
1
include Treetop::Runtime
-
-
1
def root
-
@root ||= :primary
-
end
-
-
1
include RFC2822
-
-
1
module Primary0
-
1
def day_of_week
-
elements[0]
-
end
-
-
end
-
-
1
module Primary1
-
1
def date
-
elements[1]
-
end
-
-
1
def FWS
-
elements[2]
-
end
-
-
1
def time
-
elements[3]
-
end
-
-
end
-
-
1
def _nt_primary
-
start_index = index
-
if node_cache[:primary].has_key?(index)
-
cached = node_cache[:primary][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
i2, s2 = index, []
-
r3 = _nt_day_of_week
-
s2 << r3
-
if r3
-
if has_terminal?(",", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(",")
-
r4 = nil
-
end
-
s2 << r4
-
end
-
if s2.last
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
r2.extend(Primary0)
-
else
-
@index = i2
-
r2 = nil
-
end
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
r5 = _nt_date
-
s0 << r5
-
if r5
-
r6 = _nt_FWS
-
s0 << r6
-
if r6
-
r7 = _nt_time
-
s0 << r7
-
if r7
-
r9 = _nt_CFWS
-
if r9
-
r8 = r9
-
else
-
r8 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r8
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(Primary1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:primary][start_index] = r0
-
-
r0
-
end
-
-
end
-
-
1
class DateTimeParser < Treetop::Runtime::CompiledParser
-
1
include DateTime
-
end
-
-
end
-
# Autogenerated from a Treetop grammar. Edits may be lost.
-
-
-
1
module Mail
-
1
module EnvelopeFrom
-
1
include Treetop::Runtime
-
-
1
def root
-
@root ||= :primary
-
end
-
-
1
include RFC2822
-
-
1
module Primary0
-
1
def addr_spec
-
elements[0]
-
end
-
-
1
def ctime_date
-
elements[1]
-
end
-
end
-
-
1
def _nt_primary
-
start_index = index
-
if node_cache[:primary].has_key?(index)
-
cached = node_cache[:primary][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_addr_spec
-
s0 << r1
-
if r1
-
r2 = _nt_ctime_date
-
s0 << r2
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(Primary0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:primary][start_index] = r0
-
-
r0
-
end
-
-
1
module CtimeDate0
-
1
def day_name
-
elements[0]
-
end
-
-
1
def month_name
-
elements[2]
-
end
-
-
1
def day
-
elements[4]
-
end
-
-
1
def time_of_day
-
elements[6]
-
end
-
-
1
def year
-
elements[8]
-
end
-
end
-
-
1
def _nt_ctime_date
-
start_index = index
-
if node_cache[:ctime_date].has_key?(index)
-
cached = node_cache[:ctime_date][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_day_name
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
if has_terminal?(" ", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(" ")
-
r3 = nil
-
end
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
if s2.empty?
-
@index = i2
-
r2 = nil
-
else
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
end
-
s0 << r2
-
if r2
-
r4 = _nt_month_name
-
s0 << r4
-
if r4
-
s5, i5 = [], index
-
loop do
-
if has_terminal?(" ", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(" ")
-
r6 = nil
-
end
-
if r6
-
s5 << r6
-
else
-
break
-
end
-
end
-
if s5.empty?
-
@index = i5
-
r5 = nil
-
else
-
r5 = instantiate_node(SyntaxNode,input, i5...index, s5)
-
end
-
s0 << r5
-
if r5
-
r7 = _nt_day
-
s0 << r7
-
if r7
-
if has_terminal?(" ", false, index)
-
r8 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(" ")
-
r8 = nil
-
end
-
s0 << r8
-
if r8
-
r9 = _nt_time_of_day
-
s0 << r9
-
if r9
-
if has_terminal?(" ", false, index)
-
r10 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(" ")
-
r10 = nil
-
end
-
s0 << r10
-
if r10
-
r11 = _nt_year
-
s0 << r11
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(CtimeDate0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:ctime_date][start_index] = r0
-
-
r0
-
end
-
-
end
-
-
1
class EnvelopeFromParser < Treetop::Runtime::CompiledParser
-
1
include EnvelopeFrom
-
end
-
-
end
-
# Autogenerated from a Treetop grammar. Edits may be lost.
-
-
-
1
module Mail
-
1
module MessageIds
-
1
include Treetop::Runtime
-
-
1
def root
-
@root ||= :primary
-
end
-
-
1
include RFC2822
-
-
1
module Primary0
-
1
def message_ids
-
[first_msg_id] + other_msg_ids.elements.map { |o| o.msg_id_value }
-
end
-
end
-
-
1
def _nt_primary
-
start_index = index
-
if node_cache[:primary].has_key?(index)
-
cached = node_cache[:primary][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
r0 = _nt_message_ids
-
r0.extend(Primary0)
-
-
node_cache[:primary][start_index] = r0
-
-
r0
-
end
-
-
end
-
-
1
class MessageIdsParser < Treetop::Runtime::CompiledParser
-
1
include MessageIds
-
end
-
-
end
-
# Autogenerated from a Treetop grammar. Edits may be lost.
-
-
-
1
module Mail
-
1
module MimeVersion
-
1
include Treetop::Runtime
-
-
1
def root
-
@root ||= :version
-
end
-
-
1
include RFC2822
-
-
1
module Version0
-
1
def CFWS1
-
elements[0]
-
end
-
-
1
def major_digits
-
elements[1]
-
end
-
-
1
def minor_digits
-
elements[5]
-
end
-
-
1
def CFWS2
-
elements[6]
-
end
-
end
-
-
1
module Version1
-
1
def major
-
major_digits
-
end
-
-
1
def minor
-
minor_digits
-
end
-
end
-
-
1
def _nt_version
-
start_index = index
-
if node_cache[:version].has_key?(index)
-
cached = node_cache[:version][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_CFWS
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_DIGIT
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
if s2.empty?
-
@index = i2
-
r2 = nil
-
else
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
end
-
s0 << r2
-
if r2
-
r5 = _nt_comment
-
if r5
-
r4 = r5
-
else
-
r4 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r4
-
if r4
-
if has_terminal?(".", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(".")
-
r6 = nil
-
end
-
s0 << r6
-
if r6
-
r8 = _nt_comment
-
if r8
-
r7 = r8
-
else
-
r7 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r7
-
if r7
-
s9, i9 = [], index
-
loop do
-
r10 = _nt_DIGIT
-
if r10
-
s9 << r10
-
else
-
break
-
end
-
end
-
if s9.empty?
-
@index = i9
-
r9 = nil
-
else
-
r9 = instantiate_node(SyntaxNode,input, i9...index, s9)
-
end
-
s0 << r9
-
if r9
-
r11 = _nt_CFWS
-
s0 << r11
-
end
-
end
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(Version0)
-
r0.extend(Version1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:version][start_index] = r0
-
-
r0
-
end
-
-
end
-
-
1
class MimeVersionParser < Treetop::Runtime::CompiledParser
-
1
include MimeVersion
-
end
-
-
end
-
# Autogenerated from a Treetop grammar. Edits may be lost.
-
-
-
1
module Mail
-
1
module PhraseLists
-
1
include Treetop::Runtime
-
-
1
def root
-
@root ||= :primary_phrase
-
end
-
-
1
include RFC2822
-
-
1
module PrimaryPhrase0
-
1
def phrases
-
[first_phrase] + other_phrases.elements.map { |o| o.phrase_value }
-
end
-
end
-
-
1
def _nt_primary_phrase
-
start_index = index
-
if node_cache[:primary_phrase].has_key?(index)
-
cached = node_cache[:primary_phrase][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
r0 = _nt_phrase_list
-
r0.extend(PrimaryPhrase0)
-
-
node_cache[:primary_phrase][start_index] = r0
-
-
r0
-
end
-
-
end
-
-
1
class PhraseListsParser < Treetop::Runtime::CompiledParser
-
1
include PhraseLists
-
end
-
-
end
-
# Autogenerated from a Treetop grammar. Edits may be lost.
-
-
-
1
module Mail
-
1
module Received
-
1
include Treetop::Runtime
-
-
1
def root
-
@root ||= :primary
-
end
-
-
1
include RFC2822
-
-
1
module Primary0
-
1
def name_val_list
-
elements[0]
-
end
-
-
1
def date_time
-
elements[2]
-
end
-
end
-
-
1
def _nt_primary
-
start_index = index
-
if node_cache[:primary].has_key?(index)
-
cached = node_cache[:primary][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_name_val_list
-
s0 << r1
-
if r1
-
if has_terminal?(";", false, index)
-
r2 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(";")
-
r2 = nil
-
end
-
s0 << r2
-
if r2
-
r3 = _nt_date_time
-
s0 << r3
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(Primary0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:primary][start_index] = r0
-
-
r0
-
end
-
-
end
-
-
1
class ReceivedParser < Treetop::Runtime::CompiledParser
-
1
include Received
-
end
-
-
end
-
# Autogenerated from a Treetop grammar. Edits may be lost.
-
-
-
1
module Mail
-
1
module RFC2045
-
1
include Treetop::Runtime
-
-
1
def root
-
@root ||= :tspecials
-
end
-
-
1
def _nt_tspecials
-
start_index = index
-
if node_cache[:tspecials].has_key?(index)
-
cached = node_cache[:tspecials][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
if has_terminal?("(", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("(")
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
if has_terminal?(")", false, index)
-
r2 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(")")
-
r2 = nil
-
end
-
if r2
-
r0 = r2
-
else
-
if has_terminal?("<", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("<")
-
r3 = nil
-
end
-
if r3
-
r0 = r3
-
else
-
if has_terminal?(">", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(">")
-
r4 = nil
-
end
-
if r4
-
r0 = r4
-
else
-
if has_terminal?("@", false, index)
-
r5 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("@")
-
r5 = nil
-
end
-
if r5
-
r0 = r5
-
else
-
if has_terminal?(",", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(",")
-
r6 = nil
-
end
-
if r6
-
r0 = r6
-
else
-
if has_terminal?(";", false, index)
-
r7 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(";")
-
r7 = nil
-
end
-
if r7
-
r0 = r7
-
else
-
if has_terminal?(":", false, index)
-
r8 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r8 = nil
-
end
-
if r8
-
r0 = r8
-
else
-
if has_terminal?('\\', false, index)
-
r9 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure('\\')
-
r9 = nil
-
end
-
if r9
-
r0 = r9
-
else
-
if has_terminal?("<", false, index)
-
r10 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("<")
-
r10 = nil
-
end
-
if r10
-
r0 = r10
-
else
-
if has_terminal?(">", false, index)
-
r11 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(">")
-
r11 = nil
-
end
-
if r11
-
r0 = r11
-
else
-
if has_terminal?("/", false, index)
-
r12 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("/")
-
r12 = nil
-
end
-
if r12
-
r0 = r12
-
else
-
if has_terminal?("[", false, index)
-
r13 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("[")
-
r13 = nil
-
end
-
if r13
-
r0 = r13
-
else
-
if has_terminal?("]", false, index)
-
r14 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("]")
-
r14 = nil
-
end
-
if r14
-
r0 = r14
-
else
-
if has_terminal?("?", false, index)
-
r15 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("?")
-
r15 = nil
-
end
-
if r15
-
r0 = r15
-
else
-
if has_terminal?("=", false, index)
-
r16 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("=")
-
r16 = nil
-
end
-
if r16
-
r0 = r16
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
-
node_cache[:tspecials][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_ietf_token
-
start_index = index
-
if node_cache[:ietf_token].has_key?(index)
-
cached = node_cache[:ietf_token][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
s0, i0 = [], index
-
loop do
-
r1 = _nt_token
-
if r1
-
s0 << r1
-
else
-
break
-
end
-
end
-
if s0.empty?
-
@index = i0
-
r0 = nil
-
else
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
end
-
-
node_cache[:ietf_token][start_index] = r0
-
-
r0
-
end
-
-
1
module CustomXToken0
-
end
-
-
1
def _nt_custom_x_token
-
start_index = index
-
if node_cache[:custom_x_token].has_key?(index)
-
cached = node_cache[:custom_x_token][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?('\G[xX]', true, index)
-
r1 = true
-
@index += 1
-
else
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
if has_terminal?("-", false, index)
-
r2 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("-")
-
r2 = nil
-
end
-
s0 << r2
-
if r2
-
s3, i3 = [], index
-
loop do
-
r4 = _nt_token
-
if r4
-
s3 << r4
-
else
-
break
-
end
-
end
-
if s3.empty?
-
@index = i3
-
r3 = nil
-
else
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
end
-
s0 << r3
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(CustomXToken0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:custom_x_token][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_iana_token
-
start_index = index
-
if node_cache[:iana_token].has_key?(index)
-
cached = node_cache[:iana_token][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
s0, i0 = [], index
-
loop do
-
r1 = _nt_token
-
if r1
-
s0 << r1
-
else
-
break
-
end
-
end
-
if s0.empty?
-
@index = i0
-
r0 = nil
-
else
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
end
-
-
node_cache[:iana_token][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_token
-
start_index = index
-
if node_cache[:token].has_key?(index)
-
cached = node_cache[:token][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
if has_terminal?('\G[\\x21-\\x27]', true, index)
-
r1 = true
-
@index += 1
-
else
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
if has_terminal?('\G[\\x2a-\\x2b]', true, index)
-
r2 = true
-
@index += 1
-
else
-
r2 = nil
-
end
-
if r2
-
r0 = r2
-
else
-
if has_terminal?('\G[\\x2c-\\x2e]', true, index)
-
r3 = true
-
@index += 1
-
else
-
r3 = nil
-
end
-
if r3
-
r0 = r3
-
else
-
if has_terminal?('\G[\\x30-\\x39]', true, index)
-
r4 = true
-
@index += 1
-
else
-
r4 = nil
-
end
-
if r4
-
r0 = r4
-
else
-
if has_terminal?('\G[\\x41-\\x5a]', true, index)
-
r5 = true
-
@index += 1
-
else
-
r5 = nil
-
end
-
if r5
-
r0 = r5
-
else
-
if has_terminal?('\G[\\x5e-\\x7e]', true, index)
-
r6 = true
-
@index += 1
-
else
-
r6 = nil
-
end
-
if r6
-
r0 = r6
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
end
-
end
-
-
node_cache[:token][start_index] = r0
-
-
r0
-
end
-
-
end
-
-
1
class RFC2045Parser < Treetop::Runtime::CompiledParser
-
1
include RFC2045
-
end
-
-
end
-
# Autogenerated from a Treetop grammar. Edits may be lost.
-
-
-
1
module Mail
-
1
module RFC2822
-
1
include Treetop::Runtime
-
-
1
def root
-
@root ||= :ALPHA
-
end
-
-
1
include RFC2822Obsolete
-
-
1
def _nt_ALPHA
-
start_index = index
-
if node_cache[:ALPHA].has_key?(index)
-
cached = node_cache[:ALPHA][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
if has_terminal?('\G[a-zA-Z]', true, index)
-
r0 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
r0 = nil
-
end
-
-
node_cache[:ALPHA][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_DIGIT
-
start_index = index
-
if node_cache[:DIGIT].has_key?(index)
-
cached = node_cache[:DIGIT][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
if has_terminal?('\G[0-9]', true, index)
-
r0 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
r0 = nil
-
end
-
-
node_cache[:DIGIT][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_DQUOTE
-
start_index = index
-
if node_cache[:DQUOTE].has_key?(index)
-
cached = node_cache[:DQUOTE][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
if has_terminal?('"', false, index)
-
r0 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure('"')
-
r0 = nil
-
end
-
-
node_cache[:DQUOTE][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_LF
-
start_index = index
-
if node_cache[:LF].has_key?(index)
-
cached = node_cache[:LF][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
if has_terminal?("\n", false, index)
-
r0 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("\n")
-
r0 = nil
-
end
-
-
node_cache[:LF][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_CR
-
start_index = index
-
if node_cache[:CR].has_key?(index)
-
cached = node_cache[:CR][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
if has_terminal?("\r", false, index)
-
r0 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("\r")
-
r0 = nil
-
end
-
-
node_cache[:CR][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_CRLF
-
start_index = index
-
if node_cache[:CRLF].has_key?(index)
-
cached = node_cache[:CRLF][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
if has_terminal?("\r\n", false, index)
-
r0 = instantiate_node(SyntaxNode,input, index...(index + 2))
-
@index += 2
-
else
-
terminal_parse_failure("\r\n")
-
r0 = nil
-
end
-
-
node_cache[:CRLF][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_WSP
-
start_index = index
-
if node_cache[:WSP].has_key?(index)
-
cached = node_cache[:WSP][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
if has_terminal?('\G[\\x09\\x20]', true, index)
-
r0 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
r0 = nil
-
end
-
-
node_cache[:WSP][start_index] = r0
-
-
r0
-
end
-
-
1
module FWS0
-
1
def CRLF
-
elements[1]
-
end
-
-
end
-
-
1
module FWS1
-
1
def CRLF
-
elements[0]
-
end
-
-
end
-
-
1
def _nt_FWS
-
start_index = index
-
if node_cache[:FWS].has_key?(index)
-
cached = node_cache[:FWS][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s1 << r2
-
if r2
-
r4 = _nt_CRLF
-
s1 << r4
-
if r4
-
s5, i5 = [], index
-
loop do
-
r6 = _nt_WSP
-
if r6
-
s5 << r6
-
else
-
break
-
end
-
end
-
if s5.empty?
-
@index = i5
-
r5 = nil
-
else
-
r5 = instantiate_node(SyntaxNode,input, i5...index, s5)
-
end
-
s1 << r5
-
end
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(FWS0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
i7, s7 = index, []
-
r8 = _nt_CRLF
-
s7 << r8
-
if r8
-
s9, i9 = [], index
-
loop do
-
r10 = _nt_WSP
-
if r10
-
s9 << r10
-
else
-
break
-
end
-
end
-
if s9.empty?
-
@index = i9
-
r9 = nil
-
else
-
r9 = instantiate_node(SyntaxNode,input, i9...index, s9)
-
end
-
s7 << r9
-
end
-
if s7.last
-
r7 = instantiate_node(SyntaxNode,input, i7...index, s7)
-
r7.extend(FWS1)
-
else
-
@index = i7
-
r7 = nil
-
end
-
if r7
-
r0 = r7
-
else
-
r11 = _nt_obs_FWS
-
if r11
-
r0 = r11
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
-
node_cache[:FWS][start_index] = r0
-
-
r0
-
end
-
-
1
module CFWS0
-
1
def comment
-
elements[1]
-
end
-
end
-
-
1
module CFWS1
-
end
-
-
1
def _nt_CFWS
-
start_index = index
-
if node_cache[:CFWS].has_key?(index)
-
cached = node_cache[:CFWS][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
s1, i1 = [], index
-
loop do
-
i2, s2 = index, []
-
s3, i3 = [], index
-
loop do
-
r4 = _nt_FWS
-
if r4
-
s3 << r4
-
else
-
break
-
end
-
end
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
s2 << r3
-
if r3
-
r5 = _nt_comment
-
s2 << r5
-
end
-
if s2.last
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
r2.extend(CFWS0)
-
else
-
@index = i2
-
r2 = nil
-
end
-
if r2
-
s1 << r2
-
else
-
break
-
end
-
end
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
s0 << r1
-
if r1
-
r7 = _nt_FWS
-
if r7
-
r6 = r7
-
else
-
r6 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r6
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(CFWS1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:CFWS][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_NO_WS_CTL
-
start_index = index
-
if node_cache[:NO_WS_CTL].has_key?(index)
-
cached = node_cache[:NO_WS_CTL][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
if has_terminal?('\G[\\x01-\\x08]', true, index)
-
r1 = true
-
@index += 1
-
else
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
if has_terminal?('\G[\\x0B-\\x0C]', true, index)
-
r2 = true
-
@index += 1
-
else
-
r2 = nil
-
end
-
if r2
-
r0 = r2
-
else
-
if has_terminal?('\G[\\x0E-\\x1F]', true, index)
-
r3 = true
-
@index += 1
-
else
-
r3 = nil
-
end
-
if r3
-
r0 = r3
-
else
-
if has_terminal?('\G[\\x7f]', true, index)
-
r4 = true
-
@index += 1
-
else
-
r4 = nil
-
end
-
if r4
-
r0 = r4
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
-
node_cache[:NO_WS_CTL][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_specials
-
start_index = index
-
if node_cache[:specials].has_key?(index)
-
cached = node_cache[:specials][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
if has_terminal?("(", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("(")
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
if has_terminal?(")", false, index)
-
r2 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(")")
-
r2 = nil
-
end
-
if r2
-
r0 = r2
-
else
-
if has_terminal?("<", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("<")
-
r3 = nil
-
end
-
if r3
-
r0 = r3
-
else
-
if has_terminal?(">", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(">")
-
r4 = nil
-
end
-
if r4
-
r0 = r4
-
else
-
if has_terminal?("[", false, index)
-
r5 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("[")
-
r5 = nil
-
end
-
if r5
-
r0 = r5
-
else
-
if has_terminal?("]", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("]")
-
r6 = nil
-
end
-
if r6
-
r0 = r6
-
else
-
if has_terminal?(":", false, index)
-
r7 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r7 = nil
-
end
-
if r7
-
r0 = r7
-
else
-
if has_terminal?(";", false, index)
-
r8 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(";")
-
r8 = nil
-
end
-
if r8
-
r0 = r8
-
else
-
if has_terminal?("@", false, index)
-
r9 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("@")
-
r9 = nil
-
end
-
if r9
-
r0 = r9
-
else
-
if has_terminal?('\\', false, index)
-
r10 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure('\\')
-
r10 = nil
-
end
-
if r10
-
r0 = r10
-
else
-
if has_terminal?(",", false, index)
-
r11 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(",")
-
r11 = nil
-
end
-
if r11
-
r0 = r11
-
else
-
if has_terminal?(".", false, index)
-
r12 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(".")
-
r12 = nil
-
end
-
if r12
-
r0 = r12
-
else
-
r13 = _nt_DQUOTE
-
if r13
-
r0 = r13
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
-
node_cache[:specials][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_ctext
-
start_index = index
-
if node_cache[:ctext].has_key?(index)
-
cached = node_cache[:ctext][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_NO_WS_CTL
-
if r1
-
r0 = r1
-
else
-
if has_terminal?('\G[\\x21-\\x27]', true, index)
-
r2 = true
-
@index += 1
-
else
-
r2 = nil
-
end
-
if r2
-
r0 = r2
-
else
-
if has_terminal?('\G[\\x2a-\\x5b]', true, index)
-
r3 = true
-
@index += 1
-
else
-
r3 = nil
-
end
-
if r3
-
r0 = r3
-
else
-
if has_terminal?('\G[\\x5d-\\x7e]', true, index)
-
r4 = true
-
@index += 1
-
else
-
r4 = nil
-
end
-
if r4
-
r0 = r4
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
-
node_cache[:ctext][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_ccontent
-
start_index = index
-
if node_cache[:ccontent].has_key?(index)
-
cached = node_cache[:ccontent][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_ctext
-
if r1
-
r0 = r1
-
else
-
r2 = _nt_quoted_pair
-
if r2
-
r0 = r2
-
else
-
r3 = _nt_comment
-
if r3
-
r0 = r3
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
-
node_cache[:ccontent][start_index] = r0
-
-
r0
-
end
-
-
1
module Comment0
-
1
def ccontent
-
elements[1]
-
end
-
end
-
-
1
module Comment1
-
end
-
-
1
def _nt_comment
-
start_index = index
-
if node_cache[:comment].has_key?(index)
-
cached = node_cache[:comment][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("(", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("(")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
i3, s3 = index, []
-
r5 = _nt_FWS
-
if r5
-
r4 = r5
-
else
-
r4 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s3 << r4
-
if r4
-
r6 = _nt_ccontent
-
s3 << r6
-
end
-
if s3.last
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
r3.extend(Comment0)
-
else
-
@index = i3
-
r3 = nil
-
end
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
r8 = _nt_FWS
-
if r8
-
r7 = r8
-
else
-
r7 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r7
-
if r7
-
if has_terminal?(")", false, index)
-
r9 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(")")
-
r9 = nil
-
end
-
s0 << r9
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(Comment1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:comment][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_atext
-
start_index = index
-
if node_cache[:atext].has_key?(index)
-
cached = node_cache[:atext][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_ALPHA
-
if r1
-
r0 = r1
-
else
-
r2 = _nt_DIGIT
-
if r2
-
r0 = r2
-
else
-
if has_terminal?("!", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("!")
-
r3 = nil
-
end
-
if r3
-
r0 = r3
-
else
-
if has_terminal?("#", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("#")
-
r4 = nil
-
end
-
if r4
-
r0 = r4
-
else
-
if has_terminal?("$", false, index)
-
r5 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("$")
-
r5 = nil
-
end
-
if r5
-
r0 = r5
-
else
-
if has_terminal?("%", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("%")
-
r6 = nil
-
end
-
if r6
-
r0 = r6
-
else
-
if has_terminal?("&", false, index)
-
r7 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("&")
-
r7 = nil
-
end
-
if r7
-
r0 = r7
-
else
-
if has_terminal?("'", false, index)
-
r8 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("'")
-
r8 = nil
-
end
-
if r8
-
r0 = r8
-
else
-
if has_terminal?("*", false, index)
-
r9 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("*")
-
r9 = nil
-
end
-
if r9
-
r0 = r9
-
else
-
if has_terminal?("+", false, index)
-
r10 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("+")
-
r10 = nil
-
end
-
if r10
-
r0 = r10
-
else
-
if has_terminal?("-", false, index)
-
r11 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("-")
-
r11 = nil
-
end
-
if r11
-
r0 = r11
-
else
-
if has_terminal?("/", false, index)
-
r12 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("/")
-
r12 = nil
-
end
-
if r12
-
r0 = r12
-
else
-
if has_terminal?("=", false, index)
-
r13 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("=")
-
r13 = nil
-
end
-
if r13
-
r0 = r13
-
else
-
if has_terminal?("?", false, index)
-
r14 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("?")
-
r14 = nil
-
end
-
if r14
-
r0 = r14
-
else
-
if has_terminal?("^", false, index)
-
r15 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("^")
-
r15 = nil
-
end
-
if r15
-
r0 = r15
-
else
-
if has_terminal?("_", false, index)
-
r16 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("_")
-
r16 = nil
-
end
-
if r16
-
r0 = r16
-
else
-
if has_terminal?("`", false, index)
-
r17 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("`")
-
r17 = nil
-
end
-
if r17
-
r0 = r17
-
else
-
if has_terminal?("{", false, index)
-
r18 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("{")
-
r18 = nil
-
end
-
if r18
-
r0 = r18
-
else
-
if has_terminal?("|", false, index)
-
r19 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("|")
-
r19 = nil
-
end
-
if r19
-
r0 = r19
-
else
-
if has_terminal?("}", false, index)
-
r20 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("}")
-
r20 = nil
-
end
-
if r20
-
r0 = r20
-
else
-
if has_terminal?("~", false, index)
-
r21 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("~")
-
r21 = nil
-
end
-
if r21
-
r0 = r21
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
-
node_cache[:atext][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_mtext
-
start_index = index
-
if node_cache[:mtext].has_key?(index)
-
cached = node_cache[:mtext][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
s0, i0 = [], index
-
loop do
-
i1 = index
-
r2 = _nt_atext
-
if r2
-
r1 = r2
-
else
-
if has_terminal?(".", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(".")
-
r3 = nil
-
end
-
if r3
-
r1 = r3
-
else
-
@index = i1
-
r1 = nil
-
end
-
end
-
if r1
-
s0 << r1
-
else
-
break
-
end
-
end
-
if s0.empty?
-
@index = i0
-
r0 = nil
-
else
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
end
-
-
node_cache[:mtext][start_index] = r0
-
-
r0
-
end
-
-
1
module Atom0
-
end
-
-
1
def _nt_atom
-
start_index = index
-
if node_cache[:atom].has_key?(index)
-
cached = node_cache[:atom][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r2 = _nt_CFWS
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
s3, i3 = [], index
-
loop do
-
r4 = _nt_atext
-
if r4
-
s3 << r4
-
else
-
break
-
end
-
end
-
if s3.empty?
-
@index = i3
-
r3 = nil
-
else
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
end
-
s0 << r3
-
if r3
-
r6 = _nt_CFWS
-
if r6
-
r5 = r6
-
else
-
r5 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r5
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(Atom0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:atom][start_index] = r0
-
-
r0
-
end
-
-
1
module DotAtom0
-
1
def dot_atom_text
-
elements[1]
-
end
-
-
end
-
-
1
def _nt_dot_atom
-
start_index = index
-
if node_cache[:dot_atom].has_key?(index)
-
cached = node_cache[:dot_atom][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r2 = _nt_CFWS
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
r3 = _nt_dot_atom_text
-
s0 << r3
-
if r3
-
r5 = _nt_CFWS
-
if r5
-
r4 = r5
-
else
-
r4 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r4
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(DotAtom0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:dot_atom][start_index] = r0
-
-
r0
-
end
-
-
1
module LocalDotAtom0
-
1
def local_dot_atom_text
-
elements[1]
-
end
-
-
end
-
-
1
def _nt_local_dot_atom
-
start_index = index
-
if node_cache[:local_dot_atom].has_key?(index)
-
cached = node_cache[:local_dot_atom][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r2 = _nt_CFWS
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
r3 = _nt_local_dot_atom_text
-
s0 << r3
-
if r3
-
r5 = _nt_CFWS
-
if r5
-
r4 = r5
-
else
-
r4 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r4
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(LocalDotAtom0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:local_dot_atom][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_message_id_text
-
start_index = index
-
if node_cache[:message_id_text].has_key?(index)
-
cached = node_cache[:message_id_text][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
s0, i0 = [], index
-
loop do
-
r1 = _nt_mtext
-
if r1
-
s0 << r1
-
else
-
break
-
end
-
end
-
if s0.empty?
-
@index = i0
-
r0 = nil
-
else
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
end
-
-
node_cache[:message_id_text][start_index] = r0
-
-
r0
-
end
-
-
1
module DotAtomText0
-
1
def domain_text
-
elements[0]
-
end
-
-
end
-
-
1
def _nt_dot_atom_text
-
start_index = index
-
if node_cache[:dot_atom_text].has_key?(index)
-
cached = node_cache[:dot_atom_text][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
s0, i0 = [], index
-
loop do
-
i1, s1 = index, []
-
r2 = _nt_domain_text
-
s1 << r2
-
if r2
-
if has_terminal?(".", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(".")
-
r4 = nil
-
end
-
if r4
-
r3 = r4
-
else
-
r3 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s1 << r3
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(DotAtomText0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
s0 << r1
-
else
-
break
-
end
-
end
-
if s0.empty?
-
@index = i0
-
r0 = nil
-
else
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
end
-
-
node_cache[:dot_atom_text][start_index] = r0
-
-
r0
-
end
-
-
1
module LocalDotAtomText0
-
1
def domain_text
-
elements[1]
-
end
-
-
end
-
-
1
def _nt_local_dot_atom_text
-
start_index = index
-
if node_cache[:local_dot_atom_text].has_key?(index)
-
cached = node_cache[:local_dot_atom_text][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
s0, i0 = [], index
-
loop do
-
i1, s1 = index, []
-
s2, i2 = [], index
-
loop do
-
if has_terminal?(".", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(".")
-
r3 = nil
-
end
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s1 << r2
-
if r2
-
r4 = _nt_domain_text
-
s1 << r4
-
if r4
-
s5, i5 = [], index
-
loop do
-
if has_terminal?(".", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(".")
-
r6 = nil
-
end
-
if r6
-
s5 << r6
-
else
-
break
-
end
-
end
-
r5 = instantiate_node(SyntaxNode,input, i5...index, s5)
-
s1 << r5
-
end
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(LocalDotAtomText0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
s0 << r1
-
else
-
break
-
end
-
end
-
if s0.empty?
-
@index = i0
-
r0 = nil
-
else
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
end
-
-
node_cache[:local_dot_atom_text][start_index] = r0
-
-
r0
-
end
-
-
1
module DomainText0
-
1
def quoted_domain
-
elements[1]
-
end
-
end
-
-
1
module DomainText1
-
1
def DQUOTE1
-
elements[0]
-
end
-
-
1
def DQUOTE2
-
elements[3]
-
end
-
end
-
-
1
def _nt_domain_text
-
start_index = index
-
if node_cache[:domain_text].has_key?(index)
-
cached = node_cache[:domain_text][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
r2 = _nt_DQUOTE
-
s1 << r2
-
if r2
-
s3, i3 = [], index
-
loop do
-
i4, s4 = index, []
-
r6 = _nt_FWS
-
if r6
-
r5 = r6
-
else
-
r5 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s4 << r5
-
if r5
-
r7 = _nt_quoted_domain
-
s4 << r7
-
end
-
if s4.last
-
r4 = instantiate_node(SyntaxNode,input, i4...index, s4)
-
r4.extend(DomainText0)
-
else
-
@index = i4
-
r4 = nil
-
end
-
if r4
-
s3 << r4
-
else
-
break
-
end
-
end
-
if s3.empty?
-
@index = i3
-
r3 = nil
-
else
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
end
-
s1 << r3
-
if r3
-
r9 = _nt_FWS
-
if r9
-
r8 = r9
-
else
-
r8 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s1 << r8
-
if r8
-
r10 = _nt_DQUOTE
-
s1 << r10
-
end
-
end
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(DomainText1)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
s11, i11 = [], index
-
loop do
-
r12 = _nt_atext
-
if r12
-
s11 << r12
-
else
-
break
-
end
-
end
-
if s11.empty?
-
@index = i11
-
r11 = nil
-
else
-
r11 = instantiate_node(SyntaxNode,input, i11...index, s11)
-
end
-
if r11
-
r0 = r11
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:domain_text][start_index] = r0
-
-
r0
-
end
-
-
1
module QuotedDomain0
-
1
def text
-
elements[1]
-
end
-
end
-
-
1
def _nt_quoted_domain
-
start_index = index
-
if node_cache[:quoted_domain].has_key?(index)
-
cached = node_cache[:quoted_domain][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_qdcontent
-
if r1
-
r0 = r1
-
else
-
i2, s2 = index, []
-
if has_terminal?("\\", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("\\")
-
r3 = nil
-
end
-
s2 << r3
-
if r3
-
r4 = _nt_text
-
s2 << r4
-
end
-
if s2.last
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
r2.extend(QuotedDomain0)
-
else
-
@index = i2
-
r2 = nil
-
end
-
if r2
-
r0 = r2
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:quoted_domain][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_qdcontent
-
start_index = index
-
if node_cache[:qdcontent].has_key?(index)
-
cached = node_cache[:qdcontent][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_NO_WS_CTL
-
if r1
-
r0 = r1
-
else
-
if has_terminal?('\G[\\x21]', true, index)
-
r2 = true
-
@index += 1
-
else
-
r2 = nil
-
end
-
if r2
-
r0 = r2
-
else
-
if has_terminal?('\G[\\x23-\\x45]', true, index)
-
r3 = true
-
@index += 1
-
else
-
r3 = nil
-
end
-
if r3
-
r0 = r3
-
else
-
if has_terminal?('\G[\\x47-\\x5b]', true, index)
-
r4 = true
-
@index += 1
-
else
-
r4 = nil
-
end
-
if r4
-
r0 = r4
-
else
-
if has_terminal?('\G[\\x5d-\\x7e]', true, index)
-
r5 = true
-
@index += 1
-
else
-
r5 = nil
-
end
-
if r5
-
r0 = r5
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
end
-
-
node_cache[:qdcontent][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_phrase
-
start_index = index
-
if node_cache[:phrase].has_key?(index)
-
cached = node_cache[:phrase][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_obs_phrase
-
if r1
-
r0 = r1
-
else
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_word
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
if s2.empty?
-
@index = i2
-
r2 = nil
-
else
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
end
-
if r2
-
r0 = r2
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:phrase][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_word
-
start_index = index
-
if node_cache[:word].has_key?(index)
-
cached = node_cache[:word][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_atom
-
if r1
-
r0 = r1
-
else
-
r2 = _nt_quoted_string
-
if r2
-
r0 = r2
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:word][start_index] = r0
-
-
r0
-
end
-
-
1
module PhraseList0
-
1
def phrase_value
-
elements[2]
-
end
-
end
-
-
1
module PhraseList1
-
1
def first_phrase
-
elements[0]
-
end
-
-
1
def other_phrases
-
elements[1]
-
end
-
end
-
-
1
def _nt_phrase_list
-
start_index = index
-
if node_cache[:phrase_list].has_key?(index)
-
cached = node_cache[:phrase_list][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_phrase
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
i3, s3 = index, []
-
if has_terminal?(",", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(",")
-
r4 = nil
-
end
-
s3 << r4
-
if r4
-
s5, i5 = [], index
-
loop do
-
r6 = _nt_FWS
-
if r6
-
s5 << r6
-
else
-
break
-
end
-
end
-
r5 = instantiate_node(SyntaxNode,input, i5...index, s5)
-
s3 << r5
-
if r5
-
r7 = _nt_phrase
-
s3 << r7
-
end
-
end
-
if s3.last
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
r3.extend(PhraseList0)
-
else
-
@index = i3
-
r3 = nil
-
end
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(PhraseList1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:phrase_list][start_index] = r0
-
-
r0
-
end
-
-
1
module DomainLiteral0
-
1
def dcontent
-
elements[1]
-
end
-
end
-
-
1
module DomainLiteral1
-
end
-
-
1
def _nt_domain_literal
-
start_index = index
-
if node_cache[:domain_literal].has_key?(index)
-
cached = node_cache[:domain_literal][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r2 = _nt_CFWS
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
if has_terminal?("[", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("[")
-
r3 = nil
-
end
-
s0 << r3
-
if r3
-
s4, i4 = [], index
-
loop do
-
i5, s5 = index, []
-
r7 = _nt_FWS
-
if r7
-
r6 = r7
-
else
-
r6 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s5 << r6
-
if r6
-
r8 = _nt_dcontent
-
s5 << r8
-
end
-
if s5.last
-
r5 = instantiate_node(SyntaxNode,input, i5...index, s5)
-
r5.extend(DomainLiteral0)
-
else
-
@index = i5
-
r5 = nil
-
end
-
if r5
-
s4 << r5
-
else
-
break
-
end
-
end
-
r4 = instantiate_node(SyntaxNode,input, i4...index, s4)
-
s0 << r4
-
if r4
-
r10 = _nt_FWS
-
if r10
-
r9 = r10
-
else
-
r9 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r9
-
if r9
-
if has_terminal?("]", false, index)
-
r11 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("]")
-
r11 = nil
-
end
-
s0 << r11
-
if r11
-
r13 = _nt_CFWS
-
if r13
-
r12 = r13
-
else
-
r12 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r12
-
end
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(DomainLiteral1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:domain_literal][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_dcontent
-
start_index = index
-
if node_cache[:dcontent].has_key?(index)
-
cached = node_cache[:dcontent][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_dtext
-
if r1
-
r0 = r1
-
else
-
r2 = _nt_quoted_pair
-
if r2
-
r0 = r2
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:dcontent][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_dtext
-
start_index = index
-
if node_cache[:dtext].has_key?(index)
-
cached = node_cache[:dtext][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_NO_WS_CTL
-
if r1
-
r0 = r1
-
else
-
if has_terminal?('\G[\\x21-\\x5a]', true, index)
-
r2 = true
-
@index += 1
-
else
-
r2 = nil
-
end
-
if r2
-
r0 = r2
-
else
-
if has_terminal?('\G[\\x5e-\\x7e]', true, index)
-
r3 = true
-
@index += 1
-
else
-
r3 = nil
-
end
-
if r3
-
r0 = r3
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
-
node_cache[:dtext][start_index] = r0
-
-
r0
-
end
-
-
1
module AngleAddr0
-
1
def addr_spec
-
elements[2]
-
end
-
-
end
-
-
1
def _nt_angle_addr
-
start_index = index
-
if node_cache[:angle_addr].has_key?(index)
-
cached = node_cache[:angle_addr][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
r3 = _nt_CFWS
-
if r3
-
r2 = r3
-
else
-
r2 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s1 << r2
-
if r2
-
if has_terminal?("<", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("<")
-
r4 = nil
-
end
-
s1 << r4
-
if r4
-
r5 = _nt_addr_spec
-
s1 << r5
-
if r5
-
if has_terminal?(">", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(">")
-
r6 = nil
-
end
-
s1 << r6
-
if r6
-
r8 = _nt_CFWS
-
if r8
-
r7 = r8
-
else
-
r7 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s1 << r7
-
end
-
end
-
end
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(AngleAddr0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
r9 = _nt_obs_angle_addr
-
if r9
-
r0 = r9
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:angle_addr][start_index] = r0
-
-
r0
-
end
-
-
1
module AddrSpec0
-
1
def local_part
-
elements[0]
-
end
-
-
1
def domain
-
elements[2]
-
end
-
end
-
-
1
def _nt_addr_spec
-
start_index = index
-
if node_cache[:addr_spec].has_key?(index)
-
cached = node_cache[:addr_spec][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
r2 = _nt_local_part
-
s1 << r2
-
if r2
-
if has_terminal?("@", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("@")
-
r3 = nil
-
end
-
s1 << r3
-
if r3
-
r4 = _nt_domain
-
s1 << r4
-
end
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(AddrSpec0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
r5 = _nt_local_part
-
if r5
-
r0 = r5
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:addr_spec][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_local_part
-
start_index = index
-
if node_cache[:local_part].has_key?(index)
-
cached = node_cache[:local_part][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_local_dot_atom
-
if r1
-
r0 = r1
-
else
-
r2 = _nt_quoted_string
-
if r2
-
r0 = r2
-
else
-
r3 = _nt_obs_local_part
-
if r3
-
r0 = r3
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
-
node_cache[:local_part][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_domain
-
start_index = index
-
if node_cache[:domain].has_key?(index)
-
cached = node_cache[:domain][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_dot_atom
-
if r1
-
r0 = r1
-
else
-
r2 = _nt_domain_literal
-
if r2
-
r0 = r2
-
else
-
r3 = _nt_obs_domain
-
if r3
-
r0 = r3
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
-
node_cache[:domain][start_index] = r0
-
-
r0
-
end
-
-
1
module Group0
-
1
def group_name
-
elements[0]
-
end
-
-
1
def group_list
-
elements[2]
-
end
-
-
end
-
-
1
def _nt_group
-
start_index = index
-
if node_cache[:group].has_key?(index)
-
cached = node_cache[:group][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_display_name
-
s0 << r1
-
if r1
-
if has_terminal?(":", false, index)
-
r2 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r2 = nil
-
end
-
s0 << r2
-
if r2
-
i4 = index
-
r5 = _nt_mailbox_list_group
-
if r5
-
r4 = r5
-
else
-
r6 = _nt_CFWS
-
if r6
-
r4 = r6
-
else
-
@index = i4
-
r4 = nil
-
end
-
end
-
if r4
-
r3 = r4
-
else
-
r3 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r3
-
if r3
-
if has_terminal?(";", false, index)
-
r7 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(";")
-
r7 = nil
-
end
-
s0 << r7
-
if r7
-
r9 = _nt_CFWS
-
if r9
-
r8 = r9
-
else
-
r8 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r8
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(Group0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:group][start_index] = r0
-
-
r0
-
end
-
-
1
module MailboxListGroup0
-
1
def addresses
-
[first_addr] + other_addr.elements.map { |o| o.addr_value }
-
end
-
end
-
-
1
def _nt_mailbox_list_group
-
start_index = index
-
if node_cache[:mailbox_list_group].has_key?(index)
-
cached = node_cache[:mailbox_list_group][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
r0 = _nt_mailbox_list
-
r0.extend(MailboxListGroup0)
-
-
node_cache[:mailbox_list_group][start_index] = r0
-
-
r0
-
end
-
-
1
module QuotedString0
-
1
def qcontent
-
elements[1]
-
end
-
end
-
-
1
module QuotedString1
-
1
def DQUOTE1
-
elements[1]
-
end
-
-
1
def quoted_content
-
elements[2]
-
end
-
-
1
def DQUOTE2
-
elements[4]
-
end
-
-
end
-
-
1
def _nt_quoted_string
-
start_index = index
-
if node_cache[:quoted_string].has_key?(index)
-
cached = node_cache[:quoted_string][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r2 = _nt_CFWS
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
r3 = _nt_DQUOTE
-
s0 << r3
-
if r3
-
s4, i4 = [], index
-
loop do
-
i5, s5 = index, []
-
r7 = _nt_FWS
-
if r7
-
r6 = r7
-
else
-
r6 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s5 << r6
-
if r6
-
r8 = _nt_qcontent
-
s5 << r8
-
end
-
if s5.last
-
r5 = instantiate_node(SyntaxNode,input, i5...index, s5)
-
r5.extend(QuotedString0)
-
else
-
@index = i5
-
r5 = nil
-
end
-
if r5
-
s4 << r5
-
else
-
break
-
end
-
end
-
r4 = instantiate_node(SyntaxNode,input, i4...index, s4)
-
s0 << r4
-
if r4
-
r10 = _nt_FWS
-
if r10
-
r9 = r10
-
else
-
r9 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r9
-
if r9
-
r11 = _nt_DQUOTE
-
s0 << r11
-
if r11
-
r13 = _nt_CFWS
-
if r13
-
r12 = r13
-
else
-
r12 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r12
-
end
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(QuotedString1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:quoted_string][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_qcontent
-
start_index = index
-
if node_cache[:qcontent].has_key?(index)
-
cached = node_cache[:qcontent][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_qtext
-
if r1
-
r0 = r1
-
else
-
r2 = _nt_quoted_pair
-
if r2
-
r0 = r2
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:qcontent][start_index] = r0
-
-
r0
-
end
-
-
1
module QuotedPair0
-
1
def text
-
elements[1]
-
end
-
end
-
-
1
def _nt_quoted_pair
-
start_index = index
-
if node_cache[:quoted_pair].has_key?(index)
-
cached = node_cache[:quoted_pair][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
if has_terminal?("\\", false, index)
-
r2 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("\\")
-
r2 = nil
-
end
-
s1 << r2
-
if r2
-
r3 = _nt_text
-
s1 << r3
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(QuotedPair0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
r4 = _nt_obs_qp
-
if r4
-
r0 = r4
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:quoted_pair][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_qtext
-
start_index = index
-
if node_cache[:qtext].has_key?(index)
-
cached = node_cache[:qtext][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_NO_WS_CTL
-
if r1
-
r0 = r1
-
else
-
if has_terminal?('\G[\\x21]', true, index)
-
r2 = true
-
@index += 1
-
else
-
r2 = nil
-
end
-
if r2
-
r0 = r2
-
else
-
if has_terminal?('\G[\\x23-\\x5b]', true, index)
-
r3 = true
-
@index += 1
-
else
-
r3 = nil
-
end
-
if r3
-
r0 = r3
-
else
-
if has_terminal?('\G[\\x5d-\\x7e]', true, index)
-
r4 = true
-
@index += 1
-
else
-
r4 = nil
-
end
-
if r4
-
r0 = r4
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
-
node_cache[:qtext][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_text
-
start_index = index
-
if node_cache[:text].has_key?(index)
-
cached = node_cache[:text][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
if has_terminal?('\G[\\x01-\\x09]', true, index)
-
r1 = true
-
@index += 1
-
else
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
if has_terminal?('\G[\\x0b-\\x0c]', true, index)
-
r2 = true
-
@index += 1
-
else
-
r2 = nil
-
end
-
if r2
-
r0 = r2
-
else
-
if has_terminal?('\G[\\x0e-\\x7e]', true, index)
-
r3 = true
-
@index += 1
-
else
-
r3 = nil
-
end
-
if r3
-
r0 = r3
-
else
-
r4 = _nt_obs_text
-
if r4
-
r0 = r4
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
-
node_cache[:text][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_display_name
-
start_index = index
-
if node_cache[:display_name].has_key?(index)
-
cached = node_cache[:display_name][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
r0 = _nt_phrase
-
-
node_cache[:display_name][start_index] = r0
-
-
r0
-
end
-
-
1
module NameAddr0
-
1
def display_name
-
elements[0]
-
end
-
-
1
def angle_addr
-
elements[1]
-
end
-
end
-
-
1
def _nt_name_addr
-
start_index = index
-
if node_cache[:name_addr].has_key?(index)
-
cached = node_cache[:name_addr][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
r2 = _nt_display_name
-
s1 << r2
-
if r2
-
r3 = _nt_angle_addr
-
s1 << r3
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(NameAddr0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
r4 = _nt_angle_addr
-
if r4
-
r0 = r4
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:name_addr][start_index] = r0
-
-
r0
-
end
-
-
1
module MailboxList0
-
1
def addr_value
-
elements[1]
-
end
-
end
-
-
1
module MailboxList1
-
1
def first_addr
-
elements[0]
-
end
-
-
1
def other_addr
-
elements[1]
-
end
-
end
-
-
1
def _nt_mailbox_list
-
start_index = index
-
if node_cache[:mailbox_list].has_key?(index)
-
cached = node_cache[:mailbox_list][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
r2 = _nt_mailbox
-
s1 << r2
-
if r2
-
s3, i3 = [], index
-
loop do
-
i4, s4 = index, []
-
i5 = index
-
if has_terminal?(",", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(",")
-
r6 = nil
-
end
-
if r6
-
r5 = r6
-
else
-
if has_terminal?(";", false, index)
-
r7 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(";")
-
r7 = nil
-
end
-
if r7
-
r5 = r7
-
else
-
@index = i5
-
r5 = nil
-
end
-
end
-
s4 << r5
-
if r5
-
r8 = _nt_mailbox
-
s4 << r8
-
end
-
if s4.last
-
r4 = instantiate_node(SyntaxNode,input, i4...index, s4)
-
r4.extend(MailboxList0)
-
else
-
@index = i4
-
r4 = nil
-
end
-
if r4
-
s3 << r4
-
else
-
break
-
end
-
end
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
s1 << r3
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(MailboxList1)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
r9 = _nt_obs_mbox_list
-
if r9
-
r0 = r9
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:mailbox_list][start_index] = r0
-
-
r0
-
end
-
-
1
module Mailbox0
-
1
def dig_comments(comments, elements)
-
elements.each { |elem|
-
if elem.respond_to?(:comment)
-
comments << elem.comment
-
end
-
dig_comments(comments, elem.elements) if elem.elements
-
}
-
end
-
-
1
def comments
-
comments = []
-
dig_comments(comments, elements)
-
comments
-
end
-
end
-
-
1
def _nt_mailbox
-
start_index = index
-
if node_cache[:mailbox].has_key?(index)
-
cached = node_cache[:mailbox][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_name_addr
-
if r1
-
r0 = r1
-
r0.extend(Mailbox0)
-
else
-
r2 = _nt_addr_spec
-
if r2
-
r0 = r2
-
r0.extend(Mailbox0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:mailbox][start_index] = r0
-
-
r0
-
end
-
-
1
module Address0
-
-
1
def dig_comments(comments, elements)
-
elements.each { |elem|
-
if elem.respond_to?(:comment)
-
comments << elem.comment
-
end
-
dig_comments(comments, elem.elements) if elem.elements
-
}
-
end
-
-
1
def comments
-
comments = []
-
dig_comments(comments, elements)
-
comments
-
end
-
end
-
-
1
def _nt_address
-
start_index = index
-
if node_cache[:address].has_key?(index)
-
cached = node_cache[:address][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_group
-
r1.extend(Address0)
-
if r1
-
r0 = r1
-
else
-
r2 = _nt_mailbox
-
if r2
-
r0 = r2
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:address][start_index] = r0
-
-
r0
-
end
-
-
1
module AddressList0
-
1
def addr_value
-
elements[3]
-
end
-
end
-
-
1
module AddressList1
-
1
def first_addr
-
elements[0]
-
end
-
-
1
def other_addr
-
elements[1]
-
end
-
end
-
-
1
def _nt_address_list
-
start_index = index
-
if node_cache[:address_list].has_key?(index)
-
cached = node_cache[:address_list][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r2 = _nt_address
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
s3, i3 = [], index
-
loop do
-
i4, s4 = index, []
-
s5, i5 = [], index
-
loop do
-
r6 = _nt_FWS
-
if r6
-
s5 << r6
-
else
-
break
-
end
-
end
-
r5 = instantiate_node(SyntaxNode,input, i5...index, s5)
-
s4 << r5
-
if r5
-
i7 = index
-
if has_terminal?(",", false, index)
-
r8 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(",")
-
r8 = nil
-
end
-
if r8
-
r7 = r8
-
else
-
if has_terminal?(";", false, index)
-
r9 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(";")
-
r9 = nil
-
end
-
if r9
-
r7 = r9
-
else
-
@index = i7
-
r7 = nil
-
end
-
end
-
s4 << r7
-
if r7
-
s10, i10 = [], index
-
loop do
-
r11 = _nt_FWS
-
if r11
-
s10 << r11
-
else
-
break
-
end
-
end
-
r10 = instantiate_node(SyntaxNode,input, i10...index, s10)
-
s4 << r10
-
if r10
-
r13 = _nt_address
-
if r13
-
r12 = r13
-
else
-
r12 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s4 << r12
-
end
-
end
-
end
-
if s4.last
-
r4 = instantiate_node(SyntaxNode,input, i4...index, s4)
-
r4.extend(AddressList0)
-
else
-
@index = i4
-
r4 = nil
-
end
-
if r4
-
s3 << r4
-
else
-
break
-
end
-
end
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
s0 << r3
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(AddressList1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:address_list][start_index] = r0
-
-
r0
-
end
-
-
1
module DateTime0
-
1
def day_of_week
-
elements[0]
-
end
-
-
end
-
-
1
module DateTime1
-
1
def date
-
elements[1]
-
end
-
-
1
def FWS
-
elements[2]
-
end
-
-
1
def time
-
elements[3]
-
end
-
-
end
-
-
1
def _nt_date_time
-
start_index = index
-
if node_cache[:date_time].has_key?(index)
-
cached = node_cache[:date_time][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
i2, s2 = index, []
-
r3 = _nt_day_of_week
-
s2 << r3
-
if r3
-
if has_terminal?(",", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(",")
-
r4 = nil
-
end
-
s2 << r4
-
end
-
if s2.last
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
r2.extend(DateTime0)
-
else
-
@index = i2
-
r2 = nil
-
end
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
r5 = _nt_date
-
s0 << r5
-
if r5
-
r6 = _nt_FWS
-
s0 << r6
-
if r6
-
r7 = _nt_time
-
s0 << r7
-
if r7
-
r9 = _nt_CFWS
-
if r9
-
r8 = r9
-
else
-
r8 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r8
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(DateTime1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:date_time][start_index] = r0
-
-
r0
-
end
-
-
1
module DayOfWeek0
-
1
def day_name
-
elements[1]
-
end
-
end
-
-
1
def _nt_day_of_week
-
start_index = index
-
if node_cache[:day_of_week].has_key?(index)
-
cached = node_cache[:day_of_week][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
r3 = _nt_FWS
-
if r3
-
r2 = r3
-
else
-
r2 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s1 << r2
-
if r2
-
r4 = _nt_day_name
-
s1 << r4
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(DayOfWeek0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
r5 = _nt_obs_day_of_week
-
if r5
-
r0 = r5
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:day_of_week][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_day_name
-
start_index = index
-
if node_cache[:day_name].has_key?(index)
-
cached = node_cache[:day_name][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
if has_terminal?("Mon", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Mon")
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
if has_terminal?("Tue", false, index)
-
r2 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Tue")
-
r2 = nil
-
end
-
if r2
-
r0 = r2
-
else
-
if has_terminal?("Wed", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Wed")
-
r3 = nil
-
end
-
if r3
-
r0 = r3
-
else
-
if has_terminal?("Thu", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Thu")
-
r4 = nil
-
end
-
if r4
-
r0 = r4
-
else
-
if has_terminal?("Fri", false, index)
-
r5 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Fri")
-
r5 = nil
-
end
-
if r5
-
r0 = r5
-
else
-
if has_terminal?("Sat", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Sat")
-
r6 = nil
-
end
-
if r6
-
r0 = r6
-
else
-
if has_terminal?("Sun", false, index)
-
r7 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Sun")
-
r7 = nil
-
end
-
if r7
-
r0 = r7
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
-
node_cache[:day_name][start_index] = r0
-
-
r0
-
end
-
-
1
module Date0
-
1
def day
-
elements[0]
-
end
-
-
1
def month
-
elements[1]
-
end
-
-
1
def year
-
elements[2]
-
end
-
end
-
-
1
def _nt_date
-
start_index = index
-
if node_cache[:date].has_key?(index)
-
cached = node_cache[:date][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_day
-
s0 << r1
-
if r1
-
r2 = _nt_month
-
s0 << r2
-
if r2
-
r3 = _nt_year
-
s0 << r3
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(Date0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:date][start_index] = r0
-
-
r0
-
end
-
-
1
module Year0
-
1
def DIGIT1
-
elements[0]
-
end
-
-
1
def DIGIT2
-
elements[1]
-
end
-
-
1
def DIGIT3
-
elements[2]
-
end
-
-
1
def DIGIT4
-
elements[3]
-
end
-
end
-
-
1
def _nt_year
-
start_index = index
-
if node_cache[:year].has_key?(index)
-
cached = node_cache[:year][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
r2 = _nt_DIGIT
-
s1 << r2
-
if r2
-
r3 = _nt_DIGIT
-
s1 << r3
-
if r3
-
r4 = _nt_DIGIT
-
s1 << r4
-
if r4
-
r5 = _nt_DIGIT
-
s1 << r5
-
end
-
end
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(Year0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
r6 = _nt_obs_year
-
if r6
-
r0 = r6
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:year][start_index] = r0
-
-
r0
-
end
-
-
1
module Month0
-
1
def FWS1
-
elements[0]
-
end
-
-
1
def month_name
-
elements[1]
-
end
-
-
1
def FWS2
-
elements[2]
-
end
-
end
-
-
1
def _nt_month
-
start_index = index
-
if node_cache[:month].has_key?(index)
-
cached = node_cache[:month][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
r2 = _nt_FWS
-
s1 << r2
-
if r2
-
r3 = _nt_month_name
-
s1 << r3
-
if r3
-
r4 = _nt_FWS
-
s1 << r4
-
end
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(Month0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
r5 = _nt_obs_month
-
if r5
-
r0 = r5
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:month][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_month_name
-
start_index = index
-
if node_cache[:month_name].has_key?(index)
-
cached = node_cache[:month_name][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
if has_terminal?("Jan", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Jan")
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
if has_terminal?("Feb", false, index)
-
r2 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Feb")
-
r2 = nil
-
end
-
if r2
-
r0 = r2
-
else
-
if has_terminal?("Mar", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Mar")
-
r3 = nil
-
end
-
if r3
-
r0 = r3
-
else
-
if has_terminal?("Apr", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Apr")
-
r4 = nil
-
end
-
if r4
-
r0 = r4
-
else
-
if has_terminal?("May", false, index)
-
r5 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("May")
-
r5 = nil
-
end
-
if r5
-
r0 = r5
-
else
-
if has_terminal?("Jun", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Jun")
-
r6 = nil
-
end
-
if r6
-
r0 = r6
-
else
-
if has_terminal?("Jul", false, index)
-
r7 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Jul")
-
r7 = nil
-
end
-
if r7
-
r0 = r7
-
else
-
if has_terminal?("Aug", false, index)
-
r8 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Aug")
-
r8 = nil
-
end
-
if r8
-
r0 = r8
-
else
-
if has_terminal?("Sep", false, index)
-
r9 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Sep")
-
r9 = nil
-
end
-
if r9
-
r0 = r9
-
else
-
if has_terminal?("Oct", false, index)
-
r10 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Oct")
-
r10 = nil
-
end
-
if r10
-
r0 = r10
-
else
-
if has_terminal?("Nov", false, index)
-
r11 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Nov")
-
r11 = nil
-
end
-
if r11
-
r0 = r11
-
else
-
if has_terminal?("Dec", false, index)
-
r12 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Dec")
-
r12 = nil
-
end
-
if r12
-
r0 = r12
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
-
node_cache[:month_name][start_index] = r0
-
-
r0
-
end
-
-
1
module Day0
-
1
def DIGIT
-
elements[1]
-
end
-
-
end
-
-
1
def _nt_day
-
start_index = index
-
if node_cache[:day].has_key?(index)
-
cached = node_cache[:day][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
r3 = _nt_FWS
-
if r3
-
r2 = r3
-
else
-
r2 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s1 << r2
-
if r2
-
r4 = _nt_DIGIT
-
s1 << r4
-
if r4
-
r6 = _nt_DIGIT
-
if r6
-
r5 = r6
-
else
-
r5 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s1 << r5
-
end
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(Day0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
r7 = _nt_obs_day
-
if r7
-
r0 = r7
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:day][start_index] = r0
-
-
r0
-
end
-
-
1
module Time0
-
1
def time_of_day
-
elements[0]
-
end
-
-
1
def FWS
-
elements[1]
-
end
-
-
1
def zone
-
elements[2]
-
end
-
end
-
-
1
def _nt_time
-
start_index = index
-
if node_cache[:time].has_key?(index)
-
cached = node_cache[:time][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_time_of_day
-
s0 << r1
-
if r1
-
r2 = _nt_FWS
-
s0 << r2
-
if r2
-
r3 = _nt_zone
-
s0 << r3
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(Time0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:time][start_index] = r0
-
-
r0
-
end
-
-
1
module TimeOfDay0
-
1
def second
-
elements[1]
-
end
-
end
-
-
1
module TimeOfDay1
-
1
def hour
-
elements[0]
-
end
-
-
1
def minute
-
elements[2]
-
end
-
-
end
-
-
1
def _nt_time_of_day
-
start_index = index
-
if node_cache[:time_of_day].has_key?(index)
-
cached = node_cache[:time_of_day][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_hour
-
s0 << r1
-
if r1
-
if has_terminal?(":", false, index)
-
r2 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r2 = nil
-
end
-
s0 << r2
-
if r2
-
r3 = _nt_minute
-
s0 << r3
-
if r3
-
i5, s5 = index, []
-
if has_terminal?(":", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r6 = nil
-
end
-
s5 << r6
-
if r6
-
r7 = _nt_second
-
s5 << r7
-
end
-
if s5.last
-
r5 = instantiate_node(SyntaxNode,input, i5...index, s5)
-
r5.extend(TimeOfDay0)
-
else
-
@index = i5
-
r5 = nil
-
end
-
if r5
-
r4 = r5
-
else
-
r4 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r4
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(TimeOfDay1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:time_of_day][start_index] = r0
-
-
r0
-
end
-
-
1
module Hour0
-
1
def DIGIT1
-
elements[0]
-
end
-
-
1
def DIGIT2
-
elements[1]
-
end
-
end
-
-
1
def _nt_hour
-
start_index = index
-
if node_cache[:hour].has_key?(index)
-
cached = node_cache[:hour][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
r2 = _nt_DIGIT
-
s1 << r2
-
if r2
-
r3 = _nt_DIGIT
-
s1 << r3
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(Hour0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
r4 = _nt_obs_hour
-
if r4
-
r0 = r4
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:hour][start_index] = r0
-
-
r0
-
end
-
-
1
module Minute0
-
1
def DIGIT1
-
elements[0]
-
end
-
-
1
def DIGIT2
-
elements[1]
-
end
-
end
-
-
1
def _nt_minute
-
start_index = index
-
if node_cache[:minute].has_key?(index)
-
cached = node_cache[:minute][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
r2 = _nt_DIGIT
-
s1 << r2
-
if r2
-
r3 = _nt_DIGIT
-
s1 << r3
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(Minute0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
r4 = _nt_obs_minute
-
if r4
-
r0 = r4
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:minute][start_index] = r0
-
-
r0
-
end
-
-
1
module Second0
-
1
def DIGIT1
-
elements[0]
-
end
-
-
1
def DIGIT2
-
elements[1]
-
end
-
end
-
-
1
def _nt_second
-
start_index = index
-
if node_cache[:second].has_key?(index)
-
cached = node_cache[:second][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
r2 = _nt_DIGIT
-
s1 << r2
-
if r2
-
r3 = _nt_DIGIT
-
s1 << r3
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(Second0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
r4 = _nt_obs_second
-
if r4
-
r0 = r4
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:second][start_index] = r0
-
-
r0
-
end
-
-
1
module Zone0
-
1
def DIGIT1
-
elements[1]
-
end
-
-
1
def DIGIT2
-
elements[2]
-
end
-
-
1
def DIGIT3
-
elements[3]
-
end
-
-
1
def DIGIT4
-
elements[4]
-
end
-
end
-
-
1
def _nt_zone
-
start_index = index
-
if node_cache[:zone].has_key?(index)
-
cached = node_cache[:zone][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
i2 = index
-
if has_terminal?("+", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("+")
-
r3 = nil
-
end
-
if r3
-
r2 = r3
-
else
-
if has_terminal?("-", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("-")
-
r4 = nil
-
end
-
if r4
-
r2 = r4
-
else
-
@index = i2
-
r2 = nil
-
end
-
end
-
s1 << r2
-
if r2
-
r5 = _nt_DIGIT
-
s1 << r5
-
if r5
-
r6 = _nt_DIGIT
-
s1 << r6
-
if r6
-
r7 = _nt_DIGIT
-
s1 << r7
-
if r7
-
r8 = _nt_DIGIT
-
s1 << r8
-
end
-
end
-
end
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(Zone0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
r9 = _nt_obs_zone
-
if r9
-
r0 = r9
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:zone][start_index] = r0
-
-
r0
-
end
-
-
1
module Return0
-
1
def path
-
elements[0]
-
end
-
-
1
def CRLF
-
elements[1]
-
end
-
end
-
-
1
def _nt_return
-
start_index = index
-
if node_cache[:return].has_key?(index)
-
cached = node_cache[:return][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_path
-
s0 << r1
-
if r1
-
r2 = _nt_CRLF
-
s0 << r2
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(Return0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:return][start_index] = r0
-
-
r0
-
end
-
-
1
module Path0
-
end
-
-
1
def _nt_path
-
start_index = index
-
if node_cache[:path].has_key?(index)
-
cached = node_cache[:path][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
r3 = _nt_CFWS
-
if r3
-
r2 = r3
-
else
-
r2 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s1 << r2
-
if r2
-
if has_terminal?("<", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("<")
-
r4 = nil
-
end
-
s1 << r4
-
if r4
-
i5 = index
-
r7 = _nt_CFWS
-
if r7
-
r6 = r7
-
else
-
r6 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
if r6
-
r5 = r6
-
else
-
r8 = _nt_addr_spec
-
if r8
-
r5 = r8
-
else
-
@index = i5
-
r5 = nil
-
end
-
end
-
s1 << r5
-
if r5
-
if has_terminal?(">", false, index)
-
r9 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(">")
-
r9 = nil
-
end
-
s1 << r9
-
if r9
-
r11 = _nt_CFWS
-
if r11
-
r10 = r11
-
else
-
r10 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s1 << r10
-
end
-
end
-
end
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(Path0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
r12 = _nt_obs_path
-
if r12
-
r0 = r12
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:path][start_index] = r0
-
-
r0
-
end
-
-
1
module Received0
-
1
def name_val_list
-
elements[0]
-
end
-
-
1
def date_time
-
elements[2]
-
end
-
-
1
def CRLF
-
elements[3]
-
end
-
end
-
-
1
def _nt_received
-
start_index = index
-
if node_cache[:received].has_key?(index)
-
cached = node_cache[:received][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_name_val_list
-
s0 << r1
-
if r1
-
if has_terminal?(";", false, index)
-
r2 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(";")
-
r2 = nil
-
end
-
s0 << r2
-
if r2
-
r3 = _nt_date_time
-
s0 << r3
-
if r3
-
r4 = _nt_CRLF
-
s0 << r4
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(Received0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:received][start_index] = r0
-
-
r0
-
end
-
-
1
module NameValList0
-
1
def CFWS
-
elements[0]
-
end
-
-
1
def name_val_pair
-
elements[1]
-
end
-
end
-
-
1
module NameValList1
-
1
def name_val_pair
-
elements[0]
-
end
-
-
end
-
-
1
module NameValList2
-
end
-
-
1
def _nt_name_val_list
-
start_index = index
-
if node_cache[:name_val_list].has_key?(index)
-
cached = node_cache[:name_val_list][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r2 = _nt_CFWS
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
i4, s4 = index, []
-
r5 = _nt_name_val_pair
-
s4 << r5
-
if r5
-
s6, i6 = [], index
-
loop do
-
i7, s7 = index, []
-
r8 = _nt_CFWS
-
s7 << r8
-
if r8
-
r9 = _nt_name_val_pair
-
s7 << r9
-
end
-
if s7.last
-
r7 = instantiate_node(SyntaxNode,input, i7...index, s7)
-
r7.extend(NameValList0)
-
else
-
@index = i7
-
r7 = nil
-
end
-
if r7
-
s6 << r7
-
else
-
break
-
end
-
end
-
r6 = instantiate_node(SyntaxNode,input, i6...index, s6)
-
s4 << r6
-
end
-
if s4.last
-
r4 = instantiate_node(SyntaxNode,input, i4...index, s4)
-
r4.extend(NameValList1)
-
else
-
@index = i4
-
r4 = nil
-
end
-
if r4
-
r3 = r4
-
else
-
r3 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r3
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(NameValList2)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:name_val_list][start_index] = r0
-
-
r0
-
end
-
-
1
module NameValPair0
-
1
def item_name
-
elements[0]
-
end
-
-
1
def CFWS
-
elements[1]
-
end
-
-
1
def item_value
-
elements[2]
-
end
-
end
-
-
1
def _nt_name_val_pair
-
start_index = index
-
if node_cache[:name_val_pair].has_key?(index)
-
cached = node_cache[:name_val_pair][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_item_name
-
s0 << r1
-
if r1
-
r2 = _nt_CFWS
-
s0 << r2
-
if r2
-
r3 = _nt_item_value
-
s0 << r3
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(NameValPair0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:name_val_pair][start_index] = r0
-
-
r0
-
end
-
-
1
module ItemName0
-
end
-
-
1
module ItemName1
-
1
def ALPHA
-
elements[0]
-
end
-
-
end
-
-
1
def _nt_item_name
-
start_index = index
-
if node_cache[:item_name].has_key?(index)
-
cached = node_cache[:item_name][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_ALPHA
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
i3, s3 = index, []
-
if has_terminal?("-", false, index)
-
r5 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("-")
-
r5 = nil
-
end
-
if r5
-
r4 = r5
-
else
-
r4 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s3 << r4
-
if r4
-
i6 = index
-
r7 = _nt_ALPHA
-
if r7
-
r6 = r7
-
else
-
r8 = _nt_DIGIT
-
if r8
-
r6 = r8
-
else
-
@index = i6
-
r6 = nil
-
end
-
end
-
s3 << r6
-
end
-
if s3.last
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
r3.extend(ItemName0)
-
else
-
@index = i3
-
r3 = nil
-
end
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ItemName1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:item_name][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_item_value
-
start_index = index
-
if node_cache[:item_value].has_key?(index)
-
cached = node_cache[:item_value][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
s1, i1 = [], index
-
loop do
-
r2 = _nt_angle_addr
-
if r2
-
s1 << r2
-
else
-
break
-
end
-
end
-
if s1.empty?
-
@index = i1
-
r1 = nil
-
else
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
end
-
if r1
-
r0 = r1
-
else
-
r3 = _nt_addr_spec
-
if r3
-
r0 = r3
-
else
-
r4 = _nt_atom
-
if r4
-
r0 = r4
-
else
-
r5 = _nt_domain
-
if r5
-
r0 = r5
-
else
-
r6 = _nt_msg_id
-
if r6
-
r0 = r6
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
end
-
-
node_cache[:item_value][start_index] = r0
-
-
r0
-
end
-
-
1
module MessageIds0
-
1
def CFWS
-
elements[0]
-
end
-
-
1
def msg_id_value
-
elements[1]
-
end
-
end
-
-
1
module MessageIds1
-
1
def first_msg_id
-
elements[0]
-
end
-
-
1
def other_msg_ids
-
elements[1]
-
end
-
end
-
-
1
def _nt_message_ids
-
start_index = index
-
if node_cache[:message_ids].has_key?(index)
-
cached = node_cache[:message_ids][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_msg_id
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
i3, s3 = index, []
-
r4 = _nt_CFWS
-
s3 << r4
-
if r4
-
r5 = _nt_msg_id
-
s3 << r5
-
end
-
if s3.last
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
r3.extend(MessageIds0)
-
else
-
@index = i3
-
r3 = nil
-
end
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(MessageIds1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:message_ids][start_index] = r0
-
-
r0
-
end
-
-
1
module MsgId0
-
1
def msg_id_value
-
elements[2]
-
end
-
-
end
-
-
1
def _nt_msg_id
-
start_index = index
-
if node_cache[:msg_id].has_key?(index)
-
cached = node_cache[:msg_id][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r2 = _nt_CFWS
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
if has_terminal?("<", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("<")
-
r3 = nil
-
end
-
s0 << r3
-
if r3
-
r4 = _nt_msg_id_value
-
s0 << r4
-
if r4
-
if has_terminal?(">", false, index)
-
r5 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(">")
-
r5 = nil
-
end
-
s0 << r5
-
if r5
-
r7 = _nt_CFWS
-
if r7
-
r6 = r7
-
else
-
r6 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(MsgId0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:msg_id][start_index] = r0
-
-
r0
-
end
-
-
1
module MsgIdValue0
-
1
def id_left
-
elements[0]
-
end
-
-
1
def id_right
-
elements[2]
-
end
-
end
-
-
1
def _nt_msg_id_value
-
start_index = index
-
if node_cache[:msg_id_value].has_key?(index)
-
cached = node_cache[:msg_id_value][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_id_left
-
s0 << r1
-
if r1
-
if has_terminal?("@", false, index)
-
r2 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("@")
-
r2 = nil
-
end
-
s0 << r2
-
if r2
-
r3 = _nt_id_right
-
s0 << r3
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(MsgIdValue0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:msg_id_value][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_id_left
-
start_index = index
-
if node_cache[:id_left].has_key?(index)
-
cached = node_cache[:id_left][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_message_id_text
-
if r1
-
r0 = r1
-
else
-
r2 = _nt_no_fold_quote
-
if r2
-
r0 = r2
-
else
-
r3 = _nt_obs_id_left
-
if r3
-
r0 = r3
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
-
node_cache[:id_left][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_id_right
-
start_index = index
-
if node_cache[:id_right].has_key?(index)
-
cached = node_cache[:id_right][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_msg_id_dot_atom_text
-
if r1
-
r0 = r1
-
else
-
r2 = _nt_no_fold_literal
-
if r2
-
r0 = r2
-
else
-
r3 = _nt_obs_id_right
-
if r3
-
r0 = r3
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
-
node_cache[:id_right][start_index] = r0
-
-
r0
-
end
-
-
1
module MsgIdDotAtomText0
-
1
def msg_id_domain_text
-
elements[0]
-
end
-
-
end
-
-
1
def _nt_msg_id_dot_atom_text
-
start_index = index
-
if node_cache[:msg_id_dot_atom_text].has_key?(index)
-
cached = node_cache[:msg_id_dot_atom_text][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
s0, i0 = [], index
-
loop do
-
i1, s1 = index, []
-
r2 = _nt_msg_id_domain_text
-
s1 << r2
-
if r2
-
if has_terminal?(".", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(".")
-
r4 = nil
-
end
-
if r4
-
r3 = r4
-
else
-
r3 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s1 << r3
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(MsgIdDotAtomText0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
s0 << r1
-
else
-
break
-
end
-
end
-
if s0.empty?
-
@index = i0
-
r0 = nil
-
else
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
end
-
-
node_cache[:msg_id_dot_atom_text][start_index] = r0
-
-
r0
-
end
-
-
1
module MsgIdDomainText0
-
1
def quoted_domain
-
elements[1]
-
end
-
end
-
-
1
module MsgIdDomainText1
-
1
def DQUOTE1
-
elements[0]
-
end
-
-
1
def DQUOTE2
-
elements[3]
-
end
-
end
-
-
1
def _nt_msg_id_domain_text
-
start_index = index
-
if node_cache[:msg_id_domain_text].has_key?(index)
-
cached = node_cache[:msg_id_domain_text][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
r2 = _nt_DQUOTE
-
s1 << r2
-
if r2
-
s3, i3 = [], index
-
loop do
-
i4, s4 = index, []
-
r6 = _nt_FWS
-
if r6
-
r5 = r6
-
else
-
r5 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s4 << r5
-
if r5
-
r7 = _nt_quoted_domain
-
s4 << r7
-
end
-
if s4.last
-
r4 = instantiate_node(SyntaxNode,input, i4...index, s4)
-
r4.extend(MsgIdDomainText0)
-
else
-
@index = i4
-
r4 = nil
-
end
-
if r4
-
s3 << r4
-
else
-
break
-
end
-
end
-
if s3.empty?
-
@index = i3
-
r3 = nil
-
else
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
end
-
s1 << r3
-
if r3
-
r9 = _nt_FWS
-
if r9
-
r8 = r9
-
else
-
r8 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s1 << r8
-
if r8
-
r10 = _nt_DQUOTE
-
s1 << r10
-
end
-
end
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(MsgIdDomainText1)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
s11, i11 = [], index
-
loop do
-
r12 = _nt_msg_id_atext
-
if r12
-
s11 << r12
-
else
-
break
-
end
-
end
-
if s11.empty?
-
@index = i11
-
r11 = nil
-
else
-
r11 = instantiate_node(SyntaxNode,input, i11...index, s11)
-
end
-
if r11
-
r0 = r11
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:msg_id_domain_text][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_msg_id_atext
-
start_index = index
-
if node_cache[:msg_id_atext].has_key?(index)
-
cached = node_cache[:msg_id_atext][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_ALPHA
-
if r1
-
r0 = r1
-
else
-
r2 = _nt_DIGIT
-
if r2
-
r0 = r2
-
else
-
if has_terminal?("!", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("!")
-
r3 = nil
-
end
-
if r3
-
r0 = r3
-
else
-
if has_terminal?("#", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("#")
-
r4 = nil
-
end
-
if r4
-
r0 = r4
-
else
-
if has_terminal?("$", false, index)
-
r5 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("$")
-
r5 = nil
-
end
-
if r5
-
r0 = r5
-
else
-
if has_terminal?("%", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("%")
-
r6 = nil
-
end
-
if r6
-
r0 = r6
-
else
-
if has_terminal?("&", false, index)
-
r7 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("&")
-
r7 = nil
-
end
-
if r7
-
r0 = r7
-
else
-
if has_terminal?("'", false, index)
-
r8 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("'")
-
r8 = nil
-
end
-
if r8
-
r0 = r8
-
else
-
if has_terminal?("*", false, index)
-
r9 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("*")
-
r9 = nil
-
end
-
if r9
-
r0 = r9
-
else
-
if has_terminal?("+", false, index)
-
r10 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("+")
-
r10 = nil
-
end
-
if r10
-
r0 = r10
-
else
-
if has_terminal?("-", false, index)
-
r11 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("-")
-
r11 = nil
-
end
-
if r11
-
r0 = r11
-
else
-
if has_terminal?("/", false, index)
-
r12 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("/")
-
r12 = nil
-
end
-
if r12
-
r0 = r12
-
else
-
if has_terminal?("=", false, index)
-
r13 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("=")
-
r13 = nil
-
end
-
if r13
-
r0 = r13
-
else
-
if has_terminal?("?", false, index)
-
r14 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("?")
-
r14 = nil
-
end
-
if r14
-
r0 = r14
-
else
-
if has_terminal?("^", false, index)
-
r15 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("^")
-
r15 = nil
-
end
-
if r15
-
r0 = r15
-
else
-
if has_terminal?("_", false, index)
-
r16 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("_")
-
r16 = nil
-
end
-
if r16
-
r0 = r16
-
else
-
if has_terminal?("`", false, index)
-
r17 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("`")
-
r17 = nil
-
end
-
if r17
-
r0 = r17
-
else
-
if has_terminal?("{", false, index)
-
r18 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("{")
-
r18 = nil
-
end
-
if r18
-
r0 = r18
-
else
-
if has_terminal?("|", false, index)
-
r19 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("|")
-
r19 = nil
-
end
-
if r19
-
r0 = r19
-
else
-
if has_terminal?("}", false, index)
-
r20 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("}")
-
r20 = nil
-
end
-
if r20
-
r0 = r20
-
else
-
if has_terminal?("~", false, index)
-
r21 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("~")
-
r21 = nil
-
end
-
if r21
-
r0 = r21
-
else
-
if has_terminal?("@", false, index)
-
r22 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("@")
-
r22 = nil
-
end
-
if r22
-
r0 = r22
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
-
node_cache[:msg_id_atext][start_index] = r0
-
-
r0
-
end
-
-
1
module NoFoldQuote0
-
1
def DQUOTE1
-
elements[0]
-
end
-
-
1
def DQUOTE2
-
elements[2]
-
end
-
end
-
-
1
def _nt_no_fold_quote
-
start_index = index
-
if node_cache[:no_fold_quote].has_key?(index)
-
cached = node_cache[:no_fold_quote][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_DQUOTE
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
i3 = index
-
r4 = _nt_qtext
-
if r4
-
r3 = r4
-
else
-
r5 = _nt_quoted_pair
-
if r5
-
r3 = r5
-
else
-
@index = i3
-
r3 = nil
-
end
-
end
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
if s2.empty?
-
@index = i2
-
r2 = nil
-
else
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
end
-
s0 << r2
-
if r2
-
r6 = _nt_DQUOTE
-
s0 << r6
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(NoFoldQuote0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:no_fold_quote][start_index] = r0
-
-
r0
-
end
-
-
1
module NoFoldLiteral0
-
end
-
-
1
def _nt_no_fold_literal
-
start_index = index
-
if node_cache[:no_fold_literal].has_key?(index)
-
cached = node_cache[:no_fold_literal][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("[", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("[")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
i3 = index
-
r4 = _nt_dtext
-
if r4
-
r3 = r4
-
else
-
r5 = _nt_quoted_pair
-
if r5
-
r3 = r5
-
else
-
@index = i3
-
r3 = nil
-
end
-
end
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
if s2.empty?
-
@index = i2
-
r2 = nil
-
else
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
end
-
s0 << r2
-
if r2
-
if has_terminal?("]", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("]")
-
r6 = nil
-
end
-
s0 << r6
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(NoFoldLiteral0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:no_fold_literal][start_index] = r0
-
-
r0
-
end
-
-
end
-
-
1
class RFC2822Parser < Treetop::Runtime::CompiledParser
-
1
include RFC2822
-
end
-
-
end
-
# Autogenerated from a Treetop grammar. Edits may be lost.
-
-
-
1
module Mail
-
1
module RFC2822Obsolete
-
1
include Treetop::Runtime
-
-
1
def root
-
@root ||= :obs_qp
-
end
-
-
1
module ObsQp0
-
end
-
-
1
def _nt_obs_qp
-
start_index = index
-
if node_cache[:obs_qp].has_key?(index)
-
cached = node_cache[:obs_qp][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("\\", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("\\")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
if has_terminal?('\G[\\x00-\\x7F]', true, index)
-
r2 = true
-
@index += 1
-
else
-
r2 = nil
-
end
-
s0 << r2
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsQp0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_qp][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsText0
-
1
def obs_char
-
elements[0]
-
end
-
-
end
-
-
1
module ObsText1
-
end
-
-
1
def _nt_obs_text
-
start_index = index
-
if node_cache[:obs_text].has_key?(index)
-
cached = node_cache[:obs_text][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
s1, i1 = [], index
-
loop do
-
r2 = _nt_LF
-
if r2
-
s1 << r2
-
else
-
break
-
end
-
end
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
s0 << r1
-
if r1
-
s3, i3 = [], index
-
loop do
-
r4 = _nt_CR
-
if r4
-
s3 << r4
-
else
-
break
-
end
-
end
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
s0 << r3
-
if r3
-
s5, i5 = [], index
-
loop do
-
i6, s6 = index, []
-
r7 = _nt_obs_char
-
s6 << r7
-
if r7
-
s8, i8 = [], index
-
loop do
-
r9 = _nt_LF
-
if r9
-
s8 << r9
-
else
-
break
-
end
-
end
-
r8 = instantiate_node(SyntaxNode,input, i8...index, s8)
-
s6 << r8
-
if r8
-
s10, i10 = [], index
-
loop do
-
r11 = _nt_CR
-
if r11
-
s10 << r11
-
else
-
break
-
end
-
end
-
r10 = instantiate_node(SyntaxNode,input, i10...index, s10)
-
s6 << r10
-
end
-
end
-
if s6.last
-
r6 = instantiate_node(SyntaxNode,input, i6...index, s6)
-
r6.extend(ObsText0)
-
else
-
@index = i6
-
r6 = nil
-
end
-
if r6
-
s5 << r6
-
else
-
break
-
end
-
end
-
r5 = instantiate_node(SyntaxNode,input, i5...index, s5)
-
s0 << r5
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsText1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_text][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_obs_char
-
start_index = index
-
if node_cache[:obs_char].has_key?(index)
-
cached = node_cache[:obs_char][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
if has_terminal?('\G[\\x00-\\x09]', true, index)
-
r1 = true
-
@index += 1
-
else
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
if has_terminal?('\G[\\x0B-\\x0C]', true, index)
-
r2 = true
-
@index += 1
-
else
-
r2 = nil
-
end
-
if r2
-
r0 = r2
-
else
-
if has_terminal?('\G[\\x0E-\\x7F]', true, index)
-
r3 = true
-
@index += 1
-
else
-
r3 = nil
-
end
-
if r3
-
r0 = r3
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
-
node_cache[:obs_char][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_obs_utext
-
start_index = index
-
if node_cache[:obs_utext].has_key?(index)
-
cached = node_cache[:obs_utext][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
r0 = _nt_obs_text
-
-
node_cache[:obs_utext][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_obs_phrase
-
start_index = index
-
if node_cache[:obs_phrase].has_key?(index)
-
cached = node_cache[:obs_phrase][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
s0, i0 = [], index
-
loop do
-
i1 = index
-
r2 = _nt_word
-
if r2
-
r1 = r2
-
else
-
if has_terminal?(".", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(".")
-
r3 = nil
-
end
-
if r3
-
r1 = r3
-
else
-
if has_terminal?("@", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("@")
-
r4 = nil
-
end
-
if r4
-
r1 = r4
-
else
-
@index = i1
-
r1 = nil
-
end
-
end
-
end
-
if r1
-
s0 << r1
-
else
-
break
-
end
-
end
-
if s0.empty?
-
@index = i0
-
r0 = nil
-
else
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
end
-
-
node_cache[:obs_phrase][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsPhraseList0
-
end
-
-
1
module ObsPhraseList1
-
end
-
-
1
def _nt_obs_phrase_list
-
start_index = index
-
if node_cache[:obs_phrase_list].has_key?(index)
-
cached = node_cache[:obs_phrase_list][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_phrase
-
if r1
-
r0 = r1
-
else
-
i2, s2 = index, []
-
s3, i3 = [], index
-
loop do
-
i4, s4 = index, []
-
r6 = _nt_phrase
-
if r6
-
r5 = r6
-
else
-
r5 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s4 << r5
-
if r5
-
r8 = _nt_CFWS
-
if r8
-
r7 = r8
-
else
-
r7 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s4 << r7
-
if r7
-
if has_terminal?(",", false, index)
-
r9 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(",")
-
r9 = nil
-
end
-
s4 << r9
-
if r9
-
r11 = _nt_CFWS
-
if r11
-
r10 = r11
-
else
-
r10 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s4 << r10
-
end
-
end
-
end
-
if s4.last
-
r4 = instantiate_node(SyntaxNode,input, i4...index, s4)
-
r4.extend(ObsPhraseList0)
-
else
-
@index = i4
-
r4 = nil
-
end
-
if r4
-
s3 << r4
-
else
-
break
-
end
-
end
-
if s3.empty?
-
@index = i3
-
r3 = nil
-
else
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
end
-
s2 << r3
-
if r3
-
r13 = _nt_phrase
-
if r13
-
r12 = r13
-
else
-
r12 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s2 << r12
-
end
-
if s2.last
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
r2.extend(ObsPhraseList1)
-
else
-
@index = i2
-
r2 = nil
-
end
-
if r2
-
r0 = r2
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:obs_phrase_list][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsFWS0
-
1
def CRLF
-
elements[0]
-
end
-
-
end
-
-
1
module ObsFWS1
-
end
-
-
1
def _nt_obs_FWS
-
start_index = index
-
if node_cache[:obs_FWS].has_key?(index)
-
cached = node_cache[:obs_FWS][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
s1, i1 = [], index
-
loop do
-
r2 = _nt_WSP
-
if r2
-
s1 << r2
-
else
-
break
-
end
-
end
-
if s1.empty?
-
@index = i1
-
r1 = nil
-
else
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
end
-
s0 << r1
-
if r1
-
s3, i3 = [], index
-
loop do
-
i4, s4 = index, []
-
r5 = _nt_CRLF
-
s4 << r5
-
if r5
-
s6, i6 = [], index
-
loop do
-
r7 = _nt_WSP
-
if r7
-
s6 << r7
-
else
-
break
-
end
-
end
-
if s6.empty?
-
@index = i6
-
r6 = nil
-
else
-
r6 = instantiate_node(SyntaxNode,input, i6...index, s6)
-
end
-
s4 << r6
-
end
-
if s4.last
-
r4 = instantiate_node(SyntaxNode,input, i4...index, s4)
-
r4.extend(ObsFWS0)
-
else
-
@index = i4
-
r4 = nil
-
end
-
if r4
-
s3 << r4
-
else
-
break
-
end
-
end
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
s0 << r3
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsFWS1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_FWS][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsDayOfWeek0
-
1
def day_name
-
elements[1]
-
end
-
-
end
-
-
1
def _nt_obs_day_of_week
-
start_index = index
-
if node_cache[:obs_day_of_week].has_key?(index)
-
cached = node_cache[:obs_day_of_week][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r2 = _nt_CFWS
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
r3 = _nt_day_name
-
s0 << r3
-
if r3
-
r5 = _nt_CFWS
-
if r5
-
r4 = r5
-
else
-
r4 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r4
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsDayOfWeek0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_day_of_week][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsYear0
-
1
def DIGIT1
-
elements[0]
-
end
-
-
1
def DIGIT2
-
elements[1]
-
end
-
end
-
-
1
module ObsYear1
-
end
-
-
1
def _nt_obs_year
-
start_index = index
-
if node_cache[:obs_year].has_key?(index)
-
cached = node_cache[:obs_year][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r2 = _nt_CFWS
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
i3, s3 = index, []
-
r4 = _nt_DIGIT
-
s3 << r4
-
if r4
-
r5 = _nt_DIGIT
-
s3 << r5
-
end
-
if s3.last
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
r3.extend(ObsYear0)
-
else
-
@index = i3
-
r3 = nil
-
end
-
s0 << r3
-
if r3
-
r7 = _nt_CFWS
-
if r7
-
r6 = r7
-
else
-
r6 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r6
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsYear1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_year][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsMonth0
-
1
def CFWS1
-
elements[0]
-
end
-
-
1
def month_name
-
elements[1]
-
end
-
-
1
def CFWS2
-
elements[2]
-
end
-
end
-
-
1
def _nt_obs_month
-
start_index = index
-
if node_cache[:obs_month].has_key?(index)
-
cached = node_cache[:obs_month][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_CFWS
-
s0 << r1
-
if r1
-
r2 = _nt_month_name
-
s0 << r2
-
if r2
-
r3 = _nt_CFWS
-
s0 << r3
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsMonth0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_month][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsDay0
-
1
def DIGIT1
-
elements[0]
-
end
-
-
1
def DIGIT2
-
elements[1]
-
end
-
end
-
-
1
module ObsDay1
-
end
-
-
1
def _nt_obs_day
-
start_index = index
-
if node_cache[:obs_day].has_key?(index)
-
cached = node_cache[:obs_day][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r2 = _nt_CFWS
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
i3 = index
-
r4 = _nt_DIGIT
-
if r4
-
r3 = r4
-
else
-
i5, s5 = index, []
-
r6 = _nt_DIGIT
-
s5 << r6
-
if r6
-
r7 = _nt_DIGIT
-
s5 << r7
-
end
-
if s5.last
-
r5 = instantiate_node(SyntaxNode,input, i5...index, s5)
-
r5.extend(ObsDay0)
-
else
-
@index = i5
-
r5 = nil
-
end
-
if r5
-
r3 = r5
-
else
-
@index = i3
-
r3 = nil
-
end
-
end
-
s0 << r3
-
if r3
-
r9 = _nt_CFWS
-
if r9
-
r8 = r9
-
else
-
r8 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r8
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsDay1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_day][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsHour0
-
1
def DIGIT1
-
elements[0]
-
end
-
-
1
def DIGIT2
-
elements[1]
-
end
-
end
-
-
1
module ObsHour1
-
end
-
-
1
def _nt_obs_hour
-
start_index = index
-
if node_cache[:obs_hour].has_key?(index)
-
cached = node_cache[:obs_hour][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r2 = _nt_CFWS
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
i3, s3 = index, []
-
r4 = _nt_DIGIT
-
s3 << r4
-
if r4
-
r5 = _nt_DIGIT
-
s3 << r5
-
end
-
if s3.last
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
r3.extend(ObsHour0)
-
else
-
@index = i3
-
r3 = nil
-
end
-
s0 << r3
-
if r3
-
r7 = _nt_CFWS
-
if r7
-
r6 = r7
-
else
-
r6 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r6
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsHour1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_hour][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsMinute0
-
1
def DIGIT1
-
elements[0]
-
end
-
-
1
def DIGIT2
-
elements[1]
-
end
-
end
-
-
1
module ObsMinute1
-
end
-
-
1
def _nt_obs_minute
-
start_index = index
-
if node_cache[:obs_minute].has_key?(index)
-
cached = node_cache[:obs_minute][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r2 = _nt_CFWS
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
i3, s3 = index, []
-
r4 = _nt_DIGIT
-
s3 << r4
-
if r4
-
r5 = _nt_DIGIT
-
s3 << r5
-
end
-
if s3.last
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
r3.extend(ObsMinute0)
-
else
-
@index = i3
-
r3 = nil
-
end
-
s0 << r3
-
if r3
-
r7 = _nt_CFWS
-
if r7
-
r6 = r7
-
else
-
r6 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r6
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsMinute1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_minute][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsSecond0
-
1
def DIGIT1
-
elements[0]
-
end
-
-
1
def DIGIT2
-
elements[1]
-
end
-
end
-
-
1
module ObsSecond1
-
end
-
-
1
def _nt_obs_second
-
start_index = index
-
if node_cache[:obs_second].has_key?(index)
-
cached = node_cache[:obs_second][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r2 = _nt_CFWS
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
i3, s3 = index, []
-
r4 = _nt_DIGIT
-
s3 << r4
-
if r4
-
r5 = _nt_DIGIT
-
s3 << r5
-
end
-
if s3.last
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
r3.extend(ObsSecond0)
-
else
-
@index = i3
-
r3 = nil
-
end
-
s0 << r3
-
if r3
-
r7 = _nt_CFWS
-
if r7
-
r6 = r7
-
else
-
r6 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r6
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsSecond1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_second][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_obs_zone
-
start_index = index
-
if node_cache[:obs_zone].has_key?(index)
-
cached = node_cache[:obs_zone][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
if has_terminal?("UT", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 2))
-
@index += 2
-
else
-
terminal_parse_failure("UT")
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
if has_terminal?("GMT", false, index)
-
r2 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("GMT")
-
r2 = nil
-
end
-
if r2
-
r0 = r2
-
else
-
if has_terminal?("EST", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("EST")
-
r3 = nil
-
end
-
if r3
-
r0 = r3
-
else
-
if has_terminal?("EDT", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("EDT")
-
r4 = nil
-
end
-
if r4
-
r0 = r4
-
else
-
if has_terminal?("CST", false, index)
-
r5 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("CST")
-
r5 = nil
-
end
-
if r5
-
r0 = r5
-
else
-
if has_terminal?("CDT", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("CDT")
-
r6 = nil
-
end
-
if r6
-
r0 = r6
-
else
-
if has_terminal?("MST", false, index)
-
r7 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("MST")
-
r7 = nil
-
end
-
if r7
-
r0 = r7
-
else
-
if has_terminal?("MDT", false, index)
-
r8 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("MDT")
-
r8 = nil
-
end
-
if r8
-
r0 = r8
-
else
-
if has_terminal?("PST", false, index)
-
r9 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("PST")
-
r9 = nil
-
end
-
if r9
-
r0 = r9
-
else
-
if has_terminal?("PDT", false, index)
-
r10 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("PDT")
-
r10 = nil
-
end
-
if r10
-
r0 = r10
-
else
-
if has_terminal?('\G[\\x41-\\x49]', true, index)
-
r11 = true
-
@index += 1
-
else
-
r11 = nil
-
end
-
if r11
-
r0 = r11
-
else
-
if has_terminal?('\G[\\x4B-\\x5A]', true, index)
-
r12 = true
-
@index += 1
-
else
-
r12 = nil
-
end
-
if r12
-
r0 = r12
-
else
-
if has_terminal?('\G[\\x61-\\x69]', true, index)
-
r13 = true
-
@index += 1
-
else
-
r13 = nil
-
end
-
if r13
-
r0 = r13
-
else
-
if has_terminal?('\G[\\x6B-\\x7A]', true, index)
-
r14 = true
-
@index += 1
-
else
-
r14 = nil
-
end
-
if r14
-
r0 = r14
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
-
node_cache[:obs_zone][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsAngleAddr0
-
1
def addr_spec
-
elements[3]
-
end
-
-
end
-
-
1
def _nt_obs_angle_addr
-
start_index = index
-
if node_cache[:obs_angle_addr].has_key?(index)
-
cached = node_cache[:obs_angle_addr][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r2 = _nt_CFWS
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
if has_terminal?("<", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("<")
-
r3 = nil
-
end
-
s0 << r3
-
if r3
-
r5 = _nt_obs_route
-
if r5
-
r4 = r5
-
else
-
r4 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r4
-
if r4
-
r6 = _nt_addr_spec
-
s0 << r6
-
if r6
-
if has_terminal?(">", false, index)
-
r7 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(">")
-
r7 = nil
-
end
-
s0 << r7
-
if r7
-
r9 = _nt_CFWS
-
if r9
-
r8 = r9
-
else
-
r8 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r8
-
end
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsAngleAddr0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_angle_addr][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsRoute0
-
1
def obs_domain_list
-
elements[1]
-
end
-
-
end
-
-
1
def _nt_obs_route
-
start_index = index
-
if node_cache[:obs_route].has_key?(index)
-
cached = node_cache[:obs_route][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r2 = _nt_CFWS
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
r3 = _nt_obs_domain_list
-
s0 << r3
-
if r3
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r6 = _nt_CFWS
-
if r6
-
r5 = r6
-
else
-
r5 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r5
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsRoute0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_route][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsDomainList0
-
1
def domain
-
elements[3]
-
end
-
end
-
-
1
module ObsDomainList1
-
1
def domain
-
elements[1]
-
end
-
-
end
-
-
1
def _nt_obs_domain_list
-
start_index = index
-
if node_cache[:obs_domain_list].has_key?(index)
-
cached = node_cache[:obs_domain_list][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("@", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("@")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
r2 = _nt_domain
-
s0 << r2
-
if r2
-
s3, i3 = [], index
-
loop do
-
i4, s4 = index, []
-
s5, i5 = [], index
-
loop do
-
if has_terminal?(",", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(",")
-
r6 = nil
-
end
-
if r6
-
s5 << r6
-
else
-
break
-
end
-
end
-
r5 = instantiate_node(SyntaxNode,input, i5...index, s5)
-
s4 << r5
-
if r5
-
r8 = _nt_CFWS
-
if r8
-
r7 = r8
-
else
-
r7 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s4 << r7
-
if r7
-
if has_terminal?("@", false, index)
-
r9 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("@")
-
r9 = nil
-
end
-
s4 << r9
-
if r9
-
r10 = _nt_domain
-
s4 << r10
-
end
-
end
-
end
-
if s4.last
-
r4 = instantiate_node(SyntaxNode,input, i4...index, s4)
-
r4.extend(ObsDomainList0)
-
else
-
@index = i4
-
r4 = nil
-
end
-
if r4
-
s3 << r4
-
else
-
break
-
end
-
end
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
s0 << r3
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsDomainList1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_domain_list][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsLocalPart0
-
1
def word
-
elements[1]
-
end
-
end
-
-
1
module ObsLocalPart1
-
1
def word
-
elements[0]
-
end
-
-
end
-
-
1
def _nt_obs_local_part
-
start_index = index
-
if node_cache[:obs_local_part].has_key?(index)
-
cached = node_cache[:obs_local_part][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_word
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
i3, s3 = index, []
-
if has_terminal?(".", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(".")
-
r4 = nil
-
end
-
s3 << r4
-
if r4
-
r5 = _nt_word
-
s3 << r5
-
end
-
if s3.last
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
r3.extend(ObsLocalPart0)
-
else
-
@index = i3
-
r3 = nil
-
end
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsLocalPart1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_local_part][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsDomain0
-
1
def atom
-
elements[1]
-
end
-
end
-
-
1
module ObsDomain1
-
1
def atom
-
elements[0]
-
end
-
-
end
-
-
1
def _nt_obs_domain
-
start_index = index
-
if node_cache[:obs_domain].has_key?(index)
-
cached = node_cache[:obs_domain][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_atom
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
i3, s3 = index, []
-
if has_terminal?(".", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(".")
-
r4 = nil
-
end
-
s3 << r4
-
if r4
-
r5 = _nt_atom
-
s3 << r5
-
end
-
if s3.last
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
r3.extend(ObsDomain0)
-
else
-
@index = i3
-
r3 = nil
-
end
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsDomain1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_domain][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsMboxList0
-
end
-
-
1
module ObsMboxList1
-
end
-
-
1
def _nt_obs_mbox_list
-
start_index = index
-
if node_cache[:obs_mbox_list].has_key?(index)
-
cached = node_cache[:obs_mbox_list][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
s1, i1 = [], index
-
loop do
-
i2, s2 = index, []
-
r4 = _nt_mailbox
-
if r4
-
r3 = r4
-
else
-
r3 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s2 << r3
-
if r3
-
r6 = _nt_CFWS
-
if r6
-
r5 = r6
-
else
-
r5 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s2 << r5
-
if r5
-
if has_terminal?(",", false, index)
-
r7 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(",")
-
r7 = nil
-
end
-
s2 << r7
-
if r7
-
r9 = _nt_CFWS
-
if r9
-
r8 = r9
-
else
-
r8 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s2 << r8
-
end
-
end
-
end
-
if s2.last
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
r2.extend(ObsMboxList0)
-
else
-
@index = i2
-
r2 = nil
-
end
-
if r2
-
s1 << r2
-
else
-
break
-
end
-
end
-
if s1.empty?
-
@index = i1
-
r1 = nil
-
else
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
end
-
s0 << r1
-
if r1
-
r11 = _nt_mailbox
-
if r11
-
r10 = r11
-
else
-
r10 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r10
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsMboxList1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_mbox_list][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsAddrList0
-
end
-
-
1
module ObsAddrList1
-
end
-
-
1
def _nt_obs_addr_list
-
start_index = index
-
if node_cache[:obs_addr_list].has_key?(index)
-
cached = node_cache[:obs_addr_list][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
s1, i1 = [], index
-
loop do
-
i2, s2 = index, []
-
r4 = _nt_address
-
if r4
-
r3 = r4
-
else
-
r3 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s2 << r3
-
if r3
-
r6 = _nt_CFWS
-
if r6
-
r5 = r6
-
else
-
r5 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s2 << r5
-
if r5
-
if has_terminal?(",", false, index)
-
r7 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(",")
-
r7 = nil
-
end
-
s2 << r7
-
if r7
-
r9 = _nt_CFWS
-
if r9
-
r8 = r9
-
else
-
r8 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s2 << r8
-
end
-
end
-
end
-
if s2.last
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
r2.extend(ObsAddrList0)
-
else
-
@index = i2
-
r2 = nil
-
end
-
if r2
-
s1 << r2
-
else
-
break
-
end
-
end
-
if s1.empty?
-
@index = i1
-
r1 = nil
-
else
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
end
-
s0 << r1
-
if r1
-
r11 = _nt_address
-
if r11
-
r10 = r11
-
else
-
r10 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r10
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsAddrList1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_addr_list][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_obs_fields
-
start_index = index
-
if node_cache[:obs_fields].has_key?(index)
-
cached = node_cache[:obs_fields][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
s0, i0 = [], index
-
loop do
-
i1 = index
-
r2 = _nt_obs_return
-
if r2
-
r1 = r2
-
else
-
r3 = _nt_obs_received
-
if r3
-
r1 = r3
-
else
-
r4 = _nt_obs_orig_date
-
if r4
-
r1 = r4
-
else
-
r5 = _nt_obs_from
-
if r5
-
r1 = r5
-
else
-
r6 = _nt_obs_sender
-
if r6
-
r1 = r6
-
else
-
r7 = _nt_obs_reply_to
-
if r7
-
r1 = r7
-
else
-
r8 = _nt_obs_to
-
if r8
-
r1 = r8
-
else
-
r9 = _nt_obs_cc
-
if r9
-
r1 = r9
-
else
-
r10 = _nt_obs_bcc
-
if r10
-
r1 = r10
-
else
-
r11 = _nt_obs_message_id
-
if r11
-
r1 = r11
-
else
-
r12 = _nt_obs_in_reply_to
-
if r12
-
r1 = r12
-
else
-
r13 = _nt_obs_references
-
if r13
-
r1 = r13
-
else
-
r14 = _nt_obs_subject
-
if r14
-
r1 = r14
-
else
-
r15 = _nt_obs_comments
-
if r15
-
r1 = r15
-
else
-
r16 = _nt_obs_keywords
-
if r16
-
r1 = r16
-
else
-
r17 = _nt_obs_resent_date
-
if r17
-
r1 = r17
-
else
-
r18 = _nt_obs_resent_from
-
if r18
-
r1 = r18
-
else
-
r19 = _nt_obs_resent_send
-
if r19
-
r1 = r19
-
else
-
r20 = _nt_obs_resent_rply
-
if r20
-
r1 = r20
-
else
-
r21 = _nt_obs_resent_to
-
if r21
-
r1 = r21
-
else
-
r22 = _nt_obs_resent_cc
-
if r22
-
r1 = r22
-
else
-
r23 = _nt_obs_resent_bcc
-
if r23
-
r1 = r23
-
else
-
r24 = _nt_obs_resent_mid
-
if r24
-
r1 = r24
-
else
-
r25 = _nt_obs_optional
-
if r25
-
r1 = r25
-
else
-
@index = i1
-
r1 = nil
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
if r1
-
s0 << r1
-
else
-
break
-
end
-
end
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
-
node_cache[:obs_fields][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsOrigDate0
-
1
def date_time
-
elements[3]
-
end
-
-
1
def CRLF
-
elements[4]
-
end
-
end
-
-
1
def _nt_obs_orig_date
-
start_index = index
-
if node_cache[:obs_orig_date].has_key?(index)
-
cached = node_cache[:obs_orig_date][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Date", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 4))
-
@index += 4
-
else
-
terminal_parse_failure("Date")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_date_time
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsOrigDate0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_orig_date][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsFrom0
-
1
def mailbox_list
-
elements[3]
-
end
-
-
1
def CRLF
-
elements[4]
-
end
-
end
-
-
1
def _nt_obs_from
-
start_index = index
-
if node_cache[:obs_from].has_key?(index)
-
cached = node_cache[:obs_from][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("From", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 4))
-
@index += 4
-
else
-
terminal_parse_failure("From")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_mailbox_list
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsFrom0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_from][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsSender0
-
1
def mailbox
-
elements[3]
-
end
-
-
1
def CRLF
-
elements[4]
-
end
-
end
-
-
1
def _nt_obs_sender
-
start_index = index
-
if node_cache[:obs_sender].has_key?(index)
-
cached = node_cache[:obs_sender][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Sender", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 6))
-
@index += 6
-
else
-
terminal_parse_failure("Sender")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_mailbox
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsSender0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_sender][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsReplyTo0
-
1
def mailbox_list
-
elements[3]
-
end
-
-
1
def CRLF
-
elements[4]
-
end
-
end
-
-
1
def _nt_obs_reply_to
-
start_index = index
-
if node_cache[:obs_reply_to].has_key?(index)
-
cached = node_cache[:obs_reply_to][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Reply-To", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 8))
-
@index += 8
-
else
-
terminal_parse_failure("Reply-To")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_mailbox_list
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsReplyTo0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_reply_to][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsTo0
-
1
def address_list
-
elements[3]
-
end
-
-
1
def CRLF
-
elements[4]
-
end
-
end
-
-
1
def _nt_obs_to
-
start_index = index
-
if node_cache[:obs_to].has_key?(index)
-
cached = node_cache[:obs_to][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("To", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 2))
-
@index += 2
-
else
-
terminal_parse_failure("To")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_address_list
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsTo0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_to][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsCc0
-
1
def address_list
-
elements[3]
-
end
-
-
1
def CRLF
-
elements[4]
-
end
-
end
-
-
1
def _nt_obs_cc
-
start_index = index
-
if node_cache[:obs_cc].has_key?(index)
-
cached = node_cache[:obs_cc][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Cc", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 2))
-
@index += 2
-
else
-
terminal_parse_failure("Cc")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_address_list
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsCc0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_cc][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsBcc0
-
1
def CRLF
-
elements[4]
-
end
-
end
-
-
1
def _nt_obs_bcc
-
start_index = index
-
if node_cache[:obs_bcc].has_key?(index)
-
cached = node_cache[:obs_bcc][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Bcc", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Bcc")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
i5 = index
-
r6 = _nt_address_list
-
if r6
-
r5 = r6
-
else
-
r8 = _nt_CFWS
-
if r8
-
r7 = r8
-
else
-
r7 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
if r7
-
r5 = r7
-
else
-
@index = i5
-
r5 = nil
-
end
-
end
-
s0 << r5
-
if r5
-
r9 = _nt_CRLF
-
s0 << r9
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsBcc0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_bcc][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsMessageId0
-
1
def msg_id
-
elements[3]
-
end
-
-
1
def CRLF
-
elements[4]
-
end
-
end
-
-
1
def _nt_obs_message_id
-
start_index = index
-
if node_cache[:obs_message_id].has_key?(index)
-
cached = node_cache[:obs_message_id][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Message-ID", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 10))
-
@index += 10
-
else
-
terminal_parse_failure("Message-ID")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_msg_id
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsMessageId0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_message_id][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsInReplyTo0
-
1
def CRLF
-
elements[4]
-
end
-
end
-
-
1
def _nt_obs_in_reply_to
-
start_index = index
-
if node_cache[:obs_in_reply_to].has_key?(index)
-
cached = node_cache[:obs_in_reply_to][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("In-Reply-To", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 11))
-
@index += 11
-
else
-
terminal_parse_failure("In-Reply-To")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
s5, i5 = [], index
-
loop do
-
i6 = index
-
r7 = _nt_phrase
-
if r7
-
r6 = r7
-
else
-
r8 = _nt_msg_id
-
if r8
-
r6 = r8
-
else
-
@index = i6
-
r6 = nil
-
end
-
end
-
if r6
-
s5 << r6
-
else
-
break
-
end
-
end
-
r5 = instantiate_node(SyntaxNode,input, i5...index, s5)
-
s0 << r5
-
if r5
-
r9 = _nt_CRLF
-
s0 << r9
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsInReplyTo0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_in_reply_to][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsReferences0
-
1
def CRLF
-
elements[4]
-
end
-
end
-
-
1
def _nt_obs_references
-
start_index = index
-
if node_cache[:obs_references].has_key?(index)
-
cached = node_cache[:obs_references][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("References", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 10))
-
@index += 10
-
else
-
terminal_parse_failure("References")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
s5, i5 = [], index
-
loop do
-
i6 = index
-
r7 = _nt_phrase
-
if r7
-
r6 = r7
-
else
-
r8 = _nt_msg_id
-
if r8
-
r6 = r8
-
else
-
@index = i6
-
r6 = nil
-
end
-
end
-
if r6
-
s5 << r6
-
else
-
break
-
end
-
end
-
r5 = instantiate_node(SyntaxNode,input, i5...index, s5)
-
s0 << r5
-
if r5
-
r9 = _nt_CRLF
-
s0 << r9
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsReferences0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_references][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_obs_id_left
-
start_index = index
-
if node_cache[:obs_id_left].has_key?(index)
-
cached = node_cache[:obs_id_left][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
r0 = _nt_local_part
-
-
node_cache[:obs_id_left][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_obs_id_right
-
start_index = index
-
if node_cache[:obs_id_right].has_key?(index)
-
cached = node_cache[:obs_id_right][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
r0 = _nt_domain
-
-
node_cache[:obs_id_right][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsSubject0
-
1
def unstructured
-
elements[3]
-
end
-
-
1
def CRLF
-
elements[4]
-
end
-
end
-
-
1
def _nt_obs_subject
-
start_index = index
-
if node_cache[:obs_subject].has_key?(index)
-
cached = node_cache[:obs_subject][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Subject", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 7))
-
@index += 7
-
else
-
terminal_parse_failure("Subject")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_unstructured
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsSubject0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_subject][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsComments0
-
1
def unstructured
-
elements[3]
-
end
-
-
1
def CRLF
-
elements[4]
-
end
-
end
-
-
1
def _nt_obs_comments
-
start_index = index
-
if node_cache[:obs_comments].has_key?(index)
-
cached = node_cache[:obs_comments][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Comments", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 8))
-
@index += 8
-
else
-
terminal_parse_failure("Comments")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_unstructured
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsComments0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_comments][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsKeywords0
-
1
def obs_phrase_list
-
elements[3]
-
end
-
-
1
def CRLF
-
elements[4]
-
end
-
end
-
-
1
def _nt_obs_keywords
-
start_index = index
-
if node_cache[:obs_keywords].has_key?(index)
-
cached = node_cache[:obs_keywords][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Keywords", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 8))
-
@index += 8
-
else
-
terminal_parse_failure("Keywords")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_obs_phrase_list
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsKeywords0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_keywords][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsResentFrom0
-
1
def mailbox_list
-
elements[3]
-
end
-
-
1
def CRLF
-
elements[4]
-
end
-
end
-
-
1
def _nt_obs_resent_from
-
start_index = index
-
if node_cache[:obs_resent_from].has_key?(index)
-
cached = node_cache[:obs_resent_from][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Resent-From", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 11))
-
@index += 11
-
else
-
terminal_parse_failure("Resent-From")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_mailbox_list
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsResentFrom0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_resent_from][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsResentSend0
-
1
def mailbox
-
elements[3]
-
end
-
-
1
def CRLF
-
elements[4]
-
end
-
end
-
-
1
def _nt_obs_resent_send
-
start_index = index
-
if node_cache[:obs_resent_send].has_key?(index)
-
cached = node_cache[:obs_resent_send][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Resent-Sender", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 13))
-
@index += 13
-
else
-
terminal_parse_failure("Resent-Sender")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_mailbox
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsResentSend0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_resent_send][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsResentDate0
-
1
def date_time
-
elements[3]
-
end
-
-
1
def CRLF
-
elements[4]
-
end
-
end
-
-
1
def _nt_obs_resent_date
-
start_index = index
-
if node_cache[:obs_resent_date].has_key?(index)
-
cached = node_cache[:obs_resent_date][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Resent-Date", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 11))
-
@index += 11
-
else
-
terminal_parse_failure("Resent-Date")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_date_time
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsResentDate0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_resent_date][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsResentTo0
-
1
def address_list
-
elements[3]
-
end
-
-
1
def CRLF
-
elements[4]
-
end
-
end
-
-
1
def _nt_obs_resent_to
-
start_index = index
-
if node_cache[:obs_resent_to].has_key?(index)
-
cached = node_cache[:obs_resent_to][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Resent-To", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 9))
-
@index += 9
-
else
-
terminal_parse_failure("Resent-To")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_address_list
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsResentTo0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_resent_to][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsResentCc0
-
1
def address_list
-
elements[3]
-
end
-
-
1
def CRLF
-
elements[4]
-
end
-
end
-
-
1
def _nt_obs_resent_cc
-
start_index = index
-
if node_cache[:obs_resent_cc].has_key?(index)
-
cached = node_cache[:obs_resent_cc][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Resent-Cc", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 9))
-
@index += 9
-
else
-
terminal_parse_failure("Resent-Cc")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_address_list
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsResentCc0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_resent_cc][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsResentBcc0
-
1
def CRLF
-
elements[4]
-
end
-
end
-
-
1
def _nt_obs_resent_bcc
-
start_index = index
-
if node_cache[:obs_resent_bcc].has_key?(index)
-
cached = node_cache[:obs_resent_bcc][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Resent-Bcc", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 10))
-
@index += 10
-
else
-
terminal_parse_failure("Resent-Bcc")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
i5 = index
-
r6 = _nt_address_list
-
if r6
-
r5 = r6
-
else
-
r8 = _nt_CFWS
-
if r8
-
r7 = r8
-
else
-
r7 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
if r7
-
r5 = r7
-
else
-
@index = i5
-
r5 = nil
-
end
-
end
-
s0 << r5
-
if r5
-
r9 = _nt_CRLF
-
s0 << r9
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsResentBcc0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_resent_bcc][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsResentMid0
-
1
def msg_id
-
elements[3]
-
end
-
-
1
def CRLF
-
elements[4]
-
end
-
end
-
-
1
def _nt_obs_resent_mid
-
start_index = index
-
if node_cache[:obs_resent_mid].has_key?(index)
-
cached = node_cache[:obs_resent_mid][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Resent-Message-ID", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 17))
-
@index += 17
-
else
-
terminal_parse_failure("Resent-Message-ID")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_msg_id
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsResentMid0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_resent_mid][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsResentRply0
-
1
def address_list
-
elements[3]
-
end
-
-
1
def CRLF
-
elements[4]
-
end
-
end
-
-
1
def _nt_obs_resent_rply
-
start_index = index
-
if node_cache[:obs_resent_rply].has_key?(index)
-
cached = node_cache[:obs_resent_rply][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Resent-Reply-To", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 15))
-
@index += 15
-
else
-
terminal_parse_failure("Resent-Reply-To")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_address_list
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsResentRply0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_resent_rply][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsReturn0
-
1
def path
-
elements[3]
-
end
-
-
1
def CRLF
-
elements[4]
-
end
-
end
-
-
1
def _nt_obs_return
-
start_index = index
-
if node_cache[:obs_return].has_key?(index)
-
cached = node_cache[:obs_return][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Return-Path", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 11))
-
@index += 11
-
else
-
terminal_parse_failure("Return-Path")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_path
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsReturn0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_return][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsReceived0
-
1
def name_val_list
-
elements[3]
-
end
-
-
1
def CRLF
-
elements[4]
-
end
-
end
-
-
1
def _nt_obs_received
-
start_index = index
-
if node_cache[:obs_received].has_key?(index)
-
cached = node_cache[:obs_received][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Received", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 8))
-
@index += 8
-
else
-
terminal_parse_failure("Received")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_name_val_list
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsReceived0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_received][start_index] = r0
-
-
r0
-
end
-
-
1
def _nt_obs_path
-
start_index = index
-
if node_cache[:obs_path].has_key?(index)
-
cached = node_cache[:obs_path][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
r0 = _nt_obs_angle_addr
-
-
node_cache[:obs_path][start_index] = r0
-
-
r0
-
end
-
-
1
module ObsOptional0
-
1
def field_name
-
elements[0]
-
end
-
-
1
def unstructured
-
elements[3]
-
end
-
-
1
def CRLF
-
elements[4]
-
end
-
end
-
-
1
def _nt_obs_optional
-
start_index = index
-
if node_cache[:obs_optional].has_key?(index)
-
cached = node_cache[:obs_optional][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_field_name
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_unstructured
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsOptional0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_optional][start_index] = r0
-
-
r0
-
end
-
-
end
-
-
1
class RFC2822ObsoleteParser < Treetop::Runtime::CompiledParser
-
1
include RFC2822Obsolete
-
end
-
-
end
-
# encoding: utf-8
-
1
module Mail
-
1
class Part < Message
-
-
# Creates a new empty Content-ID field and inserts it in the correct order
-
# into the Header. The ContentIdField object will automatically generate
-
# a unique content ID if you try and encode it or output it to_s without
-
# specifying a content id.
-
#
-
# It will preserve the content ID you specify if you do.
-
1
def add_content_id(content_id_val = '')
-
header['content-id'] = content_id_val
-
end
-
-
# Returns true if the part has a content ID field, the field may or may
-
# not have a value, but the field exists or not.
-
1
def has_content_id?
-
header.has_content_id?
-
end
-
-
1
def inline_content_id
-
# TODO: Deprecated in 2.2.2 - Remove in 2.3
-
STDERR.puts("Part#inline_content_id is deprecated, please call Part#cid instead")
-
cid
-
end
-
-
1
def cid
-
add_content_id unless has_content_id?
-
uri_escape(unbracket(content_id))
-
end
-
-
1
def url
-
"cid:#{cid}"
-
end
-
-
1
def inline?
-
header[:content_disposition].disposition_type == 'inline' if header[:content_disposition]
-
end
-
-
1
def add_required_fields
-
super
-
add_content_id if !has_content_id? && inline?
-
end
-
-
1
def add_required_message_fields
-
# Override so we don't add Date, MIME-Version, or Message-ID.
-
end
-
-
1
def delivery_status_report_part?
-
(main_type =~ /message/i && sub_type =~ /delivery-status/i) && body =~ /Status:/
-
end
-
-
1
def delivery_status_data
-
delivery_status_report_part? ? parse_delivery_status_report : {}
-
end
-
-
1
def bounced?
-
if action.is_a?(Array)
-
!!(action.first =~ /failed/i)
-
else
-
!!(action =~ /failed/i)
-
end
-
end
-
-
-
# Either returns the action if the message has just a single report, or an
-
# array of all the actions, one for each report
-
1
def action
-
get_return_values('action')
-
end
-
-
1
def final_recipient
-
get_return_values('final-recipient')
-
end
-
-
1
def error_status
-
get_return_values('status')
-
end
-
-
1
def diagnostic_code
-
get_return_values('diagnostic-code')
-
end
-
-
1
def remote_mta
-
get_return_values('remote-mta')
-
end
-
-
1
def retryable?
-
!(error_status =~ /^5/)
-
end
-
-
1
private
-
-
1
def get_return_values(key)
-
if delivery_status_data[key].is_a?(Array)
-
delivery_status_data[key].map { |a| a.value }
-
else
-
delivery_status_data[key].value
-
end
-
end
-
-
# A part may not have a header.... so, just init a body if no header
-
1
def parse_message
-
header_part, body_part = raw_source.split(/#{CRLF}#{WSP}*#{CRLF}/m, 2)
-
if header_part =~ HEADER_LINE
-
self.header = header_part
-
self.body = body_part
-
else
-
self.header = "Content-Type: text/plain\r\n"
-
self.body = raw_source
-
end
-
end
-
-
1
def parse_delivery_status_report
-
@delivery_status_data ||= Header.new(body.to_s.gsub("\r\n\r\n", "\r\n"))
-
end
-
-
end
-
-
end
-
1
module Mail
-
1
class PartsList < Array
-
-
1
def attachments
-
Mail::AttachmentsList.new(self)
-
end
-
-
1
def collect
-
if block_given?
-
ary = PartsList.new
-
each { |o| ary << yield(o) }
-
ary
-
else
-
to_a
-
end
-
end
-
-
1
undef :map
-
1
alias_method :map, :collect
-
-
1
def map!
-
raise NoMethodError, "#map! is not defined, please call #collect and create a new PartsList"
-
end
-
-
1
def collect!
-
raise NoMethodError, "#collect! is not defined, please call #collect and create a new PartsList"
-
end
-
-
1
def sort
-
self.class.new(super)
-
end
-
-
1
def sort!(order)
-
sorted = self.sort do |a, b|
-
# OK, 10000 is arbitrary... if anyone actually wants to explicitly sort 10000 parts of a
-
# single email message... please show me a use case and I'll put more work into this method,
-
# in the meantime, it works :)
-
get_order_value(a, order) <=> get_order_value(b, order)
-
end
-
self.clear
-
sorted.each { |p| self << p }
-
end
-
-
1
private
-
-
1
def get_order_value(part, order)
-
if part.respond_to?(:content_type)
-
order.index(part[:content_type].string.downcase) || 10000
-
else
-
10000
-
end
-
end
-
-
end
-
end
-
# encoding: us-ascii
-
1
module Mail
-
1
module Patterns
-
1
white_space = %Q|\x9\x20|
-
1
text = %Q|\x1-\x8\xB\xC\xE-\x7f|
-
1
field_name = %Q|\x21-\x39\x3b-\x7e|
-
1
qp_safe = %Q|\x20-\x3c\x3e-\x7e|
-
-
1
aspecial = %Q|()<>[]:;@\\,."| # RFC5322
-
1
tspecial = %Q|()<>@,;:\\"/[]?=| # RFC2045
-
1
sp = %Q| |
-
1
control = %Q|\x00-\x1f\x7f-\xff|
-
-
1
if control.respond_to?(:force_encoding)
-
1
control = control.force_encoding(Encoding::BINARY)
-
end
-
-
1
CRLF = /\r\n/
-
1
WSP = /[#{white_space}]/
-
1
FWS = /#{CRLF}#{WSP}*/
-
1
TEXT = /[#{text}]/ # + obs-text
-
1
FIELD_NAME = /[#{field_name}]+/
-
1
FIELD_BODY = /.+/
-
1
FIELD_LINE = /^[#{field_name}]+:\s*.+$/
-
1
FIELD_SPLIT = /^(#{FIELD_NAME})\s*:\s*(#{FIELD_BODY})?$/
-
1
HEADER_LINE = /^([#{field_name}]+:\s*.+)$/
-
-
1
QP_UNSAFE = /[^#{qp_safe}]/
-
1
QP_SAFE = /[#{qp_safe}]/
-
1
CONTROL_CHAR = /[#{control}]/n
-
1
ATOM_UNSAFE = /[#{Regexp.quote aspecial}#{control}#{sp}]/n
-
1
PHRASE_UNSAFE = /[#{Regexp.quote aspecial}#{control}]/n
-
1
TOKEN_UNSAFE = /[#{Regexp.quote tspecial}#{control}#{sp}]/n
-
end
-
end
-
# encoding: utf-8
-
1
module Mail
-
1
module Utilities
-
1
include Patterns
-
-
# Returns true if the string supplied is free from characters not allowed as an ATOM
-
1
def atom_safe?( str )
-
not ATOM_UNSAFE === str
-
end
-
-
# If the string supplied has ATOM unsafe characters in it, will return the string quoted
-
# in double quotes, otherwise returns the string unmodified
-
1
def quote_atom( str )
-
atom_safe?( str ) ? str : dquote(str)
-
end
-
-
# If the string supplied has PHRASE unsafe characters in it, will return the string quoted
-
# in double quotes, otherwise returns the string unmodified
-
1
def quote_phrase( str )
-
if RUBY_VERSION >= '1.9'
-
original_encoding = str.encoding
-
str.force_encoding('ASCII-8BIT')
-
if (PHRASE_UNSAFE === str)
-
dquote(str).force_encoding(original_encoding)
-
else
-
str.force_encoding(original_encoding)
-
end
-
else
-
(PHRASE_UNSAFE === str) ? dquote(str) : str
-
end
-
end
-
-
# Returns true if the string supplied is free from characters not allowed as a TOKEN
-
1
def token_safe?( str )
-
not TOKEN_UNSAFE === str
-
end
-
-
# If the string supplied has TOKEN unsafe characters in it, will return the string quoted
-
# in double quotes, otherwise returns the string unmodified
-
1
def quote_token( str )
-
token_safe?( str ) ? str : dquote(str)
-
end
-
-
# Wraps supplied string in double quotes and applies \-escaping as necessary,
-
# unless it is already wrapped.
-
#
-
# Example:
-
#
-
# string = 'This is a string'
-
# dquote(string) #=> '"This is a string"'
-
#
-
# string = 'This is "a string"'
-
# dquote(string #=> '"This is \"a string\"'
-
1
def dquote( str )
-
'"' + unquote(str).gsub(/[\\"]/n) {|s| '\\' + s } + '"'
-
end
-
-
# Unwraps supplied string from inside double quotes and
-
# removes any \-escaping.
-
#
-
# Example:
-
#
-
# string = '"This is a string"'
-
# unquote(string) #=> 'This is a string'
-
#
-
# string = '"This is \"a string\""'
-
# unqoute(string) #=> 'This is "a string"'
-
1
def unquote( str )
-
if str =~ /^"(.*?)"$/
-
$1.gsub(/\\(.)/, '\1')
-
else
-
str
-
end
-
end
-
-
# Wraps a string in parenthesis and escapes any that are in the string itself.
-
#
-
# Example:
-
#
-
# paren( 'This is a string' ) #=> '(This is a string)'
-
1
def paren( str )
-
RubyVer.paren( str )
-
end
-
-
# Unwraps a string from being wrapped in parenthesis
-
#
-
# Example:
-
#
-
# str = '(This is a string)'
-
# unparen( str ) #=> 'This is a string'
-
1
def unparen( str )
-
match = str.match(/^\((.*?)\)$/)
-
match ? match[1] : str
-
end
-
-
# Wraps a string in angle brackets and escapes any that are in the string itself
-
#
-
# Example:
-
#
-
# bracket( 'This is a string' ) #=> '<This is a string>'
-
1
def bracket( str )
-
RubyVer.bracket( str )
-
end
-
-
# Unwraps a string from being wrapped in parenthesis
-
#
-
# Example:
-
#
-
# str = '<This is a string>'
-
# unbracket( str ) #=> 'This is a string'
-
1
def unbracket( str )
-
match = str.match(/^\<(.*?)\>$/)
-
match ? match[1] : str
-
end
-
-
# Escape parenthesies in a string
-
#
-
# Example:
-
#
-
# str = 'This is (a) string'
-
# escape_paren( str ) #=> 'This is \(a\) string'
-
1
def escape_paren( str )
-
RubyVer.escape_paren( str )
-
end
-
-
1
def uri_escape( str )
-
uri_parser.escape(str)
-
end
-
-
1
def uri_unescape( str )
-
uri_parser.unescape(str)
-
end
-
-
1
def uri_parser
-
@uri_parser ||= URI.const_defined?(:Parser) ? URI::Parser.new : URI
-
end
-
-
# Matches two objects with their to_s values case insensitively
-
#
-
# Example:
-
#
-
# obj2 = "This_is_An_object"
-
# obj1 = :this_IS_an_object
-
# match_to_s( obj1, obj2 ) #=> true
-
1
def match_to_s( obj1, obj2 )
-
obj1.to_s.casecmp(obj2.to_s) == 0
-
end
-
-
# Capitalizes a string that is joined by hyphens correctly.
-
#
-
# Example:
-
#
-
# string = 'resent-from-field'
-
# capitalize_field( string ) #=> 'Resent-From-Field'
-
1
def capitalize_field( str )
-
str.to_s.split("-").map { |v| v.capitalize }.join("-")
-
end
-
-
# Takes an underscored word and turns it into a class name
-
#
-
# Example:
-
#
-
# constantize("hello") #=> "Hello"
-
# constantize("hello-there") #=> "HelloThere"
-
# constantize("hello-there-mate") #=> "HelloThereMate"
-
1
def constantize( str )
-
str.to_s.split(/[-_]/).map { |v| v.capitalize }.to_s
-
end
-
-
# Swaps out all underscores (_) for hyphens (-) good for stringing from symbols
-
# a field name.
-
#
-
# Example:
-
#
-
# string = :resent_from_field
-
# dasherize ( string ) #=> 'resent_from_field'
-
1
def dasherize( str )
-
str.to_s.gsub('_', '-')
-
end
-
-
# Swaps out all hyphens (-) for underscores (_) good for stringing to symbols
-
# a field name.
-
#
-
# Example:
-
#
-
# string = :resent_from_field
-
# underscoreize ( string ) #=> 'resent_from_field'
-
1
def underscoreize( str )
-
str.to_s.downcase.gsub('-', '_')
-
end
-
-
1
if RUBY_VERSION <= '1.8.6'
-
-
def map_lines( str, &block )
-
results = []
-
str.each_line do |line|
-
results << yield(line)
-
end
-
results
-
end
-
-
def map_with_index( enum, &block )
-
results = []
-
enum.each_with_index do |token, i|
-
results[i] = yield(token, i)
-
end
-
results
-
end
-
-
else
-
-
1
def map_lines( str, &block )
-
str.each_line.map(&block)
-
end
-
-
1
def map_with_index( enum, &block )
-
enum.each_with_index.map(&block)
-
end
-
-
end
-
-
end
-
end
-
# encoding: utf-8
-
1
module Mail
-
1
module VERSION
-
-
1
version = {}
-
1
File.read(File.join(File.dirname(__FILE__), '../', 'VERSION')).each_line do |line|
-
4
type, value = line.chomp.split(":")
-
4
next if type =~ /^\s+$/ || value =~ /^\s+$/
-
4
version[type] = value
-
end
-
-
1
MAJOR = version['major']
-
1
MINOR = version['minor']
-
1
PATCH = version['patch']
-
1
BUILD = version['build']
-
-
1
STRING = [MAJOR, MINOR, PATCH, BUILD].compact.join('.')
-
-
1
def self.version
-
STRING
-
end
-
-
end
-
end
-
# encoding: utf-8
-
-
1
module Mail
-
1
class Ruby19
-
-
# Escapes any parenthesis in a string that are unescaped this uses
-
# a Ruby 1.9.1 regexp feature of negative look behind
-
1
def Ruby19.escape_paren( str )
-
re = /(?<!\\)([\(\)])/ # Only match unescaped parens
-
str.gsub(re) { |s| '\\' + s }
-
end
-
-
1
def Ruby19.paren( str )
-
str = $1 if str =~ /^\((.*)?\)$/
-
str = escape_paren( str )
-
'(' + str + ')'
-
end
-
-
1
def Ruby19.escape_bracket( str )
-
re = /(?<!\\)([\<\>])/ # Only match unescaped brackets
-
str.gsub(re) { |s| '\\' + s }
-
end
-
-
1
def Ruby19.bracket( str )
-
str = $1 if str =~ /^\<(.*)?\>$/
-
str = escape_bracket( str )
-
'<' + str + '>'
-
end
-
-
1
def Ruby19.decode_base64(str)
-
str.unpack( 'm' ).first
-
end
-
-
1
def Ruby19.encode_base64(str)
-
[str].pack( 'm' )
-
end
-
-
1
def Ruby19.has_constant?(klass, string)
-
klass.const_defined?( string, false )
-
end
-
-
1
def Ruby19.get_constant(klass, string)
-
klass.const_get( string )
-
end
-
-
1
def Ruby19.b_value_encode(str, encoding = nil)
-
encoding = str.encoding.to_s
-
[Ruby19.encode_base64(str), encoding]
-
end
-
-
1
def Ruby19.b_value_decode(str)
-
match = str.match(/\=\?(.+)?\?[Bb]\?(.+)?\?\=/m)
-
if match
-
charset = match[1]
-
str = Ruby19.decode_base64(match[2])
-
str.force_encoding(pick_encoding(charset))
-
end
-
decoded = str.encode("utf-8", :invalid => :replace, :replace => "")
-
decoded.valid_encoding? ? decoded : decoded.encode("utf-16le", :invalid => :replace, :replace => "").encode("utf-8")
-
end
-
-
1
def Ruby19.q_value_encode(str, encoding = nil)
-
encoding = str.encoding.to_s
-
[Encodings::QuotedPrintable.encode(str), encoding]
-
end
-
-
1
def Ruby19.q_value_decode(str)
-
match = str.match(/\=\?(.+)?\?[Qq]\?(.+)?\?\=/m)
-
if match
-
charset = match[1]
-
string = match[2].gsub(/_/, '=20')
-
# Remove trailing = if it exists in a Q encoding
-
string = string.sub(/\=$/, '')
-
str = Encodings::QuotedPrintable.decode(string)
-
str.force_encoding(pick_encoding(charset))
-
end
-
decoded = str.encode("utf-8", :invalid => :replace, :replace => "")
-
decoded.valid_encoding? ? decoded : decoded.encode("utf-16le", :invalid => :replace, :replace => "").encode("utf-8")
-
rescue Encoding::UndefinedConversionError
-
str.dup.force_encoding("utf-8")
-
end
-
-
1
def Ruby19.param_decode(str, encoding)
-
string = uri_parser.unescape(str)
-
string.force_encoding(encoding) if encoding
-
string
-
end
-
-
1
def Ruby19.param_encode(str)
-
encoding = str.encoding.to_s.downcase
-
language = Configuration.instance.param_encode_language
-
"#{encoding}'#{language}'#{uri_parser.escape(str)}"
-
end
-
-
1
def Ruby19.uri_parser
-
@uri_parser ||= URI::Parser.new
-
end
-
-
# Pick a Ruby encoding corresponding to the message charset. Most
-
# charsets have a Ruby encoding, but some need manual aliasing here.
-
#
-
# TODO: add this as a test somewhere:
-
# Encoding.list.map { |e| [e.to_s.upcase == pick_encoding(e.to_s.downcase.gsub("-", "")), e.to_s] }.select {|a,b| !b}
-
# Encoding.list.map { |e| [e.to_s == pick_encoding(e.to_s), e.to_s] }.select {|a,b| !b}
-
1
def Ruby19.pick_encoding(charset)
-
case charset
-
-
# ISO-8859-15, ISO-2022-JP and alike
-
when /iso-?(\d{4})-?(\w{1,2})/i
-
"ISO-#{$1}-#{$2}"
-
-
# "ISO-2022-JP-KDDI" and alike
-
when /iso-?(\d{4})-?(\w{1,2})-?(\w*)/i
-
"ISO-#{$1}-#{$2}-#{$3}"
-
-
# UTF-8, UTF-32BE and alike
-
when /utf-?(\d{1,2})?(\w{1,2})/i
-
"UTF-#{$1}#{$2}".gsub(/\A(UTF-(?:16|32))\z/, '\\1BE')
-
-
# Windows-1252 and alike
-
when /Windows-?(.*)/i
-
"Windows-#{$1}"
-
-
when /^8bit$/
-
Encoding::ASCII_8BIT
-
-
# Microsoft-specific alias for CP949 (Korean)
-
when 'ks_c_5601-1987'
-
Encoding::CP949
-
-
# Wrongly written Shift_JIS (Japanese)
-
when 'shift-jis'
-
Encoding::Shift_JIS
-
-
# GB2312 (Chinese charset) is a subset of GB18030 (its replacement)
-
when /gb2312/i
-
Encoding::GB18030
-
-
else
-
charset
-
end
-
end
-
end
-
end
-
# -*- ruby encoding: utf-8 -*-
-
-
# The namespace for MIME applications, tools, and libraries.
-
1
module MIME
-
# Reflects a MIME Content-Type which is in invalid format (e.g., it isn't
-
# in the form of type/subtype).
-
1
class InvalidContentType < RuntimeError; end
-
-
# The definition of one MIME content-type.
-
#
-
# == Usage
-
# require 'mime/types'
-
#
-
# plaintext = MIME::Types['text/plain'].first
-
# # returns [text/plain, text/plain]
-
# text = plaintext.first
-
# print text.media_type # => 'text'
-
# print text.sub_type # => 'plain'
-
#
-
# puts text.extensions.join(" ") # => 'asc txt c cc h hh cpp'
-
#
-
# puts text.encoding # => 8bit
-
# puts text.binary? # => false
-
# puts text.ascii? # => true
-
# puts text == 'text/plain' # => true
-
# puts MIME::Type.simplified('x-appl/x-zip') # => 'appl/zip'
-
#
-
# puts MIME::Types.any? { |type|
-
# type.content_type == 'text/plain'
-
# } # => true
-
# puts MIME::Types.all?(&:registered?)
-
# # => false
-
#
-
1
class Type
-
# The released version of Ruby MIME::Types
-
1
VERSION = '1.25.1'
-
-
1
include Comparable
-
-
1
MEDIA_TYPE_RE = %r{([-\w.+]+)/([-\w.+]*)}o
-
1
UNREG_RE = %r{[Xx]-}o
-
1
ENCODING_RE = %r{(?:base64|7bit|8bit|quoted\-printable)}o
-
1
PLATFORM_RE = %r|#{RUBY_PLATFORM}|o
-
-
1
SIGNATURES = %w(application/pgp-keys application/pgp
-
application/pgp-signature application/pkcs10
-
application/pkcs7-mime application/pkcs7-signature
-
text/vcard)
-
-
1
IANA_URL = "http://www.iana.org/assignments/media-types/%s/%s"
-
1
RFC_URL = "http://rfc-editor.org/rfc/rfc%s.txt"
-
1
DRAFT_URL = "http://datatracker.ietf.org/public/idindex.cgi?command=id_details&filename=%s"
-
1
LTSW_URL = "http://www.ltsw.se/knbase/internet/%s.htp"
-
1
CONTACT_URL = "http://www.iana.org/assignments/contact-people.htm#%s"
-
-
# Returns +true+ if the simplified type matches the current
-
1
def like?(other)
-
if other.respond_to?(:simplified)
-
@simplified == other.simplified
-
else
-
@simplified == Type.simplified(other)
-
end
-
end
-
-
# Compares the MIME::Type against the exact content type or the
-
# simplified type (the simplified type will be used if comparing against
-
# something that can be treated as a String with #to_s). In comparisons,
-
# this is done against the lowercase version of the MIME::Type.
-
1
def <=>(other)
-
74
if other.respond_to?(:content_type)
-
74
@content_type.downcase <=> other.content_type.downcase
-
elsif other.respond_to?(:to_s)
-
@simplified <=> Type.simplified(other.to_s)
-
else
-
@content_type.downcase <=> other.downcase
-
end
-
end
-
-
# Compares the MIME::Type based on how reliable it is before doing a
-
# normal <=> comparison. Used by MIME::Types#[] to sort types. The
-
# comparisons involved are:
-
#
-
# 1. self.simplified <=> other.simplified (ensures that we
-
# don't try to compare different types)
-
# 2. IANA-registered definitions < other definitions.
-
# 3. Generic definitions < platform definitions.
-
# 3. Complete definitions < incomplete definitions.
-
# 4. Current definitions < obsolete definitions.
-
# 5. Obselete with use-instead references < obsolete without.
-
# 6. Obsolete use-instead definitions are compared.
-
1
def priority_compare(other)
-
pc = simplified <=> other.simplified
-
-
if pc.zero?
-
pc = if registered? != other.registered?
-
registered? ? -1 : 1 # registered < unregistered
-
elsif platform? != other.platform?
-
platform? ? 1 : -1 # generic < platform
-
elsif complete? != other.complete?
-
complete? ? -1 : 1 # complete < incomplete
-
elsif obsolete? != other.obsolete?
-
obsolete? ? 1 : -1 # current < obsolete
-
else
-
0
-
end
-
-
if pc.zero? and obsolete? and (use_instead != other.use_instead)
-
pc = if use_instead.nil?
-
-1
-
elsif other.use_instead.nil?
-
1
-
else
-
use_instead <=> other.use_instead
-
end
-
end
-
end
-
-
pc
-
end
-
-
# Returns +true+ if the other object is a MIME::Type and the content
-
# types match.
-
1
def eql?(other)
-
other.kind_of?(MIME::Type) and self == other
-
end
-
-
# Returns the whole MIME content-type string.
-
#
-
# text/plain => text/plain
-
# x-chemical/x-pdb => x-chemical/x-pdb
-
1
attr_reader :content_type
-
# Returns the media type of the simplified MIME type.
-
#
-
# text/plain => text
-
# x-chemical/x-pdb => chemical
-
1
attr_reader :media_type
-
# Returns the media type of the unmodified MIME type.
-
#
-
# text/plain => text
-
# x-chemical/x-pdb => x-chemical
-
1
attr_reader :raw_media_type
-
# Returns the sub-type of the simplified MIME type.
-
#
-
# text/plain => plain
-
# x-chemical/x-pdb => pdb
-
1
attr_reader :sub_type
-
# Returns the media type of the unmodified MIME type.
-
#
-
# text/plain => plain
-
# x-chemical/x-pdb => x-pdb
-
1
attr_reader :raw_sub_type
-
# The MIME types main- and sub-label can both start with <tt>x-</tt>,
-
# which indicates that it is a non-registered name. Of course, after
-
# registration this flag can disappear, adds to the confusing
-
# proliferation of MIME types. The simplified string has the <tt>x-</tt>
-
# removed and are translated to lowercase.
-
#
-
# text/plain => text/plain
-
# x-chemical/x-pdb => chemical/pdb
-
1
attr_reader :simplified
-
# The list of extensions which are known to be used for this MIME::Type.
-
# Non-array values will be coerced into an array with #to_a. Array
-
# values will be flattened and +nil+ values removed.
-
1
attr_accessor :extensions
-
1
remove_method :extensions= ;
-
1
def extensions=(ext) #:nodoc:
-
3286
@extensions = [ext].flatten.compact
-
end
-
-
# The encoding (7bit, 8bit, quoted-printable, or base64) required to
-
# transport the data of this content type safely across a network, which
-
# roughly corresponds to Content-Transfer-Encoding. A value of +nil+ or
-
# <tt>:default</tt> will reset the #encoding to the #default_encoding
-
# for the MIME::Type. Raises ArgumentError if the encoding provided is
-
# invalid.
-
#
-
# If the encoding is not provided on construction, this will be either
-
# 'quoted-printable' (for text/* media types) and 'base64' for eveything
-
# else.
-
1
attr_accessor :encoding
-
1
remove_method :encoding= ;
-
1
def encoding=(enc) #:nodoc:
-
3286
if enc.nil? or enc == :default
-
3129
@encoding = self.default_encoding
-
157
elsif enc =~ ENCODING_RE
-
157
@encoding = enc
-
else
-
raise ArgumentError, "The encoding must be nil, :default, base64, 7bit, 8bit, or quoted-printable."
-
end
-
end
-
-
# The regexp for the operating system that this MIME::Type is specific
-
# to.
-
1
attr_accessor :system
-
1
remove_method :system= ;
-
1
def system=(os) #:nodoc:
-
3286
if os.nil? or os.kind_of?(Regexp)
-
3282
@system = os
-
else
-
4
@system = %r|#{os}|
-
end
-
end
-
# Returns the default encoding for the MIME::Type based on the media
-
# type.
-
1
attr_reader :default_encoding
-
1
remove_method :default_encoding
-
1
def default_encoding
-
3129
(@media_type == 'text') ? 'quoted-printable' : 'base64'
-
end
-
-
# Returns the media type or types that should be used instead of this
-
# media type, if it is obsolete. If there is no replacement media type,
-
# or it is not obsolete, +nil+ will be returned.
-
1
attr_reader :use_instead
-
1
remove_method :use_instead
-
1
def use_instead
-
return nil unless @obsolete
-
@use_instead
-
end
-
-
# Returns +true+ if the media type is obsolete.
-
1
def obsolete?
-
@obsolete ? true : false
-
end
-
# Sets the obsolescence indicator for this media type.
-
1
attr_writer :obsolete
-
-
# The documentation for this MIME::Type. Documentation about media
-
# types will be found on a media type definition as a comment.
-
# Documentation will be found through #docs.
-
1
attr_accessor :docs
-
1
remove_method :docs= ;
-
1
def docs=(d)
-
3286
if d
-
45
a = d.scan(%r{use-instead:#{MEDIA_TYPE_RE}})
-
-
45
if a.empty?
-
2
@use_instead = nil
-
else
-
86
@use_instead = a.map { |el| "#{el[0]}/#{el[1]}" }
-
end
-
end
-
3286
@docs = d
-
end
-
-
# The encoded URL list for this MIME::Type. See #urls for more
-
# information.
-
1
attr_accessor :url
-
# The decoded URL list for this MIME::Type.
-
# The special URL value IANA will be translated into:
-
# http://www.iana.org/assignments/media-types/<mediatype>/<subtype>
-
#
-
# The special URL value RFC### will be translated into:
-
# http://www.rfc-editor.org/rfc/rfc###.txt
-
#
-
# The special URL value DRAFT:name will be translated into:
-
# https://datatracker.ietf.org/public/idindex.cgi?
-
# command=id_detail&filename=<name>
-
#
-
# The special URL value LTSW will be translated into:
-
# http://www.ltsw.se/knbase/internet/<mediatype>.htp
-
#
-
# The special URL value [token] will be translated into:
-
# http://www.iana.org/assignments/contact-people.htm#<token>
-
#
-
# These values will be accessible through #urls, which always returns an
-
# array.
-
1
def urls
-
@url.map do |el|
-
case el
-
when %r{^IANA$}
-
IANA_URL % [ @media_type, @sub_type ]
-
when %r{^RFC(\d+)$}
-
RFC_URL % $1
-
when %r{^DRAFT:(.+)$}
-
DRAFT_URL % $1
-
when %r{^LTSW$}
-
LTSW_URL % @media_type
-
when %r{^\{([^=]+)=([^\}]+)\}}
-
[$1, $2]
-
when %r{^\[([^=]+)=([^\]]+)\]}
-
[$1, CONTACT_URL % $2]
-
when %r{^\[([^\]]+)\]}
-
CONTACT_URL % $1
-
else
-
el
-
end
-
end
-
end
-
-
1
class << self
-
# The MIME types main- and sub-label can both start with <tt>x-</tt>,
-
# which indicates that it is a non-registered name. Of course, after
-
# registration this flag can disappear, adds to the confusing
-
# proliferation of MIME types. The simplified string has the
-
# <tt>x-</tt> removed and are translated to lowercase.
-
1
def simplified(content_type)
-
1643
matchdata = MEDIA_TYPE_RE.match(content_type)
-
-
1643
if matchdata.nil?
-
simplified = nil
-
else
-
1643
media_type = matchdata.captures[0].downcase.gsub(UNREG_RE, '')
-
1643
subtype = matchdata.captures[1].downcase.gsub(UNREG_RE, '')
-
1643
simplified = "#{media_type}/#{subtype}"
-
end
-
1643
simplified
-
end
-
-
# Creates a MIME::Type from an array in the form of:
-
# [type-name, [extensions], encoding, system]
-
#
-
# +extensions+, +encoding+, and +system+ are optional.
-
#
-
# MIME::Type.from_array("application/x-ruby", ['rb'], '8bit')
-
# MIME::Type.from_array(["application/x-ruby", ['rb'], '8bit'])
-
#
-
# These are equivalent to:
-
#
-
# MIME::Type.new('application/x-ruby') do |t|
-
# t.extensions = %w(rb)
-
# t.encoding = '8bit'
-
# end
-
1
def from_array(*args) #:yields MIME::Type.new:
-
# Dereferences the array one level, if necessary.
-
args = args.first if args.first.kind_of? Array
-
-
unless args.size.between?(1, 8)
-
raise ArgumentError, "Array provided must contain between one and eight elements."
-
end
-
-
MIME::Type.new(args.shift) do |t|
-
t.extensions, t.encoding, t.system, t.obsolete, t.docs, t.url,
-
t.registered = *args
-
yield t if block_given?
-
end
-
end
-
-
# Creates a MIME::Type from a hash. Keys are case-insensitive,
-
# dashes may be replaced with underscores, and the internal Symbol
-
# of the lowercase-underscore version can be used as well. That is,
-
# Content-Type can be provided as content-type, Content_Type,
-
# content_type, or :content_type.
-
#
-
# Known keys are <tt>Content-Type</tt>,
-
# <tt>Content-Transfer-Encoding</tt>, <tt>Extensions</tt>, and
-
# <tt>System</tt>.
-
#
-
# MIME::Type.from_hash('Content-Type' => 'text/x-yaml',
-
# 'Content-Transfer-Encoding' => '8bit',
-
# 'System' => 'linux',
-
# 'Extensions' => ['yaml', 'yml'])
-
#
-
# This is equivalent to:
-
#
-
# MIME::Type.new('text/x-yaml') do |t|
-
# t.encoding = '8bit'
-
# t.system = 'linux'
-
# t.extensions = ['yaml', 'yml']
-
# end
-
1
def from_hash(hash) #:yields MIME::Type.new:
-
type = {}
-
hash.each_pair do |k, v|
-
type[k.to_s.tr('A-Z', 'a-z').gsub(/-/, '_').to_sym] = v
-
end
-
-
MIME::Type.new(type[:content_type]) do |t|
-
t.extensions = type[:extensions]
-
t.encoding = type[:content_transfer_encoding]
-
t.system = type[:system]
-
t.obsolete = type[:obsolete]
-
t.docs = type[:docs]
-
t.url = type[:url]
-
t.registered = type[:registered]
-
-
yield t if block_given?
-
end
-
end
-
-
# Essentially a copy constructor.
-
#
-
# MIME::Type.from_mime_type(plaintext)
-
#
-
# is equivalent to:
-
#
-
# MIME::Type.new(plaintext.content_type.dup) do |t|
-
# t.extensions = plaintext.extensions.dup
-
# t.system = plaintext.system.dup
-
# t.encoding = plaintext.encoding.dup
-
# end
-
1
def from_mime_type(mime_type) #:yields the new MIME::Type:
-
MIME::Type.new(mime_type.content_type.dup) do |t|
-
t.extensions = mime_type.extensions.map { |e| e.dup }
-
t.url = mime_type.url && mime_type.url.map { |e| e.dup }
-
-
mime_type.system && t.system = mime_type.system.dup
-
mime_type.encoding && t.encoding = mime_type.encoding.dup
-
-
t.obsolete = mime_type.obsolete?
-
t.registered = mime_type.registered?
-
-
mime_type.docs && t.docs = mime_type.docs.dup
-
-
yield t if block_given?
-
end
-
end
-
end
-
-
# Builds a MIME::Type object from the provided MIME Content Type value
-
# (e.g., 'text/plain' or 'applicaton/x-eruby'). The constructed object
-
# is yielded to an optional block for additional configuration, such as
-
# associating extensions and encoding information.
-
1
def initialize(content_type) #:yields self:
-
1643
matchdata = MEDIA_TYPE_RE.match(content_type)
-
-
1643
if matchdata.nil?
-
raise InvalidContentType, "Invalid Content-Type provided ('#{content_type}')"
-
end
-
-
1643
@content_type = content_type
-
1643
@raw_media_type = matchdata.captures[0]
-
1643
@raw_sub_type = matchdata.captures[1]
-
-
1643
@simplified = MIME::Type.simplified(@content_type)
-
1643
matchdata = MEDIA_TYPE_RE.match(@simplified)
-
1643
@media_type = matchdata.captures[0]
-
1643
@sub_type = matchdata.captures[1]
-
-
1643
self.extensions = nil
-
1643
self.encoding = :default
-
1643
self.system = nil
-
1643
self.registered = true
-
1643
self.url = nil
-
1643
self.obsolete = nil
-
1643
self.docs = nil
-
-
1643
yield self if block_given?
-
end
-
-
# MIME content-types which are not regestered by IANA nor defined in
-
# RFCs are required to start with <tt>x-</tt>. This counts as well for
-
# a new media type as well as a new sub-type of an existing media
-
# type. If either the media-type or the content-type begins with
-
# <tt>x-</tt>, this method will return +false+.
-
1
def registered?
-
if (@raw_media_type =~ UNREG_RE) || (@raw_sub_type =~ UNREG_RE)
-
false
-
else
-
@registered
-
end
-
end
-
1
attr_writer :registered #:nodoc:
-
-
# MIME types can be specified to be sent across a network in particular
-
# formats. This method returns +true+ when the MIME type encoding is set
-
# to <tt>base64</tt>.
-
1
def binary?
-
@encoding == 'base64'
-
end
-
-
# MIME types can be specified to be sent across a network in particular
-
# formats. This method returns +false+ when the MIME type encoding is
-
# set to <tt>base64</tt>.
-
1
def ascii?
-
not binary?
-
end
-
-
# Returns +true+ when the simplified MIME type is in the list of known
-
# digital signatures.
-
1
def signature?
-
SIGNATURES.include?(@simplified.downcase)
-
end
-
-
# Returns +true+ if the MIME::Type is specific to an operating system.
-
1
def system?
-
not @system.nil?
-
end
-
-
# Returns +true+ if the MIME::Type is specific to the current operating
-
# system as represented by RUBY_PLATFORM.
-
1
def platform?
-
system? and (RUBY_PLATFORM =~ @system)
-
end
-
-
# Returns +true+ if the MIME::Type specifies an extension list,
-
# indicating that it is a complete MIME::Type.
-
1
def complete?
-
not @extensions.empty?
-
end
-
-
# Returns the MIME type as a string.
-
1
def to_s
-
@content_type
-
end
-
-
# Returns the MIME type as a string for implicit conversions.
-
1
def to_str
-
@content_type
-
end
-
-
# Returns the MIME type as an array suitable for use with
-
# MIME::Type.from_array.
-
1
def to_a
-
[ @content_type, @extensions, @encoding, @system, @obsolete, @docs,
-
@url, registered? ]
-
end
-
-
# Returns the MIME type as an array suitable for use with
-
# MIME::Type.from_hash.
-
1
def to_hash
-
{ 'Content-Type' => @content_type,
-
'Content-Transfer-Encoding' => @encoding,
-
'Extensions' => @extensions,
-
'System' => @system,
-
'Obsolete' => @obsolete,
-
'Docs' => @docs,
-
'URL' => @url,
-
'Registered' => registered?,
-
}
-
end
-
end
-
-
# = MIME::Types
-
# MIME types are used in MIME-compliant communications, as in e-mail or
-
# HTTP traffic, to indicate the type of content which is transmitted.
-
# MIME::Types provides the ability for detailed information about MIME
-
# entities (provided as a set of MIME::Type objects) to be determined and
-
# used programmatically. There are many types defined by RFCs and vendors,
-
# so the list is long but not complete; don't hesitate to ask to add
-
# additional information. This library follows the IANA collection of MIME
-
# types (see below for reference).
-
#
-
# == Description
-
# MIME types are used in MIME entities, as in email or HTTP traffic. It is
-
# useful at times to have information available about MIME types (or,
-
# inversely, about files). A MIME::Type stores the known information about
-
# one MIME type.
-
#
-
# == Usage
-
# require 'mime/types'
-
#
-
# plaintext = MIME::Types['text/plain']
-
# print plaintext.media_type # => 'text'
-
# print plaintext.sub_type # => 'plain'
-
#
-
# puts plaintext.extensions.join(" ") # => 'asc txt c cc h hh cpp'
-
#
-
# puts plaintext.encoding # => 8bit
-
# puts plaintext.binary? # => false
-
# puts plaintext.ascii? # => true
-
# puts plaintext.obsolete? # => false
-
# puts plaintext.registered? # => true
-
# puts plaintext == 'text/plain' # => true
-
# puts MIME::Type.simplified('x-appl/x-zip') # => 'appl/zip'
-
#
-
# This module is built to conform to the MIME types of RFCs 2045 and 2231.
-
# It follows the official IANA registry at
-
# http://www.iana.org/assignments/media-types/ and
-
# ftp://ftp.iana.org/assignments/media-types with some unofficial types
-
# added from the the collection at
-
# http://www.ltsw.se/knbase/internet/mime.htp
-
1
class Types
-
# The released version of Ruby MIME::Types
-
1
VERSION = MIME::Type::VERSION
-
1
DATA_VERSION = (VERSION.to_f * 100).to_i
-
-
# The data version.
-
1
attr_reader :data_version
-
-
1
class HashWithArrayDefault < Hash # :nodoc:
-
1
def initialize
-
4410
super { |h, k| h[k] = [] }
-
end
-
-
1
def marshal_dump
-
{}.merge(self)
-
end
-
-
1
def marshal_load(hash)
-
self.merge!(hash)
-
end
-
end
-
-
1
class CacheContainer # :nodoc:
-
1
attr_reader :version, :data
-
1
def initialize(version, data)
-
@version, @data = version, data
-
end
-
end
-
-
1
def initialize(data_version = DATA_VERSION)
-
25
@type_variants = HashWithArrayDefault.new
-
25
@extension_index = HashWithArrayDefault.new
-
25
@data_version = data_version
-
end
-
-
1
def add_type_variant(mime_type) #:nodoc:
-
3286
@type_variants[mime_type.simplified] << mime_type
-
end
-
-
1
def index_extensions(mime_type) #:nodoc:
-
4558
mime_type.extensions.each { |ext| @extension_index[ext] << mime_type }
-
end
-
-
1
def defined_types #:nodoc:
-
24
@type_variants.values.flatten
-
end
-
-
# Returns the number of known types. A shortcut of MIME::Types[//].size.
-
# (Keep in mind that this is memory intensive, cache the result to spare
-
# resources)
-
1
def count
-
defined_types.size
-
end
-
-
1
def each
-
defined_types.each { |t| yield t }
-
end
-
-
1
@__types__ = nil
-
-
# Returns a list of MIME::Type objects, which may be empty. The optional
-
# flag parameters are :complete (finds only complete MIME::Type objects)
-
# and :platform (finds only MIME::Types for the current platform). It is
-
# possible for multiple matches to be returned for either type (in the
-
# example below, 'text/plain' returns two values -- one for the general
-
# case, and one for VMS systems.
-
#
-
# puts "\nMIME::Types['text/plain']"
-
# MIME::Types['text/plain'].each { |t| puts t.to_a.join(", ") }
-
#
-
# puts "\nMIME::Types[/^image/, :complete => true]"
-
# MIME::Types[/^image/, :complete => true].each do |t|
-
# puts t.to_a.join(", ")
-
# end
-
#
-
# If multiple type definitions are returned, returns them sorted as
-
# follows:
-
# 1. Complete definitions sort before incomplete ones;
-
# 2. IANA-registered definitions sort before LTSW-recorded
-
# definitions.
-
# 3. Generic definitions sort before platform-specific ones;
-
# 4. Current definitions sort before obsolete ones;
-
# 5. Obsolete definitions with use-instead clauses sort before those
-
# without;
-
# 6. Obsolete definitions use-instead clauses are compared.
-
# 7. Sort on name.
-
1
def [](type_id, flags = {})
-
matches = case type_id
-
when MIME::Type
-
@type_variants[type_id.simplified]
-
when Regexp
-
match(type_id)
-
else
-
@type_variants[MIME::Type.simplified(type_id)]
-
end
-
-
prune_matches(matches, flags).sort { |a, b| a.priority_compare(b) }
-
end
-
-
# Return the list of MIME::Types which belongs to the file based on its
-
# filename extension. If +platform+ is +true+, then only file types that
-
# are specific to the current platform will be returned.
-
#
-
# This will always return an array.
-
#
-
# puts "MIME::Types.type_for('citydesk.xml')
-
# => [application/xml, text/xml]
-
# puts "MIME::Types.type_for('citydesk.gif')
-
# => [image/gif]
-
1
def type_for(filename, platform = false)
-
ext = filename.chomp.downcase.gsub(/.*\./o, '')
-
list = @extension_index[ext]
-
list.delete_if { |e| not e.platform? } if platform
-
list
-
end
-
-
# A synonym for MIME::Types.type_for
-
1
def of(filename, platform = false)
-
type_for(filename, platform)
-
end
-
-
# Add one or more MIME::Type objects to the set of known types. Each
-
# type should be experimental (e.g., 'application/x-ruby'). If the type
-
# is already known, a warning will be displayed.
-
#
-
# <strong>Please inform the maintainer of this module when registered
-
# types are missing.</strong>
-
1
def add(*types)
-
1691
types.each do |mime_type|
-
3310
if mime_type.kind_of? MIME::Types
-
24
add(*mime_type.defined_types)
-
else
-
3286
if @type_variants.include?(mime_type.simplified)
-
73
if @type_variants[mime_type.simplified].include?(mime_type)
-
6
warn "Type #{mime_type} already registered as a variant of #{mime_type.simplified}." unless defined? MIME::Types::LOAD
-
end
-
end
-
3286
add_type_variant(mime_type)
-
3286
index_extensions(mime_type)
-
end
-
end
-
end
-
-
1
private
-
1
def prune_matches(matches, flags)
-
matches.delete_if { |e| not e.complete? } if flags[:complete]
-
matches.delete_if { |e| not e.platform? } if flags[:platform]
-
matches
-
end
-
-
1
def match(pattern)
-
matches = @type_variants.select { |k, v| k =~ pattern }
-
if matches.respond_to? :values
-
matches.values.flatten
-
else
-
matches.map { |m| m.last }.flatten
-
end
-
end
-
-
1
class << self
-
1
def add_type_variant(mime_type) #:nodoc:
-
__types__.add_type_variant(mime_type)
-
end
-
-
1
def index_extensions(mime_type) #:nodoc:
-
__types__.index_extensions(mime_type)
-
end
-
-
# The regular expression used to match a file-based MIME type
-
# definition.
-
1
TEXT_FORMAT_RE = %r{
-
\A
-
\s*
-
([*])? # 0: Unregistered?
-
(!)? # 1: Obsolete?
-
(?:(\w+):)? # 2: Platform marker
-
#{MIME::Type::MEDIA_TYPE_RE}? # 3,4: Media type
-
(?:\s+@([^\s]+))? # 5: Extensions
-
(?:\s+:(#{MIME::Type::ENCODING_RE}))? # 6: Encoding
-
(?:\s+'(.+))? # 7: URL list
-
(?:\s+=(.+))? # 8: Documentation
-
(?:\s*([#].*)?)?
-
\s*
-
\z
-
}x
-
-
# Build the type list from a file in the format:
-
#
-
# [*][!][os:]mt/st[<ws>@ext][<ws>:enc][<ws>'url-list][<ws>=docs]
-
#
-
# == *
-
# An unofficial MIME type. This should be used if and only if the MIME type
-
# is not properly specified (that is, not under either x-type or
-
# vnd.name.type).
-
#
-
# == !
-
# An obsolete MIME type. May be used with an unofficial MIME type.
-
#
-
# == os:
-
# Platform-specific MIME type definition.
-
#
-
# == mt
-
# The media type.
-
#
-
# == st
-
# The media subtype.
-
#
-
# == <ws>@ext
-
# The list of comma-separated extensions.
-
#
-
# == <ws>:enc
-
# The encoding.
-
#
-
# == <ws>'url-list
-
# The list of comma-separated URLs.
-
#
-
# == <ws>=docs
-
# The documentation string.
-
#
-
# That is, everything except the media type and the subtype is optional. The
-
# more information that's available, though, the richer the values that can
-
# be provided.
-
1
def load_from_file(filename) #:nodoc:
-
24
if defined? ::Encoding
-
48
data = File.open(filename, 'r:UTF-8:-') { |f| f.read }
-
else
-
data = File.open(filename) { |f| f.read }
-
end
-
24
data = data.split($/)
-
24
mime = MIME::Types.new
-
24
data.each_with_index { |line, index|
-
1643
item = line.chomp.strip
-
1643
next if item.empty?
-
-
1643
begin
-
1643
m = TEXT_FORMAT_RE.match(item).captures
-
rescue Exception
-
puts "#{filename}:#{index}: Parsing error in MIME type definitions."
-
puts "=> #{line}"
-
raise
-
end
-
-
unregistered, obsolete, platform, mediatype, subtype, extensions,
-
1643
encoding, urls, docs, comment = *m
-
-
1643
if mediatype.nil?
-
if comment.nil?
-
puts "#{filename}:#{index}: Parsing error in MIME type definitions."
-
puts "=> #{line}"
-
raise RuntimeError
-
end
-
-
next
-
end
-
-
1643
extensions &&= extensions.split(/,/)
-
1643
urls &&= urls.split(/,/)
-
-
1643
mime_type = MIME::Type.new("#{mediatype}/#{subtype}") do |t|
-
1643
t.extensions = extensions
-
1643
t.encoding = encoding
-
1643
t.system = platform
-
1643
t.obsolete = obsolete
-
1643
t.registered = false if unregistered
-
1643
t.docs = docs
-
1643
t.url = urls
-
end
-
-
1643
mime.add(mime_type)
-
}
-
24
mime
-
end
-
-
# Returns a list of MIME::Type objects, which may be empty. The
-
# optional flag parameters are :complete (finds only complete
-
# MIME::Type objects) and :platform (finds only MIME::Types for the
-
# current platform). It is possible for multiple matches to be
-
# returned for either type (in the example below, 'text/plain' returns
-
# two values -- one for the general case, and one for VMS systems.
-
#
-
# puts "\nMIME::Types['text/plain']"
-
# MIME::Types['text/plain'].each { |t| puts t.to_a.join(", ") }
-
#
-
# puts "\nMIME::Types[/^image/, :complete => true]"
-
# MIME::Types[/^image/, :complete => true].each do |t|
-
# puts t.to_a.join(", ")
-
# end
-
1
def [](type_id, flags = {})
-
__types__[type_id, flags]
-
end
-
-
1
include Enumerable
-
-
1
def count
-
__types__.count
-
end
-
-
1
def each
-
__types__.each {|t| yield t }
-
end
-
-
# Return the list of MIME::Types which belongs to the file based on
-
# its filename extension. If +platform+ is +true+, then only file
-
# types that are specific to the current platform will be returned.
-
#
-
# This will always return an array.
-
#
-
# puts "MIME::Types.type_for('citydesk.xml')
-
# => [application/xml, text/xml]
-
# puts "MIME::Types.type_for('citydesk.gif')
-
# => [image/gif]
-
1
def type_for(filename, platform = false)
-
__types__.type_for(filename, platform)
-
end
-
-
# A synonym for MIME::Types.type_for
-
1
def of(filename, platform = false)
-
__types__.type_for(filename, platform)
-
end
-
-
# Add one or more MIME::Type objects to the set of known types. Each
-
# type should be experimental (e.g., 'application/x-ruby'). If the
-
# type is already known, a warning will be displayed.
-
#
-
# <strong>Please inform the maintainer of this module when registered
-
# types are missing.</strong>
-
1
def add(*types)
-
24
__types__.add(*types)
-
end
-
-
# Returns the currently defined cache file, if any.
-
1
def cache_file
-
2
ENV['RUBY_MIME_TYPES_CACHE']
-
end
-
-
1
private
-
1
def load_mime_types_from_cache
-
1
load_mime_types_from_cache! if cache_file
-
end
-
-
1
def load_mime_types_from_cache!
-
raise ArgumentError, "No RUBY_MIME_TYPES_CACHE set." unless cache_file
-
return false unless File.exists? cache_file
-
-
begin
-
data = File.read(cache_file)
-
container = Marshal.load(data)
-
-
if container.version == VERSION
-
@__types__ = Marshal.load(container.data)
-
true
-
else
-
false
-
end
-
rescue => e
-
warn "Could not load MIME::Types cache: #{e}"
-
false
-
end
-
end
-
-
1
def write_mime_types_to_cache
-
1
write_mime_types_to_cache! if cache_file
-
end
-
-
1
def write_mime_types_to_cache!
-
raise ArgumentError, "No RUBY_MIME_TYPES_CACHE set." unless cache_file
-
-
File.open(cache_file, 'w') do |f|
-
cache = MIME::Types::CacheContainer.new(VERSION,
-
Marshal.dump(__types__))
-
f.write Marshal.dump(cache)
-
end
-
-
true
-
end
-
-
1
def load_and_parse_mime_types
-
1
const_set(:LOAD, true) unless $DEBUG
-
1
Dir[File.join(File.dirname(__FILE__), 'types', '*')].sort.each { |f|
-
24
add(load_from_file(f))
-
}
-
1
remove_const :LOAD if defined? LOAD
-
end
-
-
1
def lazy_load?
-
1
(lazy = ENV['RUBY_MIME_TYPES_LAZY_LOAD']) && (lazy != 'false')
-
end
-
-
1
def __types__
-
24
load_mime_types unless @__types__
-
24
@__types__
-
end
-
-
1
def load_mime_types
-
1
@__types__ = new(VERSION)
-
1
unless load_mime_types_from_cache
-
1
load_and_parse_mime_types
-
1
write_mime_types_to_cache
-
end
-
end
-
end
-
-
1
load_mime_types unless lazy_load?
-
end
-
end
-
-
# vim: ft=ruby
-
1
require 'mini_magick/command_builder'
-
1
require 'mini_magick/errors'
-
1
require 'mini_magick/image'
-
1
require 'mini_magick/utilities'
-
-
1
module MiniMagick
-
1
@validate_on_create = true
-
1
@validate_on_write = true
-
-
1
class << self
-
1
attr_accessor :processor
-
1
attr_accessor :processor_path
-
1
attr_accessor :timeout
-
1
attr_accessor :debug
-
1
attr_accessor :validate_on_create
-
1
attr_accessor :validate_on_write
-
-
##
-
# Tries to detect the current processor based if any of the processors
-
# exist. Mogrify have precedence over gm by default.
-
#
-
# === Returns
-
# * [Symbol] The detected procesor
-
1
def processor
-
@processor ||= [:mogrify, :gm].detect do |processor|
-
MiniMagick::Utilities.which(processor.to_s)
-
end
-
end
-
-
##
-
# Discovers the imagemagick version based on mogrify's output.
-
#
-
# === Returns
-
# * The imagemagick version
-
1
def image_magick_version
-
@@version ||= Gem::Version.create(`mogrify --version`.split(' ')[2].split('-').first)
-
end
-
-
##
-
# The minimum allowed imagemagick version
-
#
-
# === Returns
-
# * The minimum imagemagick version
-
1
def minimum_image_magick_version
-
@@minimum_version ||= Gem::Version.create('6.6.3')
-
end
-
-
##
-
# Checks whether the imagemagick's version is valid
-
#
-
# === Returns
-
# * [Boolean]
-
1
def valid_version_installed?
-
image_magick_version >= minimum_image_magick_version
-
end
-
-
##
-
# Checks whether the current processory is mogrify.
-
#
-
# === Returns
-
# * [Boolean]
-
1
def mogrify?
-
processor && processor.to_sym == :mogrify
-
end
-
-
##
-
# Checks whether the current processor is graphicsmagick.
-
#
-
# === Returns
-
# * [Boolean]
-
1
def gm?
-
processor && processor.to_sym == :gm
-
end
-
end
-
end
-
1
module MiniMagick
-
1
class CommandBuilder
-
1
MOGRIFY_COMMANDS = %w(adaptive-blur adaptive-resize adaptive-sharpen adjoin affine alpha annotate antialias append attenuate authenticate auto-gamma auto-level auto-orient backdrop background bench bias black-point-compensation black-threshold blend blue-primary blue-shift blur border bordercolor borderwidth brightness-contrast cache caption cdl channel charcoal chop clamp clip clip-mask clip-path clone clut coalesce colorize colormap color-matrix colors colorspace combine comment compose composite compress contrast contrast-stretch convolve crop cycle debug decipher deconstruct define delay delete density depth descend deskew despeckle direction displace display dispose dissimilarity-threshold dissolve distort dither draw duplicate edge emboss encipher encoding endian enhance equalize evaluate evaluate-sequence extent extract family features fft fill filter flatten flip floodfill flop font foreground format frame function fuzz fx gamma gaussian-blur geometry gravity green-primary hald-clut help highlight-color iconGeometry iconic identify ift immutable implode insert intent interlace interpolate interline-spacing interword-spacing kerning label lat layers level level-colors limit linear-stretch linewidth liquid-rescale list log loop lowlight-color magnify map mask mattecolor median metric mode modulate monitor monochrome morph morphology mosaic motion-blur name negate noise normalize opaque ordered-dither orient page paint path pause pen perceptible ping pointsize polaroid poly posterize precision preview print process profile quality quantize quiet radial-blur raise random-threshold red-primary regard-warnings region remap remote render repage resample resize respect-parentheses reverse roll rotate sample sampling-factor scale scene screen seed segment selective-blur separate sepia-tone set shade shadow shared-memory sharpen shave shear sigmoidal-contrast silent size sketch smush snaps solarize sparse-color splice spread statistic stegano stereo stretch strip stroke strokewidth style subimage-search swap swirl synchronize taint text-font texture threshold thumbnail tile tile-offset tint title transform transparent transparent-color transpose transverse treedepth trim type undercolor unique-colors units unsharp update verbose version view vignette virtual-pixel visual watermark wave weight white-point white-threshold window window-group write)
-
1
IMAGE_CREATION_OPERATORS = %w(canvas caption gradient label logo pattern plasma radial radient rose text tile xc)
-
-
1
def initialize(tool, *options)
-
@tool = tool
-
@args = []
-
options.each { |arg| push(arg) }
-
end
-
-
1
def command
-
com = "#{@tool} #{args.join(' ')}".strip
-
com = "#{MiniMagick.processor} #{com}" unless MiniMagick.mogrify?
-
-
com = File.join MiniMagick.processor_path, com if MiniMagick.processor_path
-
com.strip
-
end
-
-
1
def args
-
@args.map { |arg| Utilities.escape(arg) }
-
end
-
-
# Add each mogrify command in both underscore and dash format
-
1
MOGRIFY_COMMANDS.each do |mogrify_command|
-
-
# Example of what is generated here:
-
#
-
# def auto_orient(*options)
-
# add_command("auto-orient", *options)
-
# self
-
# end
-
# alias_method :"auto-orient", :auto_orient
-
-
269
dashed_command = mogrify_command.to_s.gsub('_', '-')
-
269
underscored_command = mogrify_command.to_s.gsub('-', '_')
-
-
269
define_method(underscored_command) do |*options|
-
options[1] = Utilities.windows_escape(options[1]) if mogrify_command == 'annotate'
-
add_command(__method__.to_s.gsub('_', '-'), *options)
-
self
-
end
-
-
269
alias_method dashed_command, underscored_command
-
269
alias_method "mogrify_#{underscored_command}", underscored_command
-
end
-
-
1
def format(*options)
-
fail Error, "You must call 'format' on the image object directly!"
-
end
-
-
1
IMAGE_CREATION_OPERATORS.each do |operator|
-
13
define_method operator do |*options|
-
add_creation_operator(__method__.to_s, *options)
-
self
-
end
-
-
13
alias_method "operator_#{operator}", operator
-
end
-
-
1
(MOGRIFY_COMMANDS & IMAGE_CREATION_OPERATORS).each do |command_or_operator|
-
3
define_method command_or_operator do |*options|
-
if @tool == 'mogrify'
-
method = self.method("mogrify_#{command_or_operator}")
-
else
-
method = self.method("operator_#{command_or_operator}")
-
end
-
method.call(*options)
-
end
-
-
end
-
-
1
def +(*options)
-
push(@args.pop.gsub(/\A-/, '+'))
-
options.to_a.each { |option| push(option) }
-
end
-
-
1
def add_command(command, *options)
-
push "-#{command}"
-
options.to_a.each { |option| push(option) }
-
end
-
-
1
def add_creation_operator(command, *options)
-
creation_command = command
-
options.to_a.each { |option| creation_command << ":#{option}" }
-
push creation_command
-
end
-
-
1
def push(arg)
-
@args << arg.to_s.strip
-
end
-
1
alias_method :<<, :push
-
end
-
end
-
1
module MiniMagick
-
1
class Error < RuntimeError; end
-
1
class Invalid < StandardError; end
-
end
-
1
require 'tempfile'
-
1
require 'subexec'
-
1
require 'stringio'
-
1
require 'pathname'
-
-
1
module MiniMagick
-
1
class Image
-
# @return [String] The location of the current working file
-
1
attr_writer :path
-
-
1
def path
-
run_queue if @command_queued
-
MiniMagick::Utilities.path(@path)
-
end
-
-
# Class Methods
-
# -------------
-
1
class << self
-
# This is the primary loading method used by all of the other class
-
# methods.
-
#
-
# Use this to pass in a stream object. Must respond to Object#read(size)
-
# or be a binary string object (BLOBBBB)
-
#
-
# As a change from the old API, please try and use IOStream objects. They
-
# are much, much better and more efficient!
-
#
-
# Probably easier to use the #open method if you want to open a file or a
-
# URL.
-
#
-
# @param stream [IOStream, String] Some kind of stream object that needs
-
# to be read or is a binary String blob!
-
# @param ext [String] A manual extension to use for reading the file. Not
-
# required, but if you are having issues, give this a try.
-
# @return [Image]
-
1
def read(stream, ext = nil)
-
if stream.is_a?(String)
-
stream = StringIO.new(stream)
-
elsif stream.is_a?(StringIO)
-
# Do nothing, we want a StringIO-object
-
elsif stream.respond_to? :path
-
if File.respond_to?(:binread)
-
stream = StringIO.new File.binread(stream.path.to_s)
-
else
-
stream = StringIO.new File.open(stream.path.to_s, 'rb') { |f| f.read }
-
end
-
end
-
-
create(ext) do |f|
-
while chunk = stream.read(8192)
-
f.write(chunk)
-
end
-
end
-
end
-
-
# @deprecated Please use Image.read instead!
-
1
def from_blob(blob, ext = nil)
-
warn 'Warning: MiniMagick::Image.from_blob method is deprecated. Instead, please use Image.read'
-
create(ext) { |f| f.write(blob) }
-
end
-
-
# Creates an image object from a binary string blob which contains raw
-
# pixel data (i.e. no header data).
-
#
-
# @param blob [String] Binary string blob containing raw pixel data.
-
# @param columns [Integer] Number of columns.
-
# @param rows [Integer] Number of rows.
-
# @param depth [Integer] Bit depth of the encoded pixel data.
-
# @param map [String] A code for the mapping of the pixel data. Example:
-
# 'gray' or 'rgb'.
-
# @param format [String] The file extension of the image format to be
-
# used when creating the image object.
-
# Defaults to 'png'.
-
# @return [Image] The loaded image.
-
#
-
1
def import_pixels(blob, columns, rows, depth, map, format = 'png')
-
# Create an image object with the raw pixel data string:
-
image = create('.dat', false) { |f| f.write(blob) }
-
# Use ImageMagick to convert the raw data file to an image file of the
-
# desired format:
-
converted_image_path = image.path[0..-4] + format
-
arguments = ['-size', "#{columns}x#{rows}", '-depth', "#{depth}", "#{map}:#{image.path}", "#{converted_image_path}"]
-
# Example: convert -size 256x256 -depth 16 gray:blob.dat blob.png
-
cmd = CommandBuilder.new('convert', *arguments)
-
image.run(cmd)
-
# Update the image instance with the path of the properly formatted
-
# image, and return:
-
image.path = converted_image_path
-
image
-
end
-
-
# Opens a specific image file either on the local file system or at a URI.
-
#
-
# Use this if you don't want to overwrite the image file.
-
#
-
# Extension is either guessed from the path or you can specify it as a
-
# second parameter.
-
#
-
# If you pass in what looks like a URL, we require 'open-uri' before
-
# opening it.
-
#
-
# @param file_or_url [String] Either a local file path or a URL that
-
# open-uri can read
-
# @param ext [String] Specify the extension you want to read it as
-
# @return [Image] The loaded image
-
1
def open(file_or_url, ext = nil)
-
file_or_url = file_or_url.to_s # Force String... Hell or high water
-
if file_or_url.include?('://')
-
require 'open-uri'
-
ext ||= File.extname(URI.parse(file_or_url).path)
-
Kernel.open(file_or_url) do |f|
-
read(f, ext)
-
end
-
else
-
ext ||= File.extname(file_or_url)
-
File.open(file_or_url, 'rb') do |f|
-
read(f, ext)
-
end
-
end
-
end
-
-
# @deprecated Please use MiniMagick::Image.open(file_or_url) now
-
1
def from_file(file, ext = nil)
-
warn 'Warning: MiniMagick::Image.from_file is now deprecated. Please use Image.open'
-
open(file, ext)
-
end
-
-
# Used to create a new Image object data-copy. Not used to "paint" or
-
# that kind of thing.
-
#
-
# Takes an extension in a block and can be used to build a new Image
-
# object. Used by both #open and #read to create a new object! Ensures we
-
# have a good tempfile!
-
#
-
# @param ext [String] Specify the extension you want to read it as
-
# @param validate [Boolean] If false, skips validation of the created
-
# image. Defaults to true.
-
# @yield [IOStream] You can #write bits to this object to create the new
-
# Image
-
# @return [Image] The created image
-
1
def create(ext = nil, validate = MiniMagick.validate_on_create, &block)
-
tempfile = Tempfile.new(['mini_magick', ext.to_s.downcase])
-
tempfile.binmode
-
block.call(tempfile)
-
tempfile.close
-
-
image = new(tempfile.path, tempfile)
-
-
fail MiniMagick::Invalid if validate && !image.valid?
-
return image
-
ensure
-
tempfile.close if tempfile
-
end
-
end
-
-
# Create a new MiniMagick::Image object
-
#
-
# _DANGER_: The file location passed in here is the *working copy*. That
-
# is, it gets *modified*. you can either copy it yourself or use the
-
# MiniMagick::Image.open(path) method which creates a temporary file for
-
# you and protects your original!
-
#
-
# @param input_path [String] The location of an image file
-
# @todo Allow this to accept a block that can pass off to
-
# Image#combine_options
-
1
def initialize(input_path, tempfile = nil)
-
@path = input_path
-
@tempfile = tempfile
-
@info = {}
-
reset_queue
-
end
-
-
1
def reset_queue
-
@command_queued = false
-
@queue = MiniMagick::CommandBuilder.new('mogrify')
-
@info.clear
-
end
-
-
1
def run_queue
-
return nil unless @command_queued
-
@queue << MiniMagick::Utilities.path(@path)
-
run(@queue)
-
reset_queue
-
end
-
-
# Checks to make sure that MiniMagick can read the file and understand it.
-
#
-
# This uses the 'identify' command line utility to check the file. If you
-
# are having issues with this, then please work directly with the
-
# 'identify' command and see if you can figure out what the issue is.
-
#
-
# @return [Boolean]
-
1
def valid?
-
run_command('identify', path)
-
true
-
rescue MiniMagick::Invalid
-
false
-
end
-
-
1
def info(key)
-
run_queue if @command_queued
-
-
@info[key]
-
end
-
-
# A rather low-level way to interact with the "identify" command. No nice
-
# API here, just the crazy stuff you find in ImageMagick. See the examples
-
# listed!
-
#
-
# @example
-
# image["format"] #=> "TIFF"
-
# image["height"] #=> 41 (pixels)
-
# image["width"] #=> 50 (pixels)
-
# image["colorspace"] #=> "DirectClassRGB"
-
# image["dimensions"] #=> [50, 41]
-
# image["size"] #=> 2050 (bits)
-
# image["original_at"] #=> 2005-02-23 23:17:24 +0000 (Read from Exif data)
-
# image["EXIF:ExifVersion"] #=> "0220" (Can read anything from Exif)
-
#
-
# @param format [String] A format for the "identify" command
-
# @see http://www.imagemagick.org/script/command-line-options.php#format
-
# @return [String, Numeric, Array, Time, Object] Depends on the method
-
# called! Defaults to String for unknown commands
-
1
def [](value)
-
retrieved = info(value)
-
return retrieved unless retrieved.nil?
-
-
# Why do I go to the trouble of putting in newlines? Because otherwise
-
# animated gifs screw everything up
-
retrieved = case value.to_s
-
when 'colorspace'
-
run_command('identify', '-format', '%r\n', path).split("\n")[0].strip
-
when 'format'
-
run_command('identify', '-format', '%m\n', path).split("\n")[0]
-
when 'dimensions', 'width', 'height'
-
width_height = run_command(
-
'identify', '-format', MiniMagick::Utilities.windows? ? '"%w %h\n"' : '%w %h\n', path
-
).split("\n")[0].split.map { |v| v.to_i }
-
-
@info[:width] = width_height[0]
-
@info[:height] = width_height[1]
-
@info[:dimensions] = width_height
-
@info[value.to_sym]
-
when 'size'
-
File.size(path) # Do this because calling identify -format "%b" on an animated gif fails!
-
when 'original_at'
-
# Get the EXIF original capture as a Time object
-
Time.local(*self['EXIF:DateTimeOriginal'].split(/:|\s+/)) rescue nil
-
when /^EXIF\:/i
-
result = run_command('identify', '-format', "%[#{value}]", path).chomp
-
if result.include?(',')
-
read_character_data(result)
-
else
-
result
-
end
-
else
-
run_command('identify', '-format', value, path).split("\n")[0]
-
end
-
-
@info[value] = retrieved unless retrieved.nil?
-
@info[value]
-
end
-
-
# Sends raw commands to imagemagick's `mogrify` command. The image path is
-
# automatically appended to the command.
-
#
-
# Remember, we are always acting on this instance of the Image when messing
-
# with this.
-
#
-
# @return [String] Whatever the result from the command line is. May not be
-
# terribly useful.
-
1
def <<(*args)
-
run_command('mogrify', *args << path)
-
end
-
-
# This is used to change the format of the image. That is, from "tiff to
-
# jpg" or something like that. Once you run it, the instance is pointing to
-
# a new file with a new extension!
-
#
-
# *DANGER*: This renames the file that the instance is pointing to. So, if
-
# you manually opened the file with Image.new(file_path)... Then that file
-
# is DELETED! If you used Image.open(file) then you are OK. The original
-
# file will still be there. But, any changes to it might not be...
-
#
-
# Formatting an animation into a non-animated type will result in
-
# ImageMagick creating multiple pages (starting with 0). You can choose
-
# which page you want to manipulate. We default to the first page.
-
#
-
# If you would like to convert between animated formats, pass nil as your
-
# page and ImageMagick will copy all of the pages.
-
#
-
# @param format [String] The target format... Like 'jpg', 'gif', 'tiff' etc.
-
# @param page [Integer] If this is an animated gif, say which 'page' you
-
# want with an integer. Default 0 will convert only the first page; 'nil'
-
# will convert all pages.
-
# @return [nil]
-
1
def format(format, page = 0)
-
run_queue if @command_queued
-
-
c = CommandBuilder.new('mogrify', '-format', format)
-
yield c if block_given?
-
c << (page ? "#{path}[#{page}]" : path)
-
run(c)
-
-
old_path = path
-
-
self.path = path.sub(/(\.\w*)?$/, (page ? ".#{format}" : "-0.#{format}"))
-
-
File.delete(old_path) if old_path != path
-
-
unless File.exist?(path)
-
fail MiniMagick::Error, "Unable to format to #{format}"
-
end
-
end
-
-
# Collapse images with sequences to the first frame (i.e. animated gifs) and
-
# preserve quality
-
1
def collapse!
-
run_command('mogrify', '-quality', '100', "#{path}[0]")
-
end
-
-
# Writes the temporary file out to either a file location (by passing in a
-
# String) or by passing in a Stream that you can #write(chunk) to
-
# repeatedly
-
#
-
# @param output_to [IOStream, String] Some kind of stream object that needs
-
# to be read or a file path as a String
-
# @return [IOStream, Boolean] If you pass in a file location [String] then
-
# you get a success boolean. If its a stream, you get it back.
-
1
def write(output_to)
-
run_queue if @command_queued
-
-
if output_to.kind_of?(String) || output_to.kind_of?(Pathname) || !output_to.respond_to?(:write)
-
FileUtils.copy_file path, output_to
-
if MiniMagick.validate_on_write
-
run_command(
-
'identify', MiniMagick::Utilities.path(output_to.to_s)
-
) # Verify that we have a good image
-
end
-
else # stream
-
File.open(path, 'rb') do |f|
-
f.binmode
-
while chunk = f.read(8192)
-
output_to.write(chunk)
-
end
-
end
-
output_to
-
end
-
end
-
-
# Gives you raw image data back
-
# @return [String] binary string
-
1
def to_blob
-
run_queue if @command_queued
-
-
f = File.new path
-
f.binmode
-
f.read
-
ensure
-
f.close if f
-
end
-
-
1
def mime_type
-
format = self[:format]
-
'image/' + format.to_s.downcase
-
end
-
-
# If an unknown method is called then it is sent through the mogrify
-
# program.
-
#
-
# @see http://www.imagemagick.org/script/mogrify.php
-
1
def method_missing(symbol, *args)
-
@queue.send(symbol, *args)
-
@command_queued = true
-
end
-
-
# You can use multiple commands together using this method. Very easy to
-
# use!
-
#
-
# @example
-
# image.combine_options do |c|
-
# c.draw "image Over 0,0 10,10 '#{MINUS_IMAGE_PATH}'"
-
# c.thumbnail "300x500>"
-
# c.background background
-
# end
-
#
-
# @yieldparam command [CommandBuilder]
-
1
def combine_options
-
if block_given?
-
yield @queue
-
@command_queued = true
-
end
-
end
-
-
1
def composite(other_image, output_extension = 'jpg', mask = nil, &block)
-
run_queue if @command_queued
-
begin
-
second_tempfile = Tempfile.new(output_extension)
-
second_tempfile.binmode
-
ensure
-
second_tempfile.close
-
end
-
-
command = CommandBuilder.new('composite')
-
block.call(command) if block
-
command.push(other_image.path)
-
command.push(path)
-
command.push(mask.path) unless mask.nil?
-
command.push(second_tempfile.path)
-
-
run(command)
-
Image.new(second_tempfile.path, second_tempfile)
-
end
-
-
1
def run_command(command, *args)
-
run_queue if @command_queued
-
-
if command == 'identify'
-
args.unshift '-ping' # -ping "efficiently determine image characteristics."
-
args.unshift '-quiet' if MiniMagick.mogrify? && !MiniMagick.debug # graphicsmagick has no -quiet option.
-
end
-
-
run(CommandBuilder.new(command, *args))
-
end
-
-
1
def run(command_builder)
-
command = command_builder.command
-
-
sub = Subexec.run(command, :timeout => MiniMagick.timeout)
-
-
if sub.exitstatus != 0
-
# Clean up after ourselves in case of an error
-
destroy!
-
-
# Raise the appropriate error
-
if sub.output =~ /no decode delegate/i || sub.output =~ /did not return an image/i
-
fail Invalid, sub.output
-
else
-
# TODO: should we do something different if the command times out ...?
-
# its definitely better for logging.. Otherwise we don't really know
-
fail Error, "Command (#{command.inspect.gsub("\\", "")}) failed: #{{ :status_code => sub.exitstatus, :output => sub.output }.inspect}"
-
end
-
else
-
sub.output
-
end
-
end
-
-
1
def destroy!
-
return if @tempfile.nil?
-
File.unlink(@path) if File.exist?(@path)
-
@tempfile = nil
-
end
-
-
1
private
-
-
# Sometimes we get back a list of character values
-
1
def read_character_data(string)
-
string.scan(/\d+/).map(&:to_i).map(&:chr).join
-
end
-
end
-
end
-
1
require 'rbconfig'
-
1
require 'shellwords'
-
1
require 'pathname'
-
-
1
module MiniMagick
-
1
module Utilities
-
1
class << self
-
# Cross-platform way of finding an executable in the $PATH.
-
#
-
# which('ruby') #=> /usr/bin/ruby
-
1
def which(cmd)
-
exts = ENV['PATHEXT'] ? ENV['PATHEXT'].split(';') : ['']
-
ENV['PATH'].split(File::PATH_SEPARATOR).each do |path|
-
exts.each do |ext|
-
exe = File.join(path, "#{cmd}#{ext}")
-
return exe if File.executable? exe
-
end
-
end
-
nil
-
end
-
-
# Finds out if the host OS is windows
-
1
def windows?
-
RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/
-
end
-
-
1
def escape(value)
-
if windows?
-
windows_escape(value)
-
else
-
shell_escape(value)
-
end
-
end
-
-
1
def shell_escape(value)
-
Shellwords.escape(value)
-
end
-
-
1
def windows_escape(value)
-
# For Windows, ^ is the escape char, equivalent to \ in Unix.
-
escaped = value.gsub(/\^/, '^^').gsub(/>/, '^>')
-
if escaped !~ /^".+"$/ && escaped.include?("'")
-
escaped.inspect
-
else
-
escaped
-
end
-
end
-
-
1
def path(path)
-
if windows?
-
# For Windows, if a path contains space char, you need to quote it,
-
# otherwise you SHOULD NOT quote it. If you quote a path that does
-
# not contains space, it will not work.
-
pathname = Pathname.new(path).to_s
-
path.include?(' ') ? pathname.inspect : pathname
-
else
-
path
-
end
-
end
-
end
-
end
-
end
-
1
require "optparse"
-
1
require "thread"
-
1
require "mutex_m"
-
1
require "minitest/parallel"
-
-
##
-
# :include: README.txt
-
-
1
module Minitest
-
1
VERSION = "5.4.2" # :nodoc:
-
-
1
@@installed_at_exit ||= false
-
1
@@after_run = []
-
1
@extensions = []
-
-
2
mc = (class << self; self; end)
-
-
##
-
# Parallel test executor
-
-
1
mc.send :attr_accessor, :parallel_executor
-
1
self.parallel_executor = Parallel::Executor.new((ENV['N'] || 2).to_i)
-
-
##
-
# Filter object for backtraces.
-
-
1
mc.send :attr_accessor, :backtrace_filter
-
-
##
-
# Reporter object to be used for all runs.
-
#
-
# NOTE: This accessor is only available during setup, not during runs.
-
-
1
mc.send :attr_accessor, :reporter
-
-
##
-
# Names of known extension plugins.
-
-
1
mc.send :attr_accessor, :extensions
-
-
##
-
# Registers Minitest to run at process exit
-
-
1
def self.autorun
-
at_exit {
-
next if $! and not ($!.kind_of? SystemExit and $!.success?)
-
-
exit_code = nil
-
-
at_exit {
-
@@after_run.reverse_each(&:call)
-
exit exit_code || false
-
}
-
-
exit_code = Minitest.run ARGV
-
} unless @@installed_at_exit
-
@@installed_at_exit = true
-
end
-
-
##
-
# A simple hook allowing you to run a block of code after everything
-
# is done running. Eg:
-
#
-
# Minitest.after_run { p $debugging_info }
-
-
1
def self.after_run &block
-
@@after_run << block
-
end
-
-
1
def self.init_plugins options # :nodoc:
-
self.extensions.each do |name|
-
msg = "plugin_#{name}_init"
-
send msg, options if self.respond_to? msg
-
end
-
end
-
-
1
def self.load_plugins # :nodoc:
-
return unless self.extensions.empty?
-
-
seen = {}
-
-
require "rubygems" unless defined? Gem
-
-
Gem.find_files("minitest/*_plugin.rb").each do |plugin_path|
-
name = File.basename plugin_path, "_plugin.rb"
-
-
next if seen[name]
-
seen[name] = true
-
-
require plugin_path
-
self.extensions << name
-
end
-
end
-
-
##
-
# This is the top-level run method. Everything starts from here. It
-
# tells each Runnable sub-class to run, and each of those are
-
# responsible for doing whatever they do.
-
#
-
# The overall structure of a run looks like this:
-
#
-
# Minitest.autorun
-
# Minitest.run(args)
-
# Minitest.__run(reporter, options)
-
# Runnable.runnables.each
-
# runnable.run(reporter, options)
-
# self.runnable_methods.each
-
# self.run_one_method(self, runnable_method, reporter)
-
# Minitest.run_one_method(klass, runnable_method, reporter)
-
# klass.new(runnable_method).run
-
-
1
def self.run args = []
-
self.load_plugins
-
-
options = process_args args
-
-
reporter = CompositeReporter.new
-
reporter << SummaryReporter.new(options[:io], options)
-
reporter << ProgressReporter.new(options[:io], options)
-
-
self.reporter = reporter # this makes it available to plugins
-
self.init_plugins options
-
self.reporter = nil # runnables shouldn't depend on the reporter, ever
-
-
reporter.start
-
__run reporter, options
-
self.parallel_executor.shutdown
-
reporter.report
-
-
reporter.passed?
-
end
-
-
##
-
# Internal run method. Responsible for telling all Runnable
-
# sub-classes to run.
-
#
-
# NOTE: this method is redefined in parallel_each.rb, which is
-
# loaded if a Runnable calls parallelize_me!.
-
-
1
def self.__run reporter, options
-
suites = Runnable.runnables.shuffle
-
parallel, serial = suites.partition { |s| s.test_order == :parallel }
-
-
# If we run the parallel tests before the serial tests, the parallel tests
-
# could run in parallel with the serial tests. This would be bad because
-
# the serial tests won't lock around Reporter#record. Run the serial tests
-
# first, so that after they complete, the parallel tests will lock when
-
# recording results.
-
serial.map { |suite| suite.run reporter, options } +
-
parallel.map { |suite| suite.run reporter, options }
-
end
-
-
1
def self.process_args args = [] # :nodoc:
-
options = {
-
:io => $stdout,
-
}
-
orig_args = args.dup
-
-
OptionParser.new do |opts|
-
opts.banner = "minitest options:"
-
opts.version = Minitest::VERSION
-
-
opts.on "-h", "--help", "Display this help." do
-
puts opts
-
exit
-
end
-
-
opts.on "-s", "--seed SEED", Integer, "Sets random seed" do |m|
-
options[:seed] = m.to_i
-
end
-
-
opts.on "-v", "--verbose", "Verbose. Show progress processing files." do
-
options[:verbose] = true
-
end
-
-
opts.on "-n", "--name PATTERN","Filter run on /pattern/ or string." do |a|
-
options[:filter] = a
-
end
-
-
unless extensions.empty?
-
opts.separator ""
-
opts.separator "Known extensions: #{extensions.join(', ')}"
-
-
extensions.each do |meth|
-
msg = "plugin_#{meth}_options"
-
send msg, opts, options if self.respond_to?(msg)
-
end
-
end
-
-
begin
-
opts.parse! args
-
rescue OptionParser::InvalidOption => e
-
puts
-
puts e
-
puts
-
puts opts
-
exit 1
-
end
-
-
orig_args -= args
-
end
-
-
unless options[:seed] then
-
srand
-
options[:seed] = srand % 0xFFFF
-
orig_args << "--seed" << options[:seed].to_s
-
end
-
-
srand options[:seed]
-
-
options[:args] = orig_args.map { |s|
-
s =~ /[\s|&<>$()]/ ? s.inspect : s
-
}.join " "
-
-
options
-
end
-
-
1
def self.filter_backtrace bt # :nodoc:
-
backtrace_filter.filter bt
-
end
-
-
##
-
# Represents anything "runnable", like Test, Spec, Benchmark, or
-
# whatever you can dream up.
-
#
-
# Subclasses of this are automatically registered and available in
-
# Runnable.runnables.
-
-
1
class Runnable
-
##
-
# Number of assertions executed in this run.
-
-
1
attr_accessor :assertions
-
-
##
-
# An assertion raised during the run, if any.
-
-
1
attr_accessor :failures
-
-
##
-
# Name of the run.
-
-
1
def name
-
@NAME
-
end
-
-
##
-
# Set the name of the run.
-
-
1
def name= o
-
@NAME = o
-
end
-
-
1
def self.inherited klass # :nodoc:
-
7
self.runnables << klass
-
7
super
-
end
-
-
##
-
# Returns all instance methods matching the pattern +re+.
-
-
1
def self.methods_matching re
-
public_instance_methods(true).grep(re).map(&:to_s)
-
end
-
-
1
def self.reset # :nodoc:
-
1
@@runnables = []
-
end
-
-
1
reset
-
-
##
-
# Responsible for running all runnable methods in a given class,
-
# each in its own instance. Each instance is passed to the
-
# reporter to record.
-
-
1
def self.run reporter, options = {}
-
filter = options[:filter] || '/./'
-
filter = Regexp.new $1 if filter =~ /\/(.*)\//
-
-
filtered_methods = self.runnable_methods.find_all { |m|
-
filter === m || filter === "#{self}##{m}"
-
}
-
-
with_info_handler reporter do
-
filtered_methods.each do |method_name|
-
run_one_method self, method_name, reporter
-
end
-
end
-
end
-
-
1
def self.run_one_method klass, method_name, reporter
-
reporter.record Minitest.run_one_method(klass, method_name)
-
end
-
-
1
def self.with_info_handler reporter, &block # :nodoc:
-
handler = lambda do
-
unless reporter.passed? then
-
warn "Current results:"
-
warn ""
-
warn reporter.reporters.first
-
warn ""
-
end
-
end
-
-
on_signal "INFO", handler, &block
-
end
-
-
1
SIGNALS = Signal.list
-
-
1
def self.on_signal name, action # :nodoc:
-
supported = SIGNALS[name]
-
-
old_trap = trap name do
-
old_trap.call if old_trap.respond_to? :call
-
action.call
-
end if supported
-
-
yield
-
ensure
-
trap name, old_trap if supported
-
end
-
-
##
-
# Each subclass of Runnable is responsible for overriding this
-
# method to return all runnable methods. See #methods_matching.
-
-
1
def self.runnable_methods
-
raise NotImplementedError, "subclass responsibility"
-
end
-
-
##
-
# Returns all subclasses of Runnable.
-
-
1
def self.runnables
-
7
@@runnables
-
end
-
-
1
def marshal_dump # :nodoc:
-
[self.name, self.failures, self.assertions]
-
end
-
-
1
def marshal_load ary # :nodoc:
-
self.name, self.failures, self.assertions = ary
-
end
-
-
1
def failure # :nodoc:
-
self.failures.first
-
end
-
-
1
def initialize name # :nodoc:
-
self.name = name
-
self.failures = []
-
self.assertions = 0
-
end
-
-
##
-
# Runs a single method. Needs to return self.
-
-
1
def run
-
raise NotImplementedError, "subclass responsibility"
-
end
-
-
##
-
# Did this run pass?
-
#
-
# Note: skipped runs are not considered passing, but they don't
-
# cause the process to exit non-zero.
-
-
1
def passed?
-
raise NotImplementedError, "subclass responsibility"
-
end
-
-
##
-
# Returns a single character string to print based on the result
-
# of the run. Eg ".", "F", or "E".
-
-
1
def result_code
-
raise NotImplementedError, "subclass responsibility"
-
end
-
-
##
-
# Was this run skipped? See #passed? for more information.
-
-
1
def skipped?
-
raise NotImplementedError, "subclass responsibility"
-
end
-
end
-
-
##
-
# Defines the API for Reporters. Subclass this and override whatever
-
# you want. Go nuts.
-
-
1
class AbstractReporter
-
1
include Mutex_m
-
-
##
-
# Starts reporting on the run.
-
-
1
def start
-
end
-
-
##
-
# Record a result and output the Runnable#result_code. Stores the
-
# result of the run if the run did not pass.
-
-
1
def record result
-
end
-
-
##
-
# Outputs the summary of the run.
-
-
1
def report
-
end
-
-
##
-
# Did this run pass?
-
-
1
def passed?
-
true
-
end
-
end
-
-
1
class Reporter < AbstractReporter # :nodoc:
-
##
-
# The IO used to report.
-
-
1
attr_accessor :io
-
-
##
-
# Command-line options for this run.
-
-
1
attr_accessor :options
-
-
1
def initialize io = $stdout, options = {} # :nodoc:
-
super()
-
self.io = io
-
self.options = options
-
end
-
end
-
-
##
-
# A very simple reporter that prints the "dots" during the run.
-
#
-
# This is added to the top-level CompositeReporter at the start of
-
# the run. If you want to change the output of minitest via a
-
# plugin, pull this out of the composite and replace it with your
-
# own.
-
-
1
class ProgressReporter < Reporter
-
1
def record result # :nodoc:
-
io.print "%s#%s = %.2f s = " % [result.class, result.name, result.time] if
-
options[:verbose]
-
io.print result.result_code
-
io.puts if options[:verbose]
-
end
-
end
-
-
##
-
# A reporter that gathers statistics about a test run. Does not do
-
# any IO because meant to be used as a parent class for a reporter
-
# that does.
-
#
-
# If you want to create an entirely different type of output (eg,
-
# CI, HTML, etc), this is the place to start.
-
-
1
class StatisticsReporter < Reporter
-
# :stopdoc:
-
1
attr_accessor :assertions
-
1
attr_accessor :count
-
1
attr_accessor :results
-
1
attr_accessor :start_time
-
1
attr_accessor :total_time
-
1
attr_accessor :failures
-
1
attr_accessor :errors
-
1
attr_accessor :skips
-
# :startdoc:
-
-
1
def initialize io = $stdout, options = {} # :nodoc:
-
super
-
-
self.assertions = 0
-
self.count = 0
-
self.results = []
-
self.start_time = nil
-
self.total_time = nil
-
self.failures = nil
-
self.errors = nil
-
self.skips = nil
-
end
-
-
1
def passed? # :nodoc:
-
results.all?(&:skipped?)
-
end
-
-
1
def start # :nodoc:
-
self.start_time = Time.now
-
end
-
-
1
def record result # :nodoc:
-
self.count += 1
-
self.assertions += result.assertions
-
-
results << result if not result.passed? or result.skipped?
-
end
-
-
1
def report # :nodoc:
-
aggregate = results.group_by { |r| r.failure.class }
-
aggregate.default = [] # dumb. group_by should provide this
-
-
self.total_time = Time.now - start_time
-
self.failures = aggregate[Assertion].size
-
self.errors = aggregate[UnexpectedError].size
-
self.skips = aggregate[Skip].size
-
end
-
end
-
-
##
-
# A reporter that prints the header, summary, and failure details at
-
# the end of the run.
-
#
-
# This is added to the top-level CompositeReporter at the start of
-
# the run. If you want to change the output of minitest via a
-
# plugin, pull this out of the composite and replace it with your
-
# own.
-
-
1
class SummaryReporter < StatisticsReporter
-
# :stopdoc:
-
1
attr_accessor :sync
-
1
attr_accessor :old_sync
-
# :startdoc:
-
-
1
def start # :nodoc:
-
super
-
-
io.puts "Run options: #{options[:args]}"
-
io.puts
-
io.puts "# Running:"
-
io.puts
-
-
self.sync = io.respond_to? :"sync=" # stupid emacs
-
self.old_sync, io.sync = io.sync, true if self.sync
-
end
-
-
1
def report # :nodoc:
-
super
-
-
io.sync = self.old_sync
-
-
io.puts unless options[:verbose] # finish the dots
-
io.puts
-
io.puts statistics
-
io.puts aggregated_results
-
io.puts summary
-
end
-
-
1
def statistics # :nodoc:
-
"Finished in %.6fs, %.4f runs/s, %.4f assertions/s." %
-
[total_time, count / total_time, assertions / total_time]
-
end
-
-
1
def aggregated_results # :nodoc:
-
filtered_results = results.dup
-
filtered_results.reject!(&:skipped?) unless options[:verbose]
-
-
filtered_results.each_with_index.map do |result, i|
-
"\n%3d) %s" % [i+1, result]
-
end.join("\n") + "\n"
-
end
-
-
1
alias to_s aggregated_results
-
-
1
def summary # :nodoc:
-
extra = ""
-
-
extra = "\n\nYou have skipped tests. Run with --verbose for details." if
-
results.any?(&:skipped?) unless options[:verbose] or ENV["MT_NO_SKIP_MSG"]
-
-
"%d runs, %d assertions, %d failures, %d errors, %d skips%s" %
-
[count, assertions, failures, errors, skips, extra]
-
end
-
end
-
-
##
-
# Dispatch to multiple reporters as one.
-
-
1
class CompositeReporter < AbstractReporter
-
##
-
# The list of reporters to dispatch to.
-
-
1
attr_accessor :reporters
-
-
1
def initialize *reporters # :nodoc:
-
super()
-
self.reporters = reporters
-
end
-
-
##
-
# Add another reporter to the mix.
-
-
1
def << reporter
-
self.reporters << reporter
-
end
-
-
1
def passed? # :nodoc:
-
self.reporters.all?(&:passed?)
-
end
-
-
1
def start # :nodoc:
-
self.reporters.each(&:start)
-
end
-
-
1
def record result # :nodoc:
-
self.reporters.each do |reporter|
-
reporter.record result
-
end
-
end
-
-
1
def report # :nodoc:
-
self.reporters.each(&:report)
-
end
-
end
-
-
##
-
# Represents run failures.
-
-
1
class Assertion < Exception
-
1
def error # :nodoc:
-
self
-
end
-
-
##
-
# Where was this run before an assertion was raised?
-
-
1
def location
-
last_before_assertion = ""
-
self.backtrace.reverse_each do |s|
-
break if s =~ /in .(assert|refute|flunk|pass|fail|raise|must|wont)/
-
last_before_assertion = s
-
end
-
last_before_assertion.sub(/:in .*$/, "")
-
end
-
-
1
def result_code # :nodoc:
-
result_label[0, 1]
-
end
-
-
1
def result_label # :nodoc:
-
"Failure"
-
end
-
end
-
-
##
-
# Assertion raised when skipping a run.
-
-
1
class Skip < Assertion
-
1
def result_label # :nodoc:
-
"Skipped"
-
end
-
end
-
-
##
-
# Assertion wrapping an unexpected error that was raised during a run.
-
-
1
class UnexpectedError < Assertion
-
1
attr_accessor :exception # :nodoc:
-
-
1
def initialize exception # :nodoc:
-
super
-
self.exception = exception
-
end
-
-
1
def backtrace # :nodoc:
-
self.exception.backtrace
-
end
-
-
1
def error # :nodoc:
-
self.exception
-
end
-
-
1
def message # :nodoc:
-
bt = Minitest::filter_backtrace(self.backtrace).join "\n "
-
"#{self.exception.class}: #{self.exception.message}\n #{bt}"
-
end
-
-
1
def result_label # :nodoc:
-
"Error"
-
end
-
end
-
-
##
-
# Provides a simple set of guards that you can use in your tests
-
# to skip execution if it is not applicable. These methods are
-
# mixed into Test as both instance and class methods so you
-
# can use them inside or outside of the test methods.
-
#
-
# def test_something_for_mri
-
# skip "bug 1234" if jruby?
-
# # ...
-
# end
-
#
-
# if windows? then
-
# # ... lots of test methods ...
-
# end
-
-
1
module Guard
-
-
##
-
# Is this running on jruby?
-
-
1
def jruby? platform = RUBY_PLATFORM
-
"java" == platform
-
end
-
-
##
-
# Is this running on maglev?
-
-
1
def maglev? platform = defined?(RUBY_ENGINE) && RUBY_ENGINE
-
"maglev" == platform
-
end
-
-
##
-
# Is this running on mri?
-
-
1
def mri? platform = RUBY_DESCRIPTION
-
/^ruby/ =~ platform
-
end
-
-
##
-
# Is this running on rubinius?
-
-
1
def rubinius? platform = defined?(RUBY_ENGINE) && RUBY_ENGINE
-
"rbx" == platform
-
end
-
-
##
-
# Is this running on windows?
-
-
1
def windows? platform = RUBY_PLATFORM
-
/mswin|mingw/ =~ platform
-
end
-
end
-
-
1
class BacktraceFilter # :nodoc:
-
1
def filter bt
-
return ["No backtrace"] unless bt
-
-
return bt.dup if $DEBUG
-
-
new_bt = bt.take_while { |line| line !~ /lib\/minitest/ }
-
new_bt = bt.select { |line| line !~ /lib\/minitest/ } if new_bt.empty?
-
new_bt = bt.dup if new_bt.empty?
-
-
new_bt
-
end
-
end
-
-
1
self.backtrace_filter = BacktraceFilter.new
-
-
1
def self.run_one_method klass, method_name # :nodoc:
-
result = klass.new(method_name).run
-
raise "#{klass}#run _must_ return self" unless klass === result
-
result
-
end
-
end
-
-
1
require "minitest/test"
-
1
require "rbconfig"
-
1
require "tempfile"
-
1
require 'stringio'
-
-
1
module Minitest
-
##
-
# Minitest Assertions. All assertion methods accept a +msg+ which is
-
# printed if the assertion fails.
-
#
-
# Protocol: Nearly everything here boils up to +assert+, which
-
# expects to be able to increment an instance accessor named
-
# +assertions+. This is not provided by Assertions and must be
-
# provided by the thing including Assertions. See Minitest::Runnable
-
# for an example.
-
-
1
module Assertions
-
1
UNDEFINED = Object.new # :nodoc:
-
-
1
def UNDEFINED.inspect # :nodoc:
-
"UNDEFINED" # again with the rdoc bugs... :(
-
end
-
-
##
-
# Returns the diff command to use in #diff. Tries to intelligently
-
# figure out what diff to use.
-
-
1
def self.diff
-
@diff = if (RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ &&
-
system("diff.exe", __FILE__, __FILE__)) then
-
"diff.exe -u"
-
elsif Minitest::Test.maglev? then
-
"diff -u"
-
elsif system("gdiff", __FILE__, __FILE__)
-
"gdiff -u" # solaris and kin suck
-
elsif system("diff", __FILE__, __FILE__)
-
"diff -u"
-
else
-
nil
-
end unless defined? @diff
-
-
@diff
-
end
-
-
##
-
# Set the diff command to use in #diff.
-
-
1
def self.diff= o
-
@diff = o
-
end
-
-
##
-
# Returns a diff between +exp+ and +act+. If there is no known
-
# diff command or if it doesn't make sense to diff the output
-
# (single line, short output), then it simply returns a basic
-
# comparison between the two.
-
-
1
def diff exp, act
-
expect = mu_pp_for_diff exp
-
butwas = mu_pp_for_diff act
-
result = nil
-
-
need_to_diff =
-
(expect.include?("\n") ||
-
butwas.include?("\n") ||
-
expect.size > 30 ||
-
butwas.size > 30 ||
-
expect == butwas) &&
-
Minitest::Assertions.diff
-
-
-
return "Expected: #{mu_pp exp}\n Actual: #{mu_pp act}" unless
-
need_to_diff
-
-
Tempfile.open("expect") do |a|
-
a.puts expect
-
a.flush
-
-
Tempfile.open("butwas") do |b|
-
b.puts butwas
-
b.flush
-
-
result = `#{Minitest::Assertions.diff} #{a.path} #{b.path}`
-
result.sub!(/^\-\-\- .+/, "--- expected")
-
result.sub!(/^\+\+\+ .+/, "+++ actual")
-
-
if result.empty? then
-
klass = exp.class
-
result = [
-
"No visible difference in the #{klass}#inspect output.\n",
-
"You should look at the implementation of #== on ",
-
"#{klass} or its members.\n",
-
expect,
-
].join
-
end
-
end
-
end
-
-
result
-
end
-
-
##
-
# This returns a human-readable version of +obj+. By default
-
# #inspect is called. You can override this to use #pretty_print
-
# if you want.
-
-
1
def mu_pp obj
-
s = obj.inspect
-
s = s.encode Encoding.default_external if defined? Encoding
-
s
-
end
-
-
##
-
# This returns a diff-able human-readable version of +obj+. This
-
# differs from the regular mu_pp because it expands escaped
-
# newlines and makes hex-values generic (like object_ids). This
-
# uses mu_pp to do the first pass and then cleans it up.
-
-
1
def mu_pp_for_diff obj
-
mu_pp(obj).gsub(/\\n/, "\n").gsub(/:0x[a-fA-F0-9]{4,}/m, ':0xXXXXXX')
-
end
-
-
##
-
# Fails unless +test+ is truthy.
-
-
1
def assert test, msg = nil
-
self.assertions += 1
-
unless test then
-
msg ||= "Failed assertion, no message given."
-
msg = msg.call if Proc === msg
-
raise Minitest::Assertion, msg
-
end
-
true
-
end
-
-
1
def _synchronize # :nodoc:
-
yield
-
end
-
-
##
-
# Fails unless +obj+ is empty.
-
-
1
def assert_empty obj, msg = nil
-
msg = message(msg) { "Expected #{mu_pp(obj)} to be empty" }
-
assert_respond_to obj, :empty?
-
assert obj.empty?, msg
-
end
-
-
1
E = ""
-
-
##
-
# Fails unless <tt>exp == act</tt> printing the difference between
-
# the two, if possible.
-
#
-
# If there is no visible difference but the assertion fails, you
-
# should suspect that your #== is buggy, or your inspect output is
-
# missing crucial details.
-
#
-
# For floats use assert_in_delta.
-
#
-
# See also: Minitest::Assertions.diff
-
-
1
def assert_equal exp, act, msg = nil
-
msg = message(msg, E) { diff exp, act }
-
assert exp == act, msg
-
end
-
-
##
-
# For comparing Floats. Fails unless +exp+ and +act+ are within +delta+
-
# of each other.
-
#
-
# assert_in_delta Math::PI, (22.0 / 7.0), 0.01
-
-
1
def assert_in_delta exp, act, delta = 0.001, msg = nil
-
n = (exp - act).abs
-
msg = message(msg) {
-
"Expected |#{exp} - #{act}| (#{n}) to be <= #{delta}"
-
}
-
assert delta >= n, msg
-
end
-
-
##
-
# For comparing Floats. Fails unless +exp+ and +act+ have a relative
-
# error less than +epsilon+.
-
-
1
def assert_in_epsilon a, b, epsilon = 0.001, msg = nil
-
assert_in_delta a, b, [a.abs, b.abs].min * epsilon, msg
-
end
-
-
##
-
# Fails unless +collection+ includes +obj+.
-
-
1
def assert_includes collection, obj, msg = nil
-
msg = message(msg) {
-
"Expected #{mu_pp(collection)} to include #{mu_pp(obj)}"
-
}
-
assert_respond_to collection, :include?
-
assert collection.include?(obj), msg
-
end
-
-
##
-
# Fails unless +obj+ is an instance of +cls+.
-
-
1
def assert_instance_of cls, obj, msg = nil
-
msg = message(msg) {
-
"Expected #{mu_pp(obj)} to be an instance of #{cls}, not #{obj.class}"
-
}
-
-
assert obj.instance_of?(cls), msg
-
end
-
-
##
-
# Fails unless +obj+ is a kind of +cls+.
-
-
1
def assert_kind_of cls, obj, msg = nil
-
msg = message(msg) {
-
"Expected #{mu_pp(obj)} to be a kind of #{cls}, not #{obj.class}" }
-
-
assert obj.kind_of?(cls), msg
-
end
-
-
##
-
# Fails unless +matcher+ <tt>=~</tt> +obj+.
-
-
1
def assert_match matcher, obj, msg = nil
-
msg = message(msg) { "Expected #{mu_pp matcher} to match #{mu_pp obj}" }
-
assert_respond_to matcher, :"=~"
-
matcher = Regexp.new Regexp.escape matcher if String === matcher
-
assert matcher =~ obj, msg
-
end
-
-
##
-
# Fails unless +obj+ is nil
-
-
1
def assert_nil obj, msg = nil
-
msg = message(msg) { "Expected #{mu_pp(obj)} to be nil" }
-
assert obj.nil?, msg
-
end
-
-
##
-
# For testing with binary operators. Eg:
-
#
-
# assert_operator 5, :<=, 4
-
-
1
def assert_operator o1, op, o2 = UNDEFINED, msg = nil
-
return assert_predicate o1, op, msg if UNDEFINED == o2
-
msg = message(msg) { "Expected #{mu_pp(o1)} to be #{op} #{mu_pp(o2)}" }
-
assert o1.__send__(op, o2), msg
-
end
-
-
##
-
# Fails if stdout or stderr do not output the expected results.
-
# Pass in nil if you don't care about that streams output. Pass in
-
# "" if you require it to be silent. Pass in a regexp if you want
-
# to pattern match.
-
#
-
# NOTE: this uses #capture_io, not #capture_subprocess_io.
-
#
-
# See also: #assert_silent
-
-
1
def assert_output stdout = nil, stderr = nil
-
out, err = capture_io do
-
yield
-
end
-
-
err_msg = Regexp === stderr ? :assert_match : :assert_equal if stderr
-
out_msg = Regexp === stdout ? :assert_match : :assert_equal if stdout
-
-
y = send err_msg, stderr, err, "In stderr" if err_msg
-
x = send out_msg, stdout, out, "In stdout" if out_msg
-
-
(!stdout || x) && (!stderr || y)
-
end
-
-
##
-
# For testing with predicates. Eg:
-
#
-
# assert_predicate str, :empty?
-
#
-
# This is really meant for specs and is front-ended by assert_operator:
-
#
-
# str.must_be :empty?
-
-
1
def assert_predicate o1, op, msg = nil
-
msg = message(msg) { "Expected #{mu_pp(o1)} to be #{op}" }
-
assert o1.__send__(op), msg
-
end
-
-
##
-
# Fails unless the block raises one of +exp+. Returns the
-
# exception matched so you can check the message, attributes, etc.
-
-
1
def assert_raises *exp
-
msg = "#{exp.pop}.\n" if String === exp.last
-
-
begin
-
yield
-
rescue Minitest::Skip => e
-
return e if exp.include? Minitest::Skip
-
raise e
-
rescue Exception => e
-
expected = exp.any? { |ex|
-
if ex.instance_of? Module then
-
e.kind_of? ex
-
else
-
e.instance_of? ex
-
end
-
}
-
-
assert expected, proc {
-
exception_details(e, "#{msg}#{mu_pp(exp)} exception expected, not")
-
}
-
-
return e
-
end
-
-
exp = exp.first if exp.size == 1
-
-
flunk "#{msg}#{mu_pp(exp)} expected but nothing was raised."
-
end
-
-
##
-
# Fails unless +obj+ responds to +meth+.
-
-
1
def assert_respond_to obj, meth, msg = nil
-
msg = message(msg) {
-
"Expected #{mu_pp(obj)} (#{obj.class}) to respond to ##{meth}"
-
}
-
assert obj.respond_to?(meth), msg
-
end
-
-
##
-
# Fails unless +exp+ and +act+ are #equal?
-
-
1
def assert_same exp, act, msg = nil
-
msg = message(msg) {
-
data = [mu_pp(act), act.object_id, mu_pp(exp), exp.object_id]
-
"Expected %s (oid=%d) to be the same as %s (oid=%d)" % data
-
}
-
assert exp.equal?(act), msg
-
end
-
-
##
-
# +send_ary+ is a receiver, message and arguments.
-
#
-
# Fails unless the call returns a true value
-
-
1
def assert_send send_ary, m = nil
-
recv, msg, *args = send_ary
-
m = message(m) {
-
"Expected #{mu_pp(recv)}.#{msg}(*#{mu_pp(args)}) to return true" }
-
assert recv.__send__(msg, *args), m
-
end
-
-
##
-
# Fails if the block outputs anything to stderr or stdout.
-
#
-
# See also: #assert_output
-
-
1
def assert_silent
-
assert_output "", "" do
-
yield
-
end
-
end
-
-
##
-
# Fails unless the block throws +sym+
-
-
1
def assert_throws sym, msg = nil
-
default = "Expected #{mu_pp(sym)} to have been thrown"
-
caught = true
-
catch(sym) do
-
begin
-
yield
-
rescue ThreadError => e # wtf?!? 1.8 + threads == suck
-
default += ", not \:#{e.message[/uncaught throw \`(\w+?)\'/, 1]}"
-
rescue ArgumentError => e # 1.9 exception
-
default += ", not #{e.message.split(/ /).last}"
-
rescue NameError => e # 1.8 exception
-
default += ", not #{e.name.inspect}"
-
end
-
caught = false
-
end
-
-
assert caught, message(msg) { default }
-
end
-
-
##
-
# Captures $stdout and $stderr into strings:
-
#
-
# out, err = capture_io do
-
# puts "Some info"
-
# warn "You did a bad thing"
-
# end
-
#
-
# assert_match %r%info%, out
-
# assert_match %r%bad%, err
-
#
-
# NOTE: For efficiency, this method uses StringIO and does not
-
# capture IO for subprocesses. Use #capture_subprocess_io for
-
# that.
-
-
1
def capture_io
-
_synchronize do
-
begin
-
captured_stdout, captured_stderr = StringIO.new, StringIO.new
-
-
orig_stdout, orig_stderr = $stdout, $stderr
-
$stdout, $stderr = captured_stdout, captured_stderr
-
-
yield
-
-
return captured_stdout.string, captured_stderr.string
-
ensure
-
$stdout = orig_stdout
-
$stderr = orig_stderr
-
end
-
end
-
end
-
-
##
-
# Captures $stdout and $stderr into strings, using Tempfile to
-
# ensure that subprocess IO is captured as well.
-
#
-
# out, err = capture_subprocess_io do
-
# system "echo Some info"
-
# system "echo You did a bad thing 1>&2"
-
# end
-
#
-
# assert_match %r%info%, out
-
# assert_match %r%bad%, err
-
#
-
# NOTE: This method is approximately 10x slower than #capture_io so
-
# only use it when you need to test the output of a subprocess.
-
-
1
def capture_subprocess_io
-
_synchronize do
-
begin
-
require 'tempfile'
-
-
captured_stdout, captured_stderr = Tempfile.new("out"), Tempfile.new("err")
-
-
orig_stdout, orig_stderr = $stdout.dup, $stderr.dup
-
$stdout.reopen captured_stdout
-
$stderr.reopen captured_stderr
-
-
yield
-
-
$stdout.rewind
-
$stderr.rewind
-
-
return captured_stdout.read, captured_stderr.read
-
ensure
-
captured_stdout.unlink
-
captured_stderr.unlink
-
$stdout.reopen orig_stdout
-
$stderr.reopen orig_stderr
-
end
-
end
-
end
-
-
##
-
# Returns details for exception +e+
-
-
1
def exception_details e, msg
-
[
-
"#{msg}",
-
"Class: <#{e.class}>",
-
"Message: <#{e.message.inspect}>",
-
"---Backtrace---",
-
"#{Minitest::filter_backtrace(e.backtrace).join("\n")}",
-
"---------------",
-
].join "\n"
-
end
-
-
##
-
# Fails with +msg+
-
-
1
def flunk msg = nil
-
msg ||= "Epic Fail!"
-
assert false, msg
-
end
-
-
##
-
# Returns a proc that will output +msg+ along with the default message.
-
-
1
def message msg = nil, ending = nil, &default
-
proc {
-
msg = msg.call.chomp(".") if Proc === msg
-
custom_message = "#{msg}.\n" unless msg.nil? or msg.to_s.empty?
-
"#{custom_message}#{default.call}#{ending || "."}"
-
}
-
end
-
-
##
-
# used for counting assertions
-
-
1
def pass msg = nil
-
assert true
-
end
-
-
##
-
# Fails if +test+ is truthy.
-
-
1
def refute test, msg = nil
-
msg ||= "Failed refutation, no message given"
-
not assert(! test, msg)
-
end
-
-
##
-
# Fails if +obj+ is empty.
-
-
1
def refute_empty obj, msg = nil
-
msg = message(msg) { "Expected #{mu_pp(obj)} to not be empty" }
-
assert_respond_to obj, :empty?
-
refute obj.empty?, msg
-
end
-
-
##
-
# Fails if <tt>exp == act</tt>.
-
#
-
# For floats use refute_in_delta.
-
-
1
def refute_equal exp, act, msg = nil
-
msg = message(msg) {
-
"Expected #{mu_pp(act)} to not be equal to #{mu_pp(exp)}"
-
}
-
refute exp == act, msg
-
end
-
-
##
-
# For comparing Floats. Fails if +exp+ is within +delta+ of +act+.
-
#
-
# refute_in_delta Math::PI, (22.0 / 7.0)
-
-
1
def refute_in_delta exp, act, delta = 0.001, msg = nil
-
n = (exp - act).abs
-
msg = message(msg) {
-
"Expected |#{exp} - #{act}| (#{n}) to not be <= #{delta}"
-
}
-
refute delta >= n, msg
-
end
-
-
##
-
# For comparing Floats. Fails if +exp+ and +act+ have a relative error
-
# less than +epsilon+.
-
-
1
def refute_in_epsilon a, b, epsilon = 0.001, msg = nil
-
refute_in_delta a, b, a * epsilon, msg
-
end
-
-
##
-
# Fails if +collection+ includes +obj+.
-
-
1
def refute_includes collection, obj, msg = nil
-
msg = message(msg) {
-
"Expected #{mu_pp(collection)} to not include #{mu_pp(obj)}"
-
}
-
assert_respond_to collection, :include?
-
refute collection.include?(obj), msg
-
end
-
-
##
-
# Fails if +obj+ is an instance of +cls+.
-
-
1
def refute_instance_of cls, obj, msg = nil
-
msg = message(msg) {
-
"Expected #{mu_pp(obj)} to not be an instance of #{cls}"
-
}
-
refute obj.instance_of?(cls), msg
-
end
-
-
##
-
# Fails if +obj+ is a kind of +cls+.
-
-
1
def refute_kind_of cls, obj, msg = nil
-
msg = message(msg) { "Expected #{mu_pp(obj)} to not be a kind of #{cls}" }
-
refute obj.kind_of?(cls), msg
-
end
-
-
##
-
# Fails if +matcher+ <tt>=~</tt> +obj+.
-
-
1
def refute_match matcher, obj, msg = nil
-
msg = message(msg) {"Expected #{mu_pp matcher} to not match #{mu_pp obj}"}
-
assert_respond_to matcher, :"=~"
-
matcher = Regexp.new Regexp.escape matcher if String === matcher
-
refute matcher =~ obj, msg
-
end
-
-
##
-
# Fails if +obj+ is nil.
-
-
1
def refute_nil obj, msg = nil
-
msg = message(msg) { "Expected #{mu_pp(obj)} to not be nil" }
-
refute obj.nil?, msg
-
end
-
-
##
-
# Fails if +o1+ is not +op+ +o2+. Eg:
-
#
-
# refute_operator 1, :>, 2 #=> pass
-
# refute_operator 1, :<, 2 #=> fail
-
-
1
def refute_operator o1, op, o2 = UNDEFINED, msg = nil
-
return refute_predicate o1, op, msg if UNDEFINED == o2
-
msg = message(msg) { "Expected #{mu_pp(o1)} to not be #{op} #{mu_pp(o2)}"}
-
refute o1.__send__(op, o2), msg
-
end
-
-
##
-
# For testing with predicates.
-
#
-
# refute_predicate str, :empty?
-
#
-
# This is really meant for specs and is front-ended by refute_operator:
-
#
-
# str.wont_be :empty?
-
-
1
def refute_predicate o1, op, msg = nil
-
msg = message(msg) { "Expected #{mu_pp(o1)} to not be #{op}" }
-
refute o1.__send__(op), msg
-
end
-
-
##
-
# Fails if +obj+ responds to the message +meth+.
-
-
1
def refute_respond_to obj, meth, msg = nil
-
msg = message(msg) { "Expected #{mu_pp(obj)} to not respond to #{meth}" }
-
-
refute obj.respond_to?(meth), msg
-
end
-
-
##
-
# Fails if +exp+ is the same (by object identity) as +act+.
-
-
1
def refute_same exp, act, msg = nil
-
msg = message(msg) {
-
data = [mu_pp(act), act.object_id, mu_pp(exp), exp.object_id]
-
"Expected %s (oid=%d) to not be the same as %s (oid=%d)" % data
-
}
-
refute exp.equal?(act), msg
-
end
-
-
##
-
# Skips the current run. If run in verbose-mode, the skipped run
-
# gets listed at the end of the run but doesn't cause a failure
-
# exit code.
-
-
1
def skip msg = nil, bt = caller
-
msg ||= "Skipped, no message given"
-
@skip = true
-
raise Minitest::Skip, msg, bt
-
end
-
-
##
-
# Was this testcase skipped? Meant for #teardown.
-
-
1
def skipped?
-
defined?(@skip) and @skip
-
end
-
end
-
end
-
1
module Minitest
-
1
module Parallel
-
1
class Executor
-
1
attr_reader :size
-
-
1
def initialize size
-
1
@size = size
-
1
@queue = Queue.new
-
1
@pool = size.times.map {
-
2
Thread.new(@queue) do |queue|
-
2
Thread.current.abort_on_exception = true
-
2
while job = queue.pop
-
klass, method, reporter = job
-
result = Minitest.run_one_method klass, method
-
reporter.synchronize { reporter.record result }
-
end
-
end
-
}
-
end
-
-
1
def << work; @queue << work; end
-
-
1
def shutdown
-
size.times { @queue << nil }
-
@pool.each(&:join)
-
end
-
end
-
-
1
module Test
-
1
def _synchronize; Test.io_lock.synchronize { yield }; end
-
-
1
module ClassMethods
-
1
def run_one_method klass, method_name, reporter
-
Minitest.parallel_executor << [klass, method_name, reporter]
-
end
-
1
def test_order; :parallel; end
-
end
-
end
-
end
-
end
-
1
require "minitest" unless defined? Minitest::Runnable
-
-
1
module Minitest
-
##
-
# Subclass Test to create your own tests. Typically you'll want a
-
# Test subclass per implementation class.
-
#
-
# See Minitest::Assertions
-
-
1
class Test < Runnable
-
1
require "minitest/assertions"
-
1
include Minitest::Assertions
-
-
1
PASSTHROUGH_EXCEPTIONS = [NoMemoryError, SignalException, # :nodoc:
-
Interrupt, SystemExit]
-
-
2
class << self; attr_accessor :io_lock; end
-
1
self.io_lock = Mutex.new
-
-
##
-
# Call this at the top of your tests when you absolutely
-
# positively need to have ordered tests. In doing so, you're
-
# admitting that you suck and your tests are weak.
-
-
1
def self.i_suck_and_my_tests_are_order_dependent!
-
1
class << self
-
1
undef_method :test_order if method_defined? :test_order
-
1
define_method :test_order do :alpha end
-
end
-
end
-
-
##
-
# Make diffs for this Test use #pretty_inspect so that diff
-
# in assert_equal can have more details. NOTE: this is much slower
-
# than the regular inspect but much more usable for complex
-
# objects.
-
-
1
def self.make_my_diffs_pretty!
-
require "pp"
-
-
define_method :mu_pp do |o|
-
o.pretty_inspect
-
end
-
end
-
-
##
-
# Call this at the top of your tests when you want to run your
-
# tests in parallel. In doing so, you're admitting that you rule
-
# and your tests are awesome.
-
-
1
def self.parallelize_me!
-
include Minitest::Parallel::Test
-
extend Minitest::Parallel::Test::ClassMethods
-
end
-
-
##
-
# Returns all instance methods starting with "test_". Based on
-
# #test_order, the methods are either sorted, randomized
-
# (default), or run in parallel.
-
-
1
def self.runnable_methods
-
methods = methods_matching(/^test_/)
-
-
case self.test_order
-
when :random, :parallel then
-
max = methods.size
-
methods.sort.sort_by { rand max }
-
when :alpha, :sorted then
-
methods.sort
-
else
-
raise "Unknown test_order: #{self.test_order.inspect}"
-
end
-
end
-
-
##
-
# Defines the order to run tests (:random by default). Override
-
# this or use a convenience method to change it for your tests.
-
-
1
def self.test_order
-
:random
-
end
-
-
##
-
# The time it took to run this test.
-
-
1
attr_accessor :time
-
-
1
def marshal_dump # :nodoc:
-
super << self.time
-
end
-
-
1
def marshal_load ary # :nodoc:
-
self.time = ary.pop
-
super
-
end
-
-
1
TEARDOWN_METHODS = %w{ before_teardown teardown after_teardown } # :nodoc:
-
-
##
-
# Runs a single test with setup/teardown hooks.
-
-
1
def run
-
with_info_handler do
-
time_it do
-
capture_exceptions do
-
before_setup; setup; after_setup
-
-
self.send self.name
-
end
-
-
TEARDOWN_METHODS.each do |hook|
-
capture_exceptions do
-
self.send hook
-
end
-
end
-
end
-
end
-
-
self # per contract
-
end
-
-
##
-
# Provides before/after hooks for setup and teardown. These are
-
# meant for library writers, NOT for regular test authors. See
-
# #before_setup for an example.
-
-
1
module LifecycleHooks
-
-
##
-
# Runs before every test, before setup. This hook is meant for
-
# libraries to extend minitest. It is not meant to be used by
-
# test developers.
-
#
-
# As a simplistic example:
-
#
-
# module MyMinitestPlugin
-
# def before_setup
-
# super
-
# # ... stuff to do before setup is run
-
# end
-
#
-
# def after_setup
-
# # ... stuff to do after setup is run
-
# super
-
# end
-
#
-
# def before_teardown
-
# super
-
# # ... stuff to do before teardown is run
-
# end
-
#
-
# def after_teardown
-
# # ... stuff to do after teardown is run
-
# super
-
# end
-
# end
-
#
-
# class MiniTest::Test
-
# include MyMinitestPlugin
-
# end
-
-
1
def before_setup; end
-
-
##
-
# Runs before every test. Use this to set up before each test
-
# run.
-
-
1
def setup; end
-
-
##
-
# Runs before every test, after setup. This hook is meant for
-
# libraries to extend minitest. It is not meant to be used by
-
# test developers.
-
#
-
# See #before_setup for an example.
-
-
1
def after_setup; end
-
-
##
-
# Runs after every test, before teardown. This hook is meant for
-
# libraries to extend minitest. It is not meant to be used by
-
# test developers.
-
#
-
# See #before_setup for an example.
-
-
1
def before_teardown; end
-
-
##
-
# Runs after every test. Use this to clean up after each test
-
# run.
-
-
1
def teardown; end
-
-
##
-
# Runs after every test, after teardown. This hook is meant for
-
# libraries to extend minitest. It is not meant to be used by
-
# test developers.
-
#
-
# See #before_setup for an example.
-
-
1
def after_teardown; end
-
end # LifecycleHooks
-
-
1
def capture_exceptions # :nodoc:
-
begin
-
yield
-
rescue *PASSTHROUGH_EXCEPTIONS
-
raise
-
rescue Assertion => e
-
self.failures << e
-
rescue Exception => e
-
self.failures << UnexpectedError.new(e)
-
end
-
end
-
-
##
-
# Did this run error?
-
-
1
def error?
-
self.failures.any? { |f| UnexpectedError === f }
-
end
-
-
##
-
# The location identifier of this test.
-
-
1
def location
-
loc = " [#{self.failure.location}]" unless passed? or error?
-
"#{self.class}##{self.name}#{loc}"
-
end
-
-
##
-
# Did this run pass?
-
#
-
# Note: skipped runs are not considered passing, but they don't
-
# cause the process to exit non-zero.
-
-
1
def passed?
-
not self.failure
-
end
-
-
##
-
# Returns ".", "F", or "E" based on the result of the run.
-
-
1
def result_code
-
self.failure and self.failure.result_code or "."
-
end
-
-
##
-
# Was this run skipped?
-
-
1
def skipped?
-
self.failure and Skip === self.failure
-
end
-
-
1
def time_it # :nodoc:
-
t0 = Time.now
-
-
yield
-
ensure
-
self.time = Time.now - t0
-
end
-
-
1
def to_s # :nodoc:
-
return location if passed? and not skipped?
-
-
failures.map { |failure|
-
"#{failure.result_label}:\n#{self.location}:\n#{failure.message}\n"
-
}.join "\n"
-
end
-
-
1
def with_info_handler &block # :nodoc:
-
t0 = Time.now
-
-
handler = lambda do
-
warn "\nCurrent: %s#%s %.2fs" % [self.class, self.name, Time.now - t0]
-
end
-
-
self.class.on_signal "INFO", handler, &block
-
end
-
-
1
include LifecycleHooks
-
1
include Guard
-
1
extend Guard
-
end # Test
-
end
-
-
1
require "minitest/unit" unless defined?(MiniTest) # compatibility layer only
-
# :stopdoc:
-
-
1
unless defined?(Minitest) then
-
# all of this crap is just to avoid circular requires and is only
-
# needed if a user requires "minitest/unit" directly instead of
-
# "minitest/autorun", so we also warn
-
-
from = caller.reject { |s| s =~ /rubygems/ }.join("\n ")
-
warn "Warning: you should require 'minitest/autorun' instead."
-
warn %(Warning: or add 'gem "minitest"' before 'require "minitest/autorun"')
-
warn "From:\n #{from}"
-
-
module Minitest; end
-
MiniTest = Minitest # prevents minitest.rb from requiring back to us
-
require "minitest"
-
end
-
-
1
MiniTest = Minitest unless defined?(MiniTest)
-
-
1
module Minitest
-
1
class Unit
-
1
VERSION = Minitest::VERSION
-
1
class TestCase < Minitest::Test
-
1
def self.inherited klass # :nodoc:
-
from = caller.first
-
warn "MiniTest::Unit::TestCase is now Minitest::Test. From #{from}"
-
super
-
end
-
end
-
-
1
def self.autorun # :nodoc:
-
from = caller.first
-
warn "MiniTest::Unit.autorun is now Minitest.autorun. From #{from}"
-
Minitest.autorun
-
end
-
-
1
def self.after_tests(&b)
-
from = caller.first
-
warn "MiniTest::Unit.after_tests is now Minitest.after_run. From #{from}"
-
Minitest.after_run(&b)
-
end
-
end
-
end
-
-
# :startdoc:
-
1
module Momentjs
-
1
module Rails
-
1
class Engine < ::Rails::Engine
-
# Get rails to add app, lib, vendor to load path
-
end
-
end
-
end
-
-
1
require 'singleton'
-
1
require 'multi_json/options'
-
-
1
module MultiJson
-
1
class Adapter
-
1
extend Options
-
1
include Singleton
-
1
class << self
-
-
1
def defaults(action, value)
-
2
metaclass = class << self; self; end
-
-
1
metaclass.instance_eval do
-
2
define_method("default_#{action}_options"){ value }
-
end
-
end
-
-
1
def load(string, options={})
-
1
raise self::ParseError if blank?(string)
-
1
instance.load(string, load_options(options).merge(MultiJson.load_options(options)).merge!(options))
-
end
-
-
1
def dump(object, options={})
-
instance.dump(object, dump_options(options).merge(MultiJson.dump_options(options)).merge!(options))
-
end
-
-
1
private
-
-
1
def blank?(input)
-
1
input.nil? || /\A\s*\z/ === input
-
rescue ArgumentError # invalid byte sequence in UTF-8
-
false
-
end
-
-
end
-
end
-
end
-
1
require 'multi_json/adapter'
-
-
1
module MultiJson
-
1
module Adapters
-
1
class JsonCommon < Adapter
-
1
defaults :load, :create_additions => false, :quirks_mode => true
-
-
1
def load(string, options={})
-
1
string = string.read if string.respond_to?(:read)
-
-
1
if string.respond_to?(:force_encoding)
-
1
string = string.dup.force_encoding(::Encoding::ASCII_8BIT)
-
end
-
-
1
options[:symbolize_names] = true if options.delete(:symbolize_keys)
-
1
::JSON.parse(string, options)
-
end
-
-
1
def dump(object, options={})
-
options.merge!(::JSON::PRETTY_STATE_PROTOTYPE.to_h) if options.delete(:pretty)
-
object.to_json(options)
-
end
-
end
-
end
-
end
-
1
require 'json/ext'
-
1
require 'multi_json/adapters/json_common'
-
-
1
module MultiJson
-
1
module Adapters
-
# Use the JSON gem to dump/load.
-
1
class JsonGem < JsonCommon
-
1
ParseError = ::JSON::ParserError
-
end
-
end
-
end
-
1
require 'orm_adapter/base'
-
1
require 'orm_adapter/to_adapter'
-
1
require 'orm_adapter/version'
-
-
1
module OrmAdapter
-
# A collection of registered adapters
-
1
def self.adapters
-
1
@@adapters ||= []
-
end
-
end
-
-
1
require 'orm_adapter/adapters/active_record' if defined?(ActiveRecord::Base)
-
1
require 'orm_adapter/adapters/data_mapper' if defined?(DataMapper::Resource)
-
1
require 'orm_adapter/adapters/mongoid' if defined?(Mongoid::Document)
-
1
require 'orm_adapter/adapters/mongo_mapper' if defined?(MongoMapper::Document)
-
1
require 'active_record'
-
-
1
module OrmAdapter
-
1
class ActiveRecord < Base
-
# Return list of column/property names
-
1
def column_names
-
klass.column_names
-
end
-
-
# @see OrmAdapter::Base#get!
-
1
def get!(id)
-
klass.find(wrap_key(id))
-
end
-
-
# @see OrmAdapter::Base#get
-
1
def get(id)
-
klass.where(klass.primary_key => wrap_key(id)).first
-
end
-
-
# @see OrmAdapter::Base#find_first
-
1
def find_first(options = {})
-
construct_relation(klass, options).first
-
end
-
-
# @see OrmAdapter::Base#find_all
-
1
def find_all(options = {})
-
construct_relation(klass, options)
-
end
-
-
# @see OrmAdapter::Base#create!
-
1
def create!(attributes = {})
-
klass.create!(attributes)
-
end
-
-
# @see OrmAdapter::Base#destroy
-
1
def destroy(object)
-
object.destroy && true if valid_object?(object)
-
end
-
-
1
protected
-
1
def construct_relation(relation, options)
-
conditions, order, limit, offset = extract_conditions!(options)
-
-
relation = relation.where(conditions_to_fields(conditions))
-
relation = relation.order(order_clause(order)) if order.any?
-
relation = relation.limit(limit) if limit
-
relation = relation.offset(offset) if offset
-
-
relation
-
end
-
-
# Introspects the klass to convert and objects in conditions into foreign key and type fields
-
1
def conditions_to_fields(conditions)
-
fields = {}
-
conditions.each do |key, value|
-
if value.is_a?(::ActiveRecord::Base) && (assoc = klass.reflect_on_association(key.to_sym)) && assoc.belongs_to?
-
-
if ::ActiveRecord::VERSION::STRING < "3.1"
-
fields[assoc.primary_key_name] = value.send(value.class.primary_key)
-
fields[assoc.options[:foreign_type]] = value.class.base_class.name.to_s if assoc.options[:polymorphic]
-
else # >= 3.1
-
fields[assoc.foreign_key] = value.send(value.class.primary_key)
-
fields[assoc.foreign_type] = value.class.base_class.name.to_s if assoc.options[:polymorphic]
-
end
-
-
else
-
fields[key] = value
-
end
-
end
-
fields
-
end
-
-
1
def order_clause(order)
-
order.map {|pair| "#{pair[0]} #{pair[1]}"}.join(",")
-
end
-
end
-
end
-
-
1
ActiveSupport.on_load(:active_record) do
-
1
extend ::OrmAdapter::ToAdapter
-
1
self::OrmAdapter = ::OrmAdapter::ActiveRecord
-
end
-
1
module OrmAdapter
-
1
class Base
-
1
attr_reader :klass
-
-
# Your ORM adapter needs to inherit from this Base class and its adapter
-
# will be registered. To create an adapter you should create an inner
-
# constant "OrmAdapter" e.g. ActiveRecord::Base::OrmAdapter
-
#
-
# @see orm_adapters/active_record
-
# @see orm_adapters/datamapper
-
# @see orm_adapters/mongoid
-
1
def self.inherited(adapter)
-
1
OrmAdapter.adapters << adapter
-
1
super
-
end
-
-
1
def initialize(klass)
-
@klass = klass
-
end
-
-
# Get a list of column/property/field names
-
1
def column_names
-
raise NotSupportedError
-
end
-
-
# Get an instance by id of the model. Raises an error if a model is not found.
-
# This should comply with ActiveModel#to_key API, i.e.:
-
#
-
# User.to_adapter.get!(@user.to_key) == @user
-
#
-
1
def get!(id)
-
raise NotSupportedError
-
end
-
-
# Get an instance by id of the model. Returns nil if a model is not found.
-
# This should comply with ActiveModel#to_key API, i.e.:
-
#
-
# User.to_adapter.get(@user.to_key) == @user
-
#
-
1
def get(id)
-
raise NotSupportedError
-
end
-
-
# Find the first instance, optionally matching conditions, and specifying order
-
#
-
# You can call with just conditions, providing a hash
-
#
-
# User.to_adapter.find_first :name => "Fred", :age => 23
-
#
-
# Or you can specify :order, and :conditions as keys
-
#
-
# User.to_adapter.find_first :conditions => {:name => "Fred", :age => 23}
-
# User.to_adapter.find_first :order => [:age, :desc]
-
# User.to_adapter.find_first :order => :name, :conditions => {:age => 18}
-
#
-
# When specifying :order, it may be
-
# * a single arg e.g. <tt>:order => :name</tt>
-
# * a single pair with :asc, or :desc as last, e.g. <tt>:order => [:name, :desc]</tt>
-
# * an array of single args or pairs (with :asc or :desc as last), e.g. <tt>:order => [[:name, :asc], [:age, :desc]]</tt>
-
#
-
1
def find_first(options = {})
-
raise NotSupportedError
-
end
-
-
# Find all models, optionally matching conditions, and specifying order
-
# @see OrmAdapter::Base#find_first for how to specify order and conditions
-
1
def find_all(options = {})
-
raise NotSupportedError
-
end
-
-
# Create a model using attributes
-
1
def create!(attributes = {})
-
raise NotSupportedError
-
end
-
-
# Destroy an instance by passing in the instance itself.
-
1
def destroy(object)
-
raise NotSupportedError
-
end
-
-
1
protected
-
-
1
def valid_object?(object)
-
object.class == klass
-
end
-
-
1
def wrap_key(key)
-
key.is_a?(Array) ? key.first : key
-
end
-
-
# given an options hash,
-
# with optional :conditions, :order, :limit and :offset keys,
-
# returns conditions, normalized order, limit and offset
-
1
def extract_conditions!(options = {})
-
order = normalize_order(options.delete(:order))
-
limit = options.delete(:limit)
-
offset = options.delete(:offset)
-
conditions = options.delete(:conditions) || options
-
-
[conditions, order, limit, offset]
-
end
-
-
# given an order argument, returns an array of pairs, with each pair containing the attribute, and :asc or :desc
-
1
def normalize_order(order)
-
order = Array(order)
-
-
if order.length == 2 && !order[0].is_a?(Array) && [:asc, :desc].include?(order[1])
-
order = [order]
-
else
-
order = order.map {|pair| pair.is_a?(Array) ? pair : [pair, :asc] }
-
end
-
-
order.each do |pair|
-
pair.length == 2 or raise ArgumentError, "each order clause must be a pair (unknown clause #{pair.inspect})"
-
[:asc, :desc].include?(pair[1]) or raise ArgumentError, "order must be specified with :asc or :desc (unknown key #{pair[1].inspect})"
-
end
-
-
order
-
end
-
end
-
-
1
class NotSupportedError < NotImplementedError
-
1
def to_s
-
"method not supported by this orm adapter"
-
end
-
end
-
end
-
1
module OrmAdapter
-
# Extend into a class that has an OrmAdapter
-
1
module ToAdapter
-
1
def to_adapter
-
@_to_adapter ||= self::OrmAdapter.new(self)
-
end
-
end
-
end
-
1
module OrmAdapter
-
1
VERSION = "0.5.0"
-
end
-
#!/usr/bin/env ruby
-
-
1
begin
-
1
require 'pg_ext'
-
rescue LoadError
-
# If it's a Windows binary gem, try the <major>.<minor> subdirectory
-
if RUBY_PLATFORM =~/(mswin|mingw)/i
-
major_minor = RUBY_VERSION[ /^(\d+\.\d+)/ ] or
-
raise "Oops, can't extract the major/minor version from #{RUBY_VERSION.dump}"
-
require "#{major_minor}/pg_ext"
-
else
-
raise
-
end
-
-
end
-
-
-
# The top-level PG namespace.
-
1
module PG
-
-
# Library version
-
1
VERSION = '0.17.1'
-
-
# VCS revision
-
1
REVISION = %q$Revision: 22d57e3a2b37 $
-
-
1
class NotAllCopyDataRetrieved < PG::Error
-
end
-
-
### Get the PG library version. If +include_buildnum+ is +true+, include the build ID.
-
1
def self::version_string( include_buildnum=false )
-
vstring = "%s %s" % [ self.name, VERSION ]
-
vstring << " (build %s)" % [ REVISION[/: ([[:xdigit:]]+)/, 1] || '0' ] if include_buildnum
-
return vstring
-
end
-
-
-
### Convenience alias for PG::Connection.new.
-
1
def self::connect( *args )
-
return PG::Connection.new( *args )
-
end
-
-
-
1
require 'pg/exceptions'
-
1
require 'pg/constants'
-
1
require 'pg/connection'
-
1
require 'pg/result'
-
-
end # module PG
-
-
-
# Backward-compatible aliase
-
1
PGError = PG::Error
-
-
#!/usr/bin/env ruby
-
-
1
require 'pg' unless defined?( PG )
-
-
# The PostgreSQL connection class. The interface for this class is based on
-
# {libpq}[http://www.postgresql.org/docs/9.2/interactive/libpq.html], the C
-
# application programmer's interface to PostgreSQL. Some familiarity with libpq
-
# is recommended, but not necessary.
-
#
-
# For example, to send query to the database on the localhost:
-
#
-
# require 'pg'
-
# conn = PG::Connection.open(:dbname => 'test')
-
# res = conn.exec_params('SELECT $1 AS a, $2 AS b, $3 AS c', [1, 2, nil])
-
# # Equivalent to:
-
# # res = conn.exec('SELECT 1 AS a, 2 AS b, NULL AS c')
-
#
-
# See the PG::Result class for information on working with the results of a query.
-
#
-
1
class PG::Connection
-
-
# The order the options are passed to the ::connect method.
-
1
CONNECT_ARGUMENT_ORDER = %w[host port options tty dbname user password]
-
-
-
### Quote the given +value+ for use in a connection-parameter string.
-
1
def self::quote_connstr( value )
-
3
return "'" + value.to_s.gsub( /[\\']/ ) {|m| '\\' + m } + "'"
-
end
-
-
-
### Parse the connection +args+ into a connection-parameter string. See PG::Connection.new
-
### for valid arguments.
-
1
def self::parse_connect_args( *args )
-
1
return '' if args.empty?
-
-
# This will be swapped soon for code that makes options like those required for
-
# PQconnectdbParams()/PQconnectStartParams(). For now, stick to an options string for
-
# PQconnectdb()/PQconnectStart().
-
-
# Parameter 'fallback_application_name' was introduced in PostgreSQL 9.0
-
# together with PQescapeLiteral().
-
37
if PG::Connection.instance_methods.find{|m| m.to_sym == :escape_literal }
-
2
appname = $0.sub(/^(.{30}).{4,}(.{30})$/){ $1+"..."+$2 }
-
1
appname = PG::Connection.quote_connstr( appname )
-
1
connopts = ["fallback_application_name=#{appname}"]
-
else
-
connopts = []
-
end
-
-
# Handle an options hash first
-
1
if args.last.is_a?( Hash )
-
1
opthash = args.pop
-
1
opthash.each do |key, val|
-
2
connopts.push( "%s=%s" % [key, PG::Connection.quote_connstr(val)] )
-
end
-
end
-
-
# Option string style
-
1
if args.length == 1 && args.first.to_s.index( '=' )
-
connopts.unshift( args.first )
-
-
# Append positional parameters
-
else
-
1
args.each_with_index do |val, i|
-
next unless val # Skip nil placeholders
-
-
key = CONNECT_ARGUMENT_ORDER[ i ] or
-
raise ArgumentError, "Extra positional parameter %d: %p" % [ i+1, val ]
-
connopts.push( "%s=%s" % [key, PG::Connection.quote_connstr(val.to_s)] )
-
end
-
end
-
-
1
return connopts.join(' ')
-
end
-
-
# call-seq:
-
# conn.copy_data( sql ) {|sql_result| ... } -> PG::Result
-
#
-
# Execute a copy process for transfering data to or from the server.
-
#
-
# This issues the SQL COPY command via #exec. The response to this
-
# (if there is no error in the command) is a PG::Result object that
-
# is passed to the block, bearing a status code of PGRES_COPY_OUT or
-
# PGRES_COPY_IN (depending on the specified copy direction).
-
# The application should then use #put_copy_data or #get_copy_data
-
# to receive or transmit data rows and should return from the block
-
# when finished.
-
#
-
# #copy_data returns another PG::Result object when the data transfer
-
# is complete. An exception is raised if some problem was encountered,
-
# so it isn't required to make use of any of them.
-
# At this point further SQL commands can be issued via #exec.
-
# (It is not possible to execute other SQL commands using the same
-
# connection while the COPY operation is in progress.)
-
#
-
# This method ensures, that the copy process is properly terminated
-
# in case of client side or server side failures. Therefore, in case
-
# of blocking mode of operation, #copy_data is preferred to raw calls
-
# of #put_copy_data, #get_copy_data and #put_copy_end.
-
#
-
# Example with CSV input format:
-
# conn.exec "create table my_table (a text,b text,c text,d text,e text)"
-
# conn.copy_data "COPY my_table FROM STDOUT CSV" do
-
# conn.put_copy_data "some,csv,data,to,copy\n"
-
# conn.put_copy_data "more,csv,data,to,copy\n"
-
# end
-
# This creates +my_table+ and inserts two rows.
-
#
-
# Example with CSV output format:
-
# conn.copy_data "COPY my_table TO STDOUT CSV" do
-
# while row=conn.get_copy_data
-
# p row
-
# end
-
# end
-
# This prints all rows of +my_table+ to stdout:
-
# "some,csv,data,to,copy\n"
-
# "more,csv,data,to,copy\n"
-
1
def copy_data( sql )
-
res = exec( sql )
-
-
case res.result_status
-
when PGRES_COPY_IN
-
begin
-
yield res
-
rescue Exception => err
-
errmsg = "%s while copy data: %s" % [ err.class.name, err.message ]
-
put_copy_end( errmsg )
-
get_result
-
raise
-
else
-
put_copy_end
-
get_last_result
-
end
-
-
when PGRES_COPY_OUT
-
begin
-
yield res
-
rescue Exception => err
-
cancel
-
while get_copy_data
-
end
-
while get_result
-
end
-
raise
-
else
-
res = get_last_result
-
if res.result_status != PGRES_COMMAND_OK
-
while get_copy_data
-
end
-
while get_result
-
end
-
raise PG::NotAllCopyDataRetrieved, "Not all COPY data retrieved"
-
end
-
res
-
end
-
-
else
-
raise ArgumentError, "SQL command is no COPY statement: #{sql}"
-
end
-
end
-
-
# Backward-compatibility aliases for stuff that's moved into PG.
-
1
class << self
-
1
define_method( :isthreadsafe, &PG.method(:isthreadsafe) )
-
end
-
-
-
### Returns an array of Hashes with connection defaults. See ::conndefaults
-
### for details.
-
1
def conndefaults
-
return self.class.conndefaults
-
end
-
-
end # class PG::Connection
-
-
# Backward-compatible alias
-
1
PGconn = PG::Connection
-
-
#!/usr/bin/env ruby
-
-
1
require 'pg' unless defined?( PG )
-
-
-
1
module PG::Constants
-
-
# Most of these are defined in the extension.
-
-
end # module PG::Constants
-
-
#!/usr/bin/env ruby
-
-
1
require 'pg' unless defined?( PG )
-
-
-
1
module PG
-
-
1
class Error < StandardError; end
-
-
end # module PG
-
-
#!/usr/bin/env ruby
-
-
1
require 'pg' unless defined?( PG )
-
-
-
1
class PG::Result
-
-
### Returns all tuples as an array of arrays
-
1
def values
-
2
return enum_for(:each_row).to_a
-
end
-
-
end # class PG::Result
-
-
# Backward-compatible alias
-
1
PGresult = PG::Result
-
# Copyright (C) 2007, 2008, 2009, 2010 Christian Neukirchen <purl.org/net/chneukirchen>
-
#
-
# Rack is freely distributable under the terms of an MIT-style license.
-
# See COPYING or http://www.opensource.org/licenses/mit-license.php.
-
-
# The Rack main module, serving as a namespace for all core Rack
-
# modules and classes.
-
#
-
# All modules meant for use in your application are <tt>autoload</tt>ed here,
-
# so it should be enough just to <tt>require rack.rb</tt> in your code.
-
-
1
module Rack
-
# The Rack protocol version number implemented.
-
1
VERSION = [1,2]
-
-
# Return the Rack protocol version as a dotted string.
-
1
def self.version
-
VERSION.join(".")
-
end
-
-
# Return the Rack release as a dotted string.
-
1
def self.release
-
"1.5"
-
end
-
-
1
autoload :Builder, "rack/builder"
-
1
autoload :BodyProxy, "rack/body_proxy"
-
1
autoload :Cascade, "rack/cascade"
-
1
autoload :Chunked, "rack/chunked"
-
1
autoload :CommonLogger, "rack/commonlogger"
-
1
autoload :ConditionalGet, "rack/conditionalget"
-
1
autoload :Config, "rack/config"
-
1
autoload :ContentLength, "rack/content_length"
-
1
autoload :ContentType, "rack/content_type"
-
1
autoload :ETag, "rack/etag"
-
1
autoload :File, "rack/file"
-
1
autoload :Deflater, "rack/deflater"
-
1
autoload :Directory, "rack/directory"
-
1
autoload :ForwardRequest, "rack/recursive"
-
1
autoload :Handler, "rack/handler"
-
1
autoload :Head, "rack/head"
-
1
autoload :Lint, "rack/lint"
-
1
autoload :Lock, "rack/lock"
-
1
autoload :Logger, "rack/logger"
-
1
autoload :MethodOverride, "rack/methodoverride"
-
1
autoload :Mime, "rack/mime"
-
1
autoload :NullLogger, "rack/nulllogger"
-
1
autoload :Recursive, "rack/recursive"
-
1
autoload :Reloader, "rack/reloader"
-
1
autoload :Runtime, "rack/runtime"
-
1
autoload :Sendfile, "rack/sendfile"
-
1
autoload :Server, "rack/server"
-
1
autoload :ShowExceptions, "rack/showexceptions"
-
1
autoload :ShowStatus, "rack/showstatus"
-
1
autoload :Static, "rack/static"
-
1
autoload :URLMap, "rack/urlmap"
-
1
autoload :Utils, "rack/utils"
-
1
autoload :Multipart, "rack/multipart"
-
-
1
autoload :MockRequest, "rack/mock"
-
1
autoload :MockResponse, "rack/mock"
-
-
1
autoload :Request, "rack/request"
-
1
autoload :Response, "rack/response"
-
-
1
module Auth
-
1
autoload :Basic, "rack/auth/basic"
-
1
autoload :AbstractRequest, "rack/auth/abstract/request"
-
1
autoload :AbstractHandler, "rack/auth/abstract/handler"
-
1
module Digest
-
1
autoload :MD5, "rack/auth/digest/md5"
-
1
autoload :Nonce, "rack/auth/digest/nonce"
-
1
autoload :Params, "rack/auth/digest/params"
-
1
autoload :Request, "rack/auth/digest/request"
-
end
-
end
-
-
1
module Session
-
1
autoload :Cookie, "rack/session/cookie"
-
1
autoload :Pool, "rack/session/pool"
-
1
autoload :Memcache, "rack/session/memcache"
-
end
-
-
1
module Utils
-
1
autoload :OkJson, "rack/utils/okjson"
-
end
-
end
-
1
module Rack
-
1
class BodyProxy
-
1
def initialize(body, &block)
-
@body, @block, @closed = body, block, false
-
end
-
-
1
def respond_to?(*args)
-
return false if args.first.to_s =~ /^to_ary$/
-
super or @body.respond_to?(*args)
-
end
-
-
1
def close
-
return if @closed
-
@closed = true
-
begin
-
@body.close if @body.respond_to? :close
-
ensure
-
@block.call
-
end
-
end
-
-
1
def closed?
-
@closed
-
end
-
-
# N.B. This method is a special case to address the bug described by #434.
-
# We are applying this special case for #each only. Future bugs of this
-
# class will be handled by requesting users to patch their ruby
-
# implementation, to save adding too many methods in this class.
-
1
def each(*args, &block)
-
@body.each(*args, &block)
-
end
-
-
1
def method_missing(*args, &block)
-
super if args.first.to_s =~ /^to_ary$/
-
@body.__send__(*args, &block)
-
end
-
end
-
end
-
1
require 'rack/utils'
-
-
1
module Rack
-
-
# Middleware that applies chunked transfer encoding to response bodies
-
# when the response does not include a Content-Length header.
-
1
class Chunked
-
1
include Rack::Utils
-
-
# A body wrapper that emits chunked responses
-
1
class Body
-
1
TERM = "\r\n"
-
1
TAIL = "0#{TERM}#{TERM}"
-
-
1
include Rack::Utils
-
-
1
def initialize(body)
-
@body = body
-
end
-
-
1
def each
-
term = TERM
-
@body.each do |chunk|
-
size = bytesize(chunk)
-
next if size == 0
-
-
chunk = chunk.dup.force_encoding(Encoding::BINARY) if chunk.respond_to?(:force_encoding)
-
yield [size.to_s(16), term, chunk, term].join
-
end
-
yield TAIL
-
end
-
-
1
def close
-
@body.close if @body.respond_to?(:close)
-
end
-
end
-
-
1
def initialize(app)
-
@app = app
-
end
-
-
1
def call(env)
-
status, headers, body = @app.call(env)
-
headers = HeaderHash.new(headers)
-
-
if env['HTTP_VERSION'] == 'HTTP/1.0' ||
-
STATUS_WITH_NO_ENTITY_BODY.include?(status) ||
-
headers['Content-Length'] ||
-
headers['Transfer-Encoding']
-
[status, headers, body]
-
else
-
headers.delete('Content-Length')
-
headers['Transfer-Encoding'] = 'chunked'
-
[status, headers, Body.new(body)]
-
end
-
end
-
end
-
end
-
1
require 'rack/utils'
-
-
1
module Rack
-
-
# Middleware that enables conditional GET using If-None-Match and
-
# If-Modified-Since. The application should set either or both of the
-
# Last-Modified or Etag response headers according to RFC 2616. When
-
# either of the conditions is met, the response body is set to be zero
-
# length and the response status is set to 304 Not Modified.
-
#
-
# Applications that defer response body generation until the body's each
-
# message is received will avoid response body generation completely when
-
# a conditional GET matches.
-
#
-
# Adapted from Michael Klishin's Merb implementation:
-
# https://github.com/wycats/merb/blob/master/merb-core/lib/merb-core/rack/middleware/conditional_get.rb
-
1
class ConditionalGet
-
1
def initialize(app)
-
1
@app = app
-
end
-
-
1
def call(env)
-
case env['REQUEST_METHOD']
-
when "GET", "HEAD"
-
status, headers, body = @app.call(env)
-
headers = Utils::HeaderHash.new(headers)
-
if status == 200 && fresh?(env, headers)
-
status = 304
-
headers.delete('Content-Type')
-
headers.delete('Content-Length')
-
body = []
-
end
-
[status, headers, body]
-
else
-
@app.call(env)
-
end
-
end
-
-
1
private
-
-
1
def fresh?(env, headers)
-
modified_since = env['HTTP_IF_MODIFIED_SINCE']
-
none_match = env['HTTP_IF_NONE_MATCH']
-
-
return false unless modified_since || none_match
-
-
success = true
-
success &&= modified_since?(to_rfc2822(modified_since), headers) if modified_since
-
success &&= etag_matches?(none_match, headers) if none_match
-
success
-
end
-
-
1
def etag_matches?(none_match, headers)
-
etag = headers['ETag'] and etag == none_match
-
end
-
-
1
def modified_since?(modified_since, headers)
-
last_modified = to_rfc2822(headers['Last-Modified']) and
-
modified_since and
-
modified_since >= last_modified
-
end
-
-
1
def to_rfc2822(since)
-
Time.rfc2822(since) rescue nil
-
end
-
end
-
end
-
1
require 'digest/md5'
-
-
1
module Rack
-
# Automatically sets the ETag header on all String bodies.
-
#
-
# The ETag header is skipped if ETag or Last-Modified headers are sent or if
-
# a sendfile body (body.responds_to :to_path) is given (since such cases
-
# should be handled by apache/nginx).
-
#
-
# On initialization, you can pass two parameters: a Cache-Control directive
-
# used when Etag is absent and a directive when it is present. The first
-
# defaults to nil, while the second defaults to "max-age=0, private, must-revalidate"
-
1
class ETag
-
1
DEFAULT_CACHE_CONTROL = "max-age=0, private, must-revalidate".freeze
-
-
1
def initialize(app, no_cache_control = nil, cache_control = DEFAULT_CACHE_CONTROL)
-
1
@app = app
-
1
@cache_control = cache_control
-
1
@no_cache_control = no_cache_control
-
end
-
-
1
def call(env)
-
status, headers, body = @app.call(env)
-
-
if etag_status?(status) && etag_body?(body) && !skip_caching?(headers)
-
digest, body = digest_body(body)
-
headers['ETag'] = %("#{digest}") if digest
-
end
-
-
unless headers['Cache-Control']
-
if digest
-
headers['Cache-Control'] = @cache_control if @cache_control
-
else
-
headers['Cache-Control'] = @no_cache_control if @no_cache_control
-
end
-
end
-
-
[status, headers, body]
-
end
-
-
1
private
-
-
1
def etag_status?(status)
-
status == 200 || status == 201
-
end
-
-
1
def etag_body?(body)
-
!body.respond_to?(:to_path)
-
end
-
-
1
def skip_caching?(headers)
-
(headers['Cache-Control'] && headers['Cache-Control'].include?('no-cache')) ||
-
headers.key?('ETag') || headers.key?('Last-Modified')
-
end
-
-
1
def digest_body(body)
-
parts = []
-
body.each { |part| parts << part }
-
string_body = parts.join
-
digest = Digest::MD5.hexdigest(string_body) unless string_body.empty?
-
[digest, parts]
-
end
-
end
-
end
-
1
require 'time'
-
1
require 'rack/utils'
-
1
require 'rack/mime'
-
-
1
module Rack
-
# Rack::File serves files below the +root+ directory given, according to the
-
# path info of the Rack request.
-
# e.g. when Rack::File.new("/etc") is used, you can access 'passwd' file
-
# as http://localhost:9292/passwd
-
#
-
# Handlers can detect if bodies are a Rack::File, and use mechanisms
-
# like sendfile on the +path+.
-
-
1
class File
-
1
SEPS = Regexp.union(*[::File::SEPARATOR, ::File::ALT_SEPARATOR].compact)
-
1
ALLOWED_VERBS = %w[GET HEAD]
-
-
1
attr_accessor :root
-
1
attr_accessor :path
-
1
attr_accessor :cache_control
-
-
1
alias :to_path :path
-
-
1
def initialize(root, headers={}, default_mime = 'text/plain')
-
1
@root = root
-
1
@headers = headers
-
1
@default_mime = default_mime
-
end
-
-
1
def call(env)
-
dup._call(env)
-
end
-
-
1
F = ::File
-
-
1
def _call(env)
-
unless ALLOWED_VERBS.include? env["REQUEST_METHOD"]
-
return fail(405, "Method Not Allowed")
-
end
-
-
path_info = Utils.unescape(env["PATH_INFO"])
-
parts = path_info.split SEPS
-
-
clean = []
-
-
parts.each do |part|
-
next if part.empty? || part == '.'
-
part == '..' ? clean.pop : clean << part
-
end
-
-
@path = F.join(@root, *clean)
-
-
available = begin
-
F.file?(@path) && F.readable?(@path)
-
rescue SystemCallError
-
false
-
end
-
-
if available
-
serving(env)
-
else
-
fail(404, "File not found: #{path_info}")
-
end
-
end
-
-
1
def serving(env)
-
last_modified = F.mtime(@path).httpdate
-
return [304, {}, []] if env['HTTP_IF_MODIFIED_SINCE'] == last_modified
-
-
headers = { "Last-Modified" => last_modified }
-
mime = Mime.mime_type(F.extname(@path), @default_mime)
-
headers["Content-Type"] = mime if mime
-
-
# Set custom headers
-
@headers.each { |field, content| headers[field] = content } if @headers
-
-
response = [ 200, headers, env["REQUEST_METHOD"] == "HEAD" ? [] : self ]
-
-
# NOTE:
-
# We check via File::size? whether this file provides size info
-
# via stat (e.g. /proc files often don't), otherwise we have to
-
# figure it out by reading the whole file into memory.
-
size = F.size?(@path) || Utils.bytesize(F.read(@path))
-
-
ranges = Rack::Utils.byte_ranges(env, size)
-
if ranges.nil? || ranges.length > 1
-
# No ranges, or multiple ranges (which we don't support):
-
# TODO: Support multiple byte-ranges
-
response[0] = 200
-
@range = 0..size-1
-
elsif ranges.empty?
-
# Unsatisfiable. Return error, and file size:
-
response = fail(416, "Byte range unsatisfiable")
-
response[1]["Content-Range"] = "bytes */#{size}"
-
return response
-
else
-
# Partial content:
-
@range = ranges[0]
-
response[0] = 206
-
response[1]["Content-Range"] = "bytes #{@range.begin}-#{@range.end}/#{size}"
-
size = @range.end - @range.begin + 1
-
end
-
-
response[1]["Content-Length"] = size.to_s
-
response
-
end
-
-
1
def each
-
F.open(@path, "rb") do |file|
-
file.seek(@range.begin)
-
remaining_len = @range.end-@range.begin+1
-
while remaining_len > 0
-
part = file.read([8192, remaining_len].min)
-
break unless part
-
remaining_len -= part.length
-
-
yield part
-
end
-
end
-
end
-
-
1
private
-
-
1
def fail(status, body)
-
body += "\n"
-
[
-
status,
-
{
-
"Content-Type" => "text/plain",
-
"Content-Length" => body.size.to_s,
-
"X-Cascade" => "pass"
-
},
-
[body]
-
]
-
end
-
-
end
-
end
-
1
module Rack
-
-
1
class Head
-
# Rack::Head returns an empty body for all HEAD requests. It leaves
-
# all other requests unchanged.
-
1
def initialize(app)
-
1
@app = app
-
end
-
-
1
def call(env)
-
status, headers, body = @app.call(env)
-
-
if env["REQUEST_METHOD"] == "HEAD"
-
body.close if body.respond_to? :close
-
[status, headers, []]
-
else
-
[status, headers, body]
-
end
-
end
-
end
-
-
end
-
1
require 'rack/utils'
-
1
require 'forwardable'
-
-
1
module Rack
-
# Rack::Lint validates your application and the requests and
-
# responses according to the Rack spec.
-
-
1
class Lint
-
1
def initialize(app)
-
@app = app
-
@content_length = nil
-
end
-
-
# :stopdoc:
-
-
1
class LintError < RuntimeError; end
-
1
module Assertion
-
1
def assert(message, &block)
-
unless block.call
-
raise LintError, message
-
end
-
end
-
end
-
1
include Assertion
-
-
## This specification aims to formalize the Rack protocol. You
-
## can (and should) use Rack::Lint to enforce it.
-
##
-
## When you develop middleware, be sure to add a Lint before and
-
## after to catch all mistakes.
-
-
## = Rack applications
-
-
## A Rack application is a Ruby object (not a class) that
-
## responds to +call+.
-
1
def call(env=nil)
-
dup._call(env)
-
end
-
-
1
def _call(env)
-
## It takes exactly one argument, the *environment*
-
assert("No env given") { env }
-
check_env env
-
-
env['rack.input'] = InputWrapper.new(env['rack.input'])
-
env['rack.errors'] = ErrorWrapper.new(env['rack.errors'])
-
-
## and returns an Array of exactly three values:
-
status, headers, @body = @app.call(env)
-
## The *status*,
-
check_status status
-
## the *headers*,
-
check_headers headers
-
-
check_hijack_response headers, env
-
-
## and the *body*.
-
check_content_type status, headers
-
check_content_length status, headers
-
@head_request = env["REQUEST_METHOD"] == "HEAD"
-
[status, headers, self]
-
end
-
-
## == The Environment
-
1
def check_env(env)
-
## The environment must be an instance of Hash that includes
-
## CGI-like headers. The application is free to modify the
-
## environment.
-
assert("env #{env.inspect} is not a Hash, but #{env.class}") {
-
env.kind_of? Hash
-
}
-
-
##
-
## The environment is required to include these variables
-
## (adopted from PEP333), except when they'd be empty, but see
-
## below.
-
-
## <tt>REQUEST_METHOD</tt>:: The HTTP request method, such as
-
## "GET" or "POST". This cannot ever
-
## be an empty string, and so is
-
## always required.
-
-
## <tt>SCRIPT_NAME</tt>:: The initial portion of the request
-
## URL's "path" that corresponds to the
-
## application object, so that the
-
## application knows its virtual
-
## "location". This may be an empty
-
## string, if the application corresponds
-
## to the "root" of the server.
-
-
## <tt>PATH_INFO</tt>:: The remainder of the request URL's
-
## "path", designating the virtual
-
## "location" of the request's target
-
## within the application. This may be an
-
## empty string, if the request URL targets
-
## the application root and does not have a
-
## trailing slash. This value may be
-
## percent-encoded when I originating from
-
## a URL.
-
-
## <tt>QUERY_STRING</tt>:: The portion of the request URL that
-
## follows the <tt>?</tt>, if any. May be
-
## empty, but is always required!
-
-
## <tt>SERVER_NAME</tt>, <tt>SERVER_PORT</tt>:: When combined with <tt>SCRIPT_NAME</tt> and <tt>PATH_INFO</tt>, these variables can be used to complete the URL. Note, however, that <tt>HTTP_HOST</tt>, if present, should be used in preference to <tt>SERVER_NAME</tt> for reconstructing the request URL. <tt>SERVER_NAME</tt> and <tt>SERVER_PORT</tt> can never be empty strings, and so are always required.
-
-
## <tt>HTTP_</tt> Variables:: Variables corresponding to the
-
## client-supplied HTTP request
-
## headers (i.e., variables whose
-
## names begin with <tt>HTTP_</tt>). The
-
## presence or absence of these
-
## variables should correspond with
-
## the presence or absence of the
-
## appropriate HTTP header in the
-
## request. See <a href="https://tools.ietf.org/html/rfc3875#section-4.1.18">
-
## RFC3875 section 4.1.18</a> for specific behavior.
-
-
## In addition to this, the Rack environment must include these
-
## Rack-specific variables:
-
-
## <tt>rack.version</tt>:: The Array representing this version of Rack. See Rack::VERSION, that corresponds to the version of this SPEC.
-
## <tt>rack.url_scheme</tt>:: +http+ or +https+, depending on the request URL.
-
## <tt>rack.input</tt>:: See below, the input stream.
-
## <tt>rack.errors</tt>:: See below, the error stream.
-
## <tt>rack.multithread</tt>:: true if the application object may be simultaneously invoked by another thread in the same process, false otherwise.
-
## <tt>rack.multiprocess</tt>:: true if an equivalent application object may be simultaneously invoked by another process, false otherwise.
-
## <tt>rack.run_once</tt>:: true if the server expects (but does not guarantee!) that the application will only be invoked this one time during the life of its containing process. Normally, this will only be true for a server based on CGI (or something similar).
-
## <tt>rack.hijack?</tt>:: present and true if the server supports connection hijacking. See below, hijacking.
-
## <tt>rack.hijack</tt>:: an object responding to #call that must be called at least once before using rack.hijack_io. It is recommended #call return rack.hijack_io as well as setting it in env if necessary.
-
## <tt>rack.hijack_io</tt>:: if rack.hijack? is true, and rack.hijack has received #call, this will contain an object resembling an IO. See hijacking.
-
##
-
-
## Additional environment specifications have approved to
-
## standardized middleware APIs. None of these are required to
-
## be implemented by the server.
-
-
## <tt>rack.session</tt>:: A hash like interface for storing request session data.
-
## The store must implement:
-
if session = env['rack.session']
-
## store(key, value) (aliased as []=);
-
assert("session #{session.inspect} must respond to store and []=") {
-
session.respond_to?(:store) && session.respond_to?(:[]=)
-
}
-
-
## fetch(key, default = nil) (aliased as []);
-
assert("session #{session.inspect} must respond to fetch and []") {
-
session.respond_to?(:fetch) && session.respond_to?(:[])
-
}
-
-
## delete(key);
-
assert("session #{session.inspect} must respond to delete") {
-
session.respond_to?(:delete)
-
}
-
-
## clear;
-
assert("session #{session.inspect} must respond to clear") {
-
session.respond_to?(:clear)
-
}
-
end
-
-
## <tt>rack.logger</tt>:: A common object interface for logging messages.
-
## The object must implement:
-
if logger = env['rack.logger']
-
## info(message, &block)
-
assert("logger #{logger.inspect} must respond to info") {
-
logger.respond_to?(:info)
-
}
-
-
## debug(message, &block)
-
assert("logger #{logger.inspect} must respond to debug") {
-
logger.respond_to?(:debug)
-
}
-
-
## warn(message, &block)
-
assert("logger #{logger.inspect} must respond to warn") {
-
logger.respond_to?(:warn)
-
}
-
-
## error(message, &block)
-
assert("logger #{logger.inspect} must respond to error") {
-
logger.respond_to?(:error)
-
}
-
-
## fatal(message, &block)
-
assert("logger #{logger.inspect} must respond to fatal") {
-
logger.respond_to?(:fatal)
-
}
-
end
-
-
## The server or the application can store their own data in the
-
## environment, too. The keys must contain at least one dot,
-
## and should be prefixed uniquely. The prefix <tt>rack.</tt>
-
## is reserved for use with the Rack core distribution and other
-
## accepted specifications and must not be used otherwise.
-
##
-
-
%w[REQUEST_METHOD SERVER_NAME SERVER_PORT
-
QUERY_STRING
-
rack.version rack.input rack.errors
-
rack.multithread rack.multiprocess rack.run_once].each { |header|
-
assert("env missing required key #{header}") { env.include? header }
-
}
-
-
## The environment must not contain the keys
-
## <tt>HTTP_CONTENT_TYPE</tt> or <tt>HTTP_CONTENT_LENGTH</tt>
-
## (use the versions without <tt>HTTP_</tt>).
-
%w[HTTP_CONTENT_TYPE HTTP_CONTENT_LENGTH].each { |header|
-
assert("env contains #{header}, must use #{header[5,-1]}") {
-
not env.include? header
-
}
-
}
-
-
## The CGI keys (named without a period) must have String values.
-
env.each { |key, value|
-
next if key.include? "." # Skip extensions
-
assert("env variable #{key} has non-string value #{value.inspect}") {
-
value.kind_of? String
-
}
-
}
-
-
##
-
## There are the following restrictions:
-
-
## * <tt>rack.version</tt> must be an array of Integers.
-
assert("rack.version must be an Array, was #{env["rack.version"].class}") {
-
env["rack.version"].kind_of? Array
-
}
-
## * <tt>rack.url_scheme</tt> must either be +http+ or +https+.
-
assert("rack.url_scheme unknown: #{env["rack.url_scheme"].inspect}") {
-
%w[http https].include? env["rack.url_scheme"]
-
}
-
-
## * There must be a valid input stream in <tt>rack.input</tt>.
-
check_input env["rack.input"]
-
## * There must be a valid error stream in <tt>rack.errors</tt>.
-
check_error env["rack.errors"]
-
## * There may be a valid hijack stream in <tt>rack.hijack_io</tt>
-
check_hijack env
-
-
## * The <tt>REQUEST_METHOD</tt> must be a valid token.
-
assert("REQUEST_METHOD unknown: #{env["REQUEST_METHOD"]}") {
-
env["REQUEST_METHOD"] =~ /\A[0-9A-Za-z!\#$%&'*+.^_`|~-]+\z/
-
}
-
-
## * The <tt>SCRIPT_NAME</tt>, if non-empty, must start with <tt>/</tt>
-
assert("SCRIPT_NAME must start with /") {
-
!env.include?("SCRIPT_NAME") ||
-
env["SCRIPT_NAME"] == "" ||
-
env["SCRIPT_NAME"] =~ /\A\//
-
}
-
## * The <tt>PATH_INFO</tt>, if non-empty, must start with <tt>/</tt>
-
assert("PATH_INFO must start with /") {
-
!env.include?("PATH_INFO") ||
-
env["PATH_INFO"] == "" ||
-
env["PATH_INFO"] =~ /\A\//
-
}
-
## * The <tt>CONTENT_LENGTH</tt>, if given, must consist of digits only.
-
assert("Invalid CONTENT_LENGTH: #{env["CONTENT_LENGTH"]}") {
-
!env.include?("CONTENT_LENGTH") || env["CONTENT_LENGTH"] =~ /\A\d+\z/
-
}
-
-
## * One of <tt>SCRIPT_NAME</tt> or <tt>PATH_INFO</tt> must be
-
## set. <tt>PATH_INFO</tt> should be <tt>/</tt> if
-
## <tt>SCRIPT_NAME</tt> is empty.
-
assert("One of SCRIPT_NAME or PATH_INFO must be set (make PATH_INFO '/' if SCRIPT_NAME is empty)") {
-
env["SCRIPT_NAME"] || env["PATH_INFO"]
-
}
-
## <tt>SCRIPT_NAME</tt> never should be <tt>/</tt>, but instead be empty.
-
assert("SCRIPT_NAME cannot be '/', make it '' and PATH_INFO '/'") {
-
env["SCRIPT_NAME"] != "/"
-
}
-
end
-
-
## === The Input Stream
-
##
-
## The input stream is an IO-like object which contains the raw HTTP
-
## POST data.
-
1
def check_input(input)
-
## When applicable, its external encoding must be "ASCII-8BIT" and it
-
## must be opened in binary mode, for Ruby 1.9 compatibility.
-
assert("rack.input #{input} does not have ASCII-8BIT as its external encoding") {
-
input.external_encoding.name == "ASCII-8BIT"
-
} if input.respond_to?(:external_encoding)
-
assert("rack.input #{input} is not opened in binary mode") {
-
input.binmode?
-
} if input.respond_to?(:binmode?)
-
-
## The input stream must respond to +gets+, +each+, +read+ and +rewind+.
-
[:gets, :each, :read, :rewind].each { |method|
-
assert("rack.input #{input} does not respond to ##{method}") {
-
input.respond_to? method
-
}
-
}
-
end
-
-
1
class InputWrapper
-
1
include Assertion
-
-
1
def initialize(input)
-
@input = input
-
end
-
-
## * +gets+ must be called without arguments and return a string,
-
## or +nil+ on EOF.
-
1
def gets(*args)
-
assert("rack.input#gets called with arguments") { args.size == 0 }
-
v = @input.gets
-
assert("rack.input#gets didn't return a String") {
-
v.nil? or v.kind_of? String
-
}
-
v
-
end
-
-
## * +read+ behaves like IO#read. Its signature is <tt>read([length, [buffer]])</tt>.
-
## If given, +length+ must be a non-negative Integer (>= 0) or +nil+, and +buffer+ must
-
## be a String and may not be nil. If +length+ is given and not nil, then this method
-
## reads at most +length+ bytes from the input stream. If +length+ is not given or nil,
-
## then this method reads all data until EOF.
-
## When EOF is reached, this method returns nil if +length+ is given and not nil, or ""
-
## if +length+ is not given or is nil.
-
## If +buffer+ is given, then the read data will be placed into +buffer+ instead of a
-
## newly created String object.
-
1
def read(*args)
-
assert("rack.input#read called with too many arguments") {
-
args.size <= 2
-
}
-
if args.size >= 1
-
assert("rack.input#read called with non-integer and non-nil length") {
-
args.first.kind_of?(Integer) || args.first.nil?
-
}
-
assert("rack.input#read called with a negative length") {
-
args.first.nil? || args.first >= 0
-
}
-
end
-
if args.size >= 2
-
assert("rack.input#read called with non-String buffer") {
-
args[1].kind_of?(String)
-
}
-
end
-
-
v = @input.read(*args)
-
-
assert("rack.input#read didn't return nil or a String") {
-
v.nil? or v.kind_of? String
-
}
-
if args[0].nil?
-
assert("rack.input#read(nil) returned nil on EOF") {
-
!v.nil?
-
}
-
end
-
-
v
-
end
-
-
## * +each+ must be called without arguments and only yield Strings.
-
1
def each(*args)
-
assert("rack.input#each called with arguments") { args.size == 0 }
-
@input.each { |line|
-
assert("rack.input#each didn't yield a String") {
-
line.kind_of? String
-
}
-
yield line
-
}
-
end
-
-
## * +rewind+ must be called without arguments. It rewinds the input
-
## stream back to the beginning. It must not raise Errno::ESPIPE:
-
## that is, it may not be a pipe or a socket. Therefore, handler
-
## developers must buffer the input data into some rewindable object
-
## if the underlying input stream is not rewindable.
-
1
def rewind(*args)
-
assert("rack.input#rewind called with arguments") { args.size == 0 }
-
assert("rack.input#rewind raised Errno::ESPIPE") {
-
begin
-
@input.rewind
-
true
-
rescue Errno::ESPIPE
-
false
-
end
-
}
-
end
-
-
## * +close+ must never be called on the input stream.
-
1
def close(*args)
-
assert("rack.input#close must not be called") { false }
-
end
-
end
-
-
## === The Error Stream
-
1
def check_error(error)
-
## The error stream must respond to +puts+, +write+ and +flush+.
-
[:puts, :write, :flush].each { |method|
-
assert("rack.error #{error} does not respond to ##{method}") {
-
error.respond_to? method
-
}
-
}
-
end
-
-
1
class ErrorWrapper
-
1
include Assertion
-
-
1
def initialize(error)
-
@error = error
-
end
-
-
## * +puts+ must be called with a single argument that responds to +to_s+.
-
1
def puts(str)
-
@error.puts str
-
end
-
-
## * +write+ must be called with a single argument that is a String.
-
1
def write(str)
-
assert("rack.errors#write not called with a String") { str.kind_of? String }
-
@error.write str
-
end
-
-
## * +flush+ must be called without arguments and must be called
-
## in order to make the error appear for sure.
-
1
def flush
-
@error.flush
-
end
-
-
## * +close+ must never be called on the error stream.
-
1
def close(*args)
-
assert("rack.errors#close must not be called") { false }
-
end
-
end
-
-
1
class HijackWrapper
-
1
include Assertion
-
1
extend Forwardable
-
-
1
REQUIRED_METHODS = [
-
:read, :write, :read_nonblock, :write_nonblock, :flush, :close,
-
:close_read, :close_write, :closed?
-
]
-
-
1
def_delegators :@io, *REQUIRED_METHODS
-
-
1
def initialize(io)
-
@io = io
-
REQUIRED_METHODS.each do |meth|
-
assert("rack.hijack_io must respond to #{meth}") { io.respond_to? meth }
-
end
-
end
-
end
-
-
## === Hijacking
-
#
-
# AUTHORS: n.b. The trailing whitespace between paragraphs is important and
-
# should not be removed. The whitespace creates paragraphs in the RDoc
-
# output.
-
#
-
## ==== Request (before status)
-
1
def check_hijack(env)
-
if env['rack.hijack?']
-
## If rack.hijack? is true then rack.hijack must respond to #call.
-
original_hijack = env['rack.hijack']
-
assert("rack.hijack must respond to call") { original_hijack.respond_to?(:call) }
-
env['rack.hijack'] = proc do
-
## rack.hijack must return the io that will also be assigned (or is
-
## already present, in rack.hijack_io.
-
io = original_hijack.call
-
HijackWrapper.new(io)
-
##
-
## rack.hijack_io must respond to:
-
## <tt>read, write, read_nonblock, write_nonblock, flush, close,
-
## close_read, close_write, closed?</tt>
-
##
-
## The semantics of these IO methods must be a best effort match to
-
## those of a normal ruby IO or Socket object, using standard
-
## arguments and raising standard exceptions. Servers are encouraged
-
## to simply pass on real IO objects, although it is recognized that
-
## this approach is not directly compatible with SPDY and HTTP 2.0.
-
##
-
## IO provided in rack.hijack_io should preference the
-
## IO::WaitReadable and IO::WaitWritable APIs wherever supported.
-
##
-
## There is a deliberate lack of full specification around
-
## rack.hijack_io, as semantics will change from server to server.
-
## Users are encouraged to utilize this API with a knowledge of their
-
## server choice, and servers may extend the functionality of
-
## hijack_io to provide additional features to users. The purpose of
-
## rack.hijack is for Rack to "get out of the way", as such, Rack only
-
## provides the minimum of specification and support.
-
env['rack.hijack_io'] = HijackWrapper.new(env['rack.hijack_io'])
-
io
-
end
-
else
-
##
-
## If rack.hijack? is false, then rack.hijack should not be set.
-
assert("rack.hijack? is false, but rack.hijack is present") { env['rack.hijack'].nil? }
-
##
-
## If rack.hijack? is false, then rack.hijack_io should not be set.
-
assert("rack.hijack? is false, but rack.hijack_io is present") { env['rack.hijack_io'].nil? }
-
end
-
end
-
-
## ==== Response (after headers)
-
## It is also possible to hijack a response after the status and headers
-
## have been sent.
-
1
def check_hijack_response(headers, env)
-
-
# this check uses headers like a hash, but the spec only requires
-
# headers respond to #each
-
headers = Rack::Utils::HeaderHash.new(headers)
-
-
## In order to do this, an application may set the special header
-
## <tt>rack.hijack</tt> to an object that responds to <tt>call</tt>
-
## accepting an argument that conforms to the <tt>rack.hijack_io</tt>
-
## protocol.
-
##
-
## After the headers have been sent, and this hijack callback has been
-
## called, the application is now responsible for the remaining lifecycle
-
## of the IO. The application is also responsible for maintaining HTTP
-
## semantics. Of specific note, in almost all cases in the current SPEC,
-
## applications will have wanted to specify the header Connection:close in
-
## HTTP/1.1, and not Connection:keep-alive, as there is no protocol for
-
## returning hijacked sockets to the web server. For that purpose, use the
-
## body streaming API instead (progressively yielding strings via each).
-
##
-
## Servers must ignore the <tt>body</tt> part of the response tuple when
-
## the <tt>rack.hijack</tt> response API is in use.
-
-
if env['rack.hijack?'] && headers['rack.hijack']
-
assert('rack.hijack header must respond to #call') {
-
headers['rack.hijack'].respond_to? :call
-
}
-
original_hijack = headers['rack.hijack']
-
headers['rack.hijack'] = proc do |io|
-
original_hijack.call HijackWrapper.new(io)
-
end
-
else
-
##
-
## The special response header <tt>rack.hijack</tt> must only be set
-
## if the request env has <tt>rack.hijack?</tt> <tt>true</tt>.
-
assert('rack.hijack header must not be present if server does not support hijacking') {
-
headers['rack.hijack'].nil?
-
}
-
end
-
end
-
## ==== Conventions
-
## * Middleware should not use hijack unless it is handling the whole
-
## response.
-
## * Middleware may wrap the IO object for the response pattern.
-
## * Middleware should not wrap the IO object for the request pattern. The
-
## request pattern is intended to provide the hijacker with "raw tcp".
-
-
## == The Response
-
-
## === The Status
-
1
def check_status(status)
-
## This is an HTTP status. When parsed as integer (+to_i+), it must be
-
## greater than or equal to 100.
-
assert("Status must be >=100 seen as integer") { status.to_i >= 100 }
-
end
-
-
## === The Headers
-
1
def check_headers(header)
-
## The header must respond to +each+, and yield values of key and value.
-
assert("headers object should respond to #each, but doesn't (got #{header.class} as headers)") {
-
header.respond_to? :each
-
}
-
header.each { |key, value|
-
## Special headers starting "rack." are for communicating with the
-
## server, and must not be sent back to the client.
-
next if key =~ /^rack\..+$/
-
-
## The header keys must be Strings.
-
assert("header key must be a string, was #{key.class}") {
-
key.kind_of? String
-
}
-
## The header must not contain a +Status+ key,
-
assert("header must not contain Status") { key.downcase != "status" }
-
## contain keys with <tt>:</tt> or newlines in their name,
-
assert("header names must not contain : or \\n") { key !~ /[:\n]/ }
-
## contain keys names that end in <tt>-</tt> or <tt>_</tt>,
-
assert("header names must not end in - or _") { key !~ /[-_]\z/ }
-
## but only contain keys that consist of
-
## letters, digits, <tt>_</tt> or <tt>-</tt> and start with a letter.
-
assert("invalid header name: #{key}") { key =~ /\A[a-zA-Z][a-zA-Z0-9_-]*\z/ }
-
-
## The values of the header must be Strings,
-
assert("a header value must be a String, but the value of " +
-
"'#{key}' is a #{value.class}") { value.kind_of? String }
-
## consisting of lines (for multiple header values, e.g. multiple
-
## <tt>Set-Cookie</tt> values) seperated by "\n".
-
value.split("\n").each { |item|
-
## The lines must not contain characters below 037.
-
assert("invalid header value #{key}: #{item.inspect}") {
-
item !~ /[\000-\037]/
-
}
-
}
-
}
-
end
-
-
## === The Content-Type
-
1
def check_content_type(status, headers)
-
headers.each { |key, value|
-
## There must not be a <tt>Content-Type</tt>, when the +Status+ is 1xx,
-
## 204, 205 or 304.
-
if key.downcase == "content-type"
-
assert("Content-Type header found in #{status} response, not allowed") {
-
not Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
-
}
-
return
-
end
-
}
-
end
-
-
## === The Content-Length
-
1
def check_content_length(status, headers)
-
headers.each { |key, value|
-
if key.downcase == 'content-length'
-
## There must not be a <tt>Content-Length</tt> header when the
-
## +Status+ is 1xx, 204, 205 or 304.
-
assert("Content-Length header found in #{status} response, not allowed") {
-
not Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
-
}
-
@content_length = value
-
end
-
}
-
end
-
-
1
def verify_content_length(bytes)
-
if @head_request
-
assert("Response body was given for HEAD request, but should be empty") {
-
bytes == 0
-
}
-
elsif @content_length
-
assert("Content-Length header was #{@content_length}, but should be #{bytes}") {
-
@content_length == bytes.to_s
-
}
-
end
-
end
-
-
## === The Body
-
1
def each
-
@closed = false
-
bytes = 0
-
-
## The Body must respond to +each+
-
assert("Response body must respond to each") do
-
@body.respond_to?(:each)
-
end
-
-
@body.each { |part|
-
## and must only yield String values.
-
assert("Body yielded non-string value #{part.inspect}") {
-
part.kind_of? String
-
}
-
bytes += Rack::Utils.bytesize(part)
-
yield part
-
}
-
verify_content_length(bytes)
-
-
##
-
## The Body itself should not be an instance of String, as this will
-
## break in Ruby 1.9.
-
##
-
## If the Body responds to +close+, it will be called after iteration. If
-
## the body is replaced by a middleware after action, the original body
-
## must be closed first, if it repsonds to close.
-
# XXX howto: assert("Body has not been closed") { @closed }
-
-
-
##
-
## If the Body responds to +to_path+, it must return a String
-
## identifying the location of a file whose contents are identical
-
## to that produced by calling +each+; this may be used by the
-
## server as an alternative, possibly more efficient way to
-
## transport the response.
-
-
if @body.respond_to?(:to_path)
-
assert("The file identified by body.to_path does not exist") {
-
::File.exist? @body.to_path
-
}
-
end
-
-
##
-
## The Body commonly is an Array of Strings, the application
-
## instance itself, or a File-like object.
-
end
-
-
1
def close
-
@closed = true
-
@body.close if @body.respond_to?(:close)
-
end
-
-
# :startdoc:
-
-
end
-
end
-
-
## == Thanks
-
## Some parts of this specification are adopted from PEP333: Python
-
## Web Server Gateway Interface
-
## v1.0 (http://www.python.org/dev/peps/pep-0333/). I'd like to thank
-
## everyone involved in that effort.
-
1
module Rack
-
1
class MethodOverride
-
1
HTTP_METHODS = %w(GET HEAD PUT POST DELETE OPTIONS PATCH)
-
-
1
METHOD_OVERRIDE_PARAM_KEY = "_method".freeze
-
1
HTTP_METHOD_OVERRIDE_HEADER = "HTTP_X_HTTP_METHOD_OVERRIDE".freeze
-
-
1
def initialize(app)
-
1
@app = app
-
end
-
-
1
def call(env)
-
if env["REQUEST_METHOD"] == "POST"
-
method = method_override(env)
-
if HTTP_METHODS.include?(method)
-
env["rack.methodoverride.original_method"] = env["REQUEST_METHOD"]
-
env["REQUEST_METHOD"] = method
-
end
-
end
-
-
@app.call(env)
-
end
-
-
1
def method_override(env)
-
req = Request.new(env)
-
method = req.POST[METHOD_OVERRIDE_PARAM_KEY] ||
-
env[HTTP_METHOD_OVERRIDE_HEADER]
-
method.to_s.upcase
-
end
-
end
-
end
-
1
module Rack
-
1
module Mime
-
# Returns String with mime type if found, otherwise use +fallback+.
-
# +ext+ should be filename extension in the '.ext' format that
-
# File.extname(file) returns.
-
# +fallback+ may be any object
-
#
-
# Also see the documentation for MIME_TYPES
-
#
-
# Usage:
-
# Rack::Mime.mime_type('.foo')
-
#
-
# This is a shortcut for:
-
# Rack::Mime::MIME_TYPES.fetch('.foo', 'application/octet-stream')
-
-
1
def mime_type(ext, fallback='application/octet-stream')
-
MIME_TYPES.fetch(ext.to_s.downcase, fallback)
-
end
-
1
module_function :mime_type
-
-
# Returns true if the given value is a mime match for the given mime match
-
# specification, false otherwise.
-
#
-
# Rack::Mime.match?('text/html', 'text/*') => true
-
# Rack::Mime.match?('text/plain', '*') => true
-
# Rack::Mime.match?('text/html', 'application/json') => false
-
-
1
def match?(value, matcher)
-
v1, v2 = value.split('/', 2)
-
m1, m2 = matcher.split('/', 2)
-
-
if m1 == '*'
-
if m2.nil? || m2 == '*'
-
return true
-
elsif m2 == v2
-
return true
-
else
-
return false
-
end
-
end
-
-
return false if v1 != m1
-
-
return true if m2.nil? || m2 == '*'
-
-
m2 == v2
-
end
-
1
module_function :match?
-
-
# List of most common mime-types, selected various sources
-
# according to their usefulness in a webserving scope for Ruby
-
# users.
-
#
-
# To amend this list with your local mime.types list you can use:
-
#
-
# require 'webrick/httputils'
-
# list = WEBrick::HTTPUtils.load_mime_types('/etc/mime.types')
-
# Rack::Mime::MIME_TYPES.merge!(list)
-
#
-
# N.B. On Ubuntu the mime.types file does not include the leading period, so
-
# users may need to modify the data before merging into the hash.
-
#
-
# To add the list mongrel provides, use:
-
#
-
# require 'mongrel/handlers'
-
# Rack::Mime::MIME_TYPES.merge!(Mongrel::DirHandler::MIME_TYPES)
-
-
1
MIME_TYPES = {
-
".123" => "application/vnd.lotus-1-2-3",
-
".3dml" => "text/vnd.in3d.3dml",
-
".3g2" => "video/3gpp2",
-
".3gp" => "video/3gpp",
-
".a" => "application/octet-stream",
-
".acc" => "application/vnd.americandynamics.acc",
-
".ace" => "application/x-ace-compressed",
-
".acu" => "application/vnd.acucobol",
-
".aep" => "application/vnd.audiograph",
-
".afp" => "application/vnd.ibm.modcap",
-
".ai" => "application/postscript",
-
".aif" => "audio/x-aiff",
-
".aiff" => "audio/x-aiff",
-
".ami" => "application/vnd.amiga.ami",
-
".appcache" => "text/cache-manifest",
-
".apr" => "application/vnd.lotus-approach",
-
".asc" => "application/pgp-signature",
-
".asf" => "video/x-ms-asf",
-
".asm" => "text/x-asm",
-
".aso" => "application/vnd.accpac.simply.aso",
-
".asx" => "video/x-ms-asf",
-
".atc" => "application/vnd.acucorp",
-
".atom" => "application/atom+xml",
-
".atomcat" => "application/atomcat+xml",
-
".atomsvc" => "application/atomsvc+xml",
-
".atx" => "application/vnd.antix.game-component",
-
".au" => "audio/basic",
-
".avi" => "video/x-msvideo",
-
".bat" => "application/x-msdownload",
-
".bcpio" => "application/x-bcpio",
-
".bdm" => "application/vnd.syncml.dm+wbxml",
-
".bh2" => "application/vnd.fujitsu.oasysprs",
-
".bin" => "application/octet-stream",
-
".bmi" => "application/vnd.bmi",
-
".bmp" => "image/bmp",
-
".box" => "application/vnd.previewsystems.box",
-
".btif" => "image/prs.btif",
-
".bz" => "application/x-bzip",
-
".bz2" => "application/x-bzip2",
-
".c" => "text/x-c",
-
".c4g" => "application/vnd.clonk.c4group",
-
".cab" => "application/vnd.ms-cab-compressed",
-
".cc" => "text/x-c",
-
".ccxml" => "application/ccxml+xml",
-
".cdbcmsg" => "application/vnd.contact.cmsg",
-
".cdkey" => "application/vnd.mediastation.cdkey",
-
".cdx" => "chemical/x-cdx",
-
".cdxml" => "application/vnd.chemdraw+xml",
-
".cdy" => "application/vnd.cinderella",
-
".cer" => "application/pkix-cert",
-
".cgm" => "image/cgm",
-
".chat" => "application/x-chat",
-
".chm" => "application/vnd.ms-htmlhelp",
-
".chrt" => "application/vnd.kde.kchart",
-
".cif" => "chemical/x-cif",
-
".cii" => "application/vnd.anser-web-certificate-issue-initiation",
-
".cil" => "application/vnd.ms-artgalry",
-
".cla" => "application/vnd.claymore",
-
".class" => "application/octet-stream",
-
".clkk" => "application/vnd.crick.clicker.keyboard",
-
".clkp" => "application/vnd.crick.clicker.palette",
-
".clkt" => "application/vnd.crick.clicker.template",
-
".clkw" => "application/vnd.crick.clicker.wordbank",
-
".clkx" => "application/vnd.crick.clicker",
-
".clp" => "application/x-msclip",
-
".cmc" => "application/vnd.cosmocaller",
-
".cmdf" => "chemical/x-cmdf",
-
".cml" => "chemical/x-cml",
-
".cmp" => "application/vnd.yellowriver-custom-menu",
-
".cmx" => "image/x-cmx",
-
".com" => "application/x-msdownload",
-
".conf" => "text/plain",
-
".cpio" => "application/x-cpio",
-
".cpp" => "text/x-c",
-
".cpt" => "application/mac-compactpro",
-
".crd" => "application/x-mscardfile",
-
".crl" => "application/pkix-crl",
-
".crt" => "application/x-x509-ca-cert",
-
".csh" => "application/x-csh",
-
".csml" => "chemical/x-csml",
-
".csp" => "application/vnd.commonspace",
-
".css" => "text/css",
-
".csv" => "text/csv",
-
".curl" => "application/vnd.curl",
-
".cww" => "application/prs.cww",
-
".cxx" => "text/x-c",
-
".daf" => "application/vnd.mobius.daf",
-
".davmount" => "application/davmount+xml",
-
".dcr" => "application/x-director",
-
".dd2" => "application/vnd.oma.dd2+xml",
-
".ddd" => "application/vnd.fujixerox.ddd",
-
".deb" => "application/x-debian-package",
-
".der" => "application/x-x509-ca-cert",
-
".dfac" => "application/vnd.dreamfactory",
-
".diff" => "text/x-diff",
-
".dis" => "application/vnd.mobius.dis",
-
".djv" => "image/vnd.djvu",
-
".djvu" => "image/vnd.djvu",
-
".dll" => "application/x-msdownload",
-
".dmg" => "application/octet-stream",
-
".dna" => "application/vnd.dna",
-
".doc" => "application/msword",
-
".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
-
".dot" => "application/msword",
-
".dp" => "application/vnd.osgi.dp",
-
".dpg" => "application/vnd.dpgraph",
-
".dsc" => "text/prs.lines.tag",
-
".dtd" => "application/xml-dtd",
-
".dts" => "audio/vnd.dts",
-
".dtshd" => "audio/vnd.dts.hd",
-
".dv" => "video/x-dv",
-
".dvi" => "application/x-dvi",
-
".dwf" => "model/vnd.dwf",
-
".dwg" => "image/vnd.dwg",
-
".dxf" => "image/vnd.dxf",
-
".dxp" => "application/vnd.spotfire.dxp",
-
".ear" => "application/java-archive",
-
".ecelp4800" => "audio/vnd.nuera.ecelp4800",
-
".ecelp7470" => "audio/vnd.nuera.ecelp7470",
-
".ecelp9600" => "audio/vnd.nuera.ecelp9600",
-
".ecma" => "application/ecmascript",
-
".edm" => "application/vnd.novadigm.edm",
-
".edx" => "application/vnd.novadigm.edx",
-
".efif" => "application/vnd.picsel",
-
".ei6" => "application/vnd.pg.osasli",
-
".eml" => "message/rfc822",
-
".eol" => "audio/vnd.digital-winds",
-
".eot" => "application/vnd.ms-fontobject",
-
".eps" => "application/postscript",
-
".es3" => "application/vnd.eszigno3+xml",
-
".esf" => "application/vnd.epson.esf",
-
".etx" => "text/x-setext",
-
".exe" => "application/x-msdownload",
-
".ext" => "application/vnd.novadigm.ext",
-
".ez" => "application/andrew-inset",
-
".ez2" => "application/vnd.ezpix-album",
-
".ez3" => "application/vnd.ezpix-package",
-
".f" => "text/x-fortran",
-
".f77" => "text/x-fortran",
-
".f90" => "text/x-fortran",
-
".fbs" => "image/vnd.fastbidsheet",
-
".fdf" => "application/vnd.fdf",
-
".fe_launch" => "application/vnd.denovo.fcselayout-link",
-
".fg5" => "application/vnd.fujitsu.oasysgp",
-
".fli" => "video/x-fli",
-
".flo" => "application/vnd.micrografx.flo",
-
".flv" => "video/x-flv",
-
".flw" => "application/vnd.kde.kivio",
-
".flx" => "text/vnd.fmi.flexstor",
-
".fly" => "text/vnd.fly",
-
".fm" => "application/vnd.framemaker",
-
".fnc" => "application/vnd.frogans.fnc",
-
".for" => "text/x-fortran",
-
".fpx" => "image/vnd.fpx",
-
".fsc" => "application/vnd.fsc.weblaunch",
-
".fst" => "image/vnd.fst",
-
".ftc" => "application/vnd.fluxtime.clip",
-
".fti" => "application/vnd.anser-web-funds-transfer-initiation",
-
".fvt" => "video/vnd.fvt",
-
".fzs" => "application/vnd.fuzzysheet",
-
".g3" => "image/g3fax",
-
".gac" => "application/vnd.groove-account",
-
".gdl" => "model/vnd.gdl",
-
".gem" => "application/octet-stream",
-
".gemspec" => "text/x-script.ruby",
-
".ghf" => "application/vnd.groove-help",
-
".gif" => "image/gif",
-
".gim" => "application/vnd.groove-identity-message",
-
".gmx" => "application/vnd.gmx",
-
".gph" => "application/vnd.flographit",
-
".gqf" => "application/vnd.grafeq",
-
".gram" => "application/srgs",
-
".grv" => "application/vnd.groove-injector",
-
".grxml" => "application/srgs+xml",
-
".gtar" => "application/x-gtar",
-
".gtm" => "application/vnd.groove-tool-message",
-
".gtw" => "model/vnd.gtw",
-
".gv" => "text/vnd.graphviz",
-
".gz" => "application/x-gzip",
-
".h" => "text/x-c",
-
".h261" => "video/h261",
-
".h263" => "video/h263",
-
".h264" => "video/h264",
-
".hbci" => "application/vnd.hbci",
-
".hdf" => "application/x-hdf",
-
".hh" => "text/x-c",
-
".hlp" => "application/winhlp",
-
".hpgl" => "application/vnd.hp-hpgl",
-
".hpid" => "application/vnd.hp-hpid",
-
".hps" => "application/vnd.hp-hps",
-
".hqx" => "application/mac-binhex40",
-
".htc" => "text/x-component",
-
".htke" => "application/vnd.kenameaapp",
-
".htm" => "text/html",
-
".html" => "text/html",
-
".hvd" => "application/vnd.yamaha.hv-dic",
-
".hvp" => "application/vnd.yamaha.hv-voice",
-
".hvs" => "application/vnd.yamaha.hv-script",
-
".icc" => "application/vnd.iccprofile",
-
".ice" => "x-conference/x-cooltalk",
-
".ico" => "image/vnd.microsoft.icon",
-
".ics" => "text/calendar",
-
".ief" => "image/ief",
-
".ifb" => "text/calendar",
-
".ifm" => "application/vnd.shana.informed.formdata",
-
".igl" => "application/vnd.igloader",
-
".igs" => "model/iges",
-
".igx" => "application/vnd.micrografx.igx",
-
".iif" => "application/vnd.shana.informed.interchange",
-
".imp" => "application/vnd.accpac.simply.imp",
-
".ims" => "application/vnd.ms-ims",
-
".ipk" => "application/vnd.shana.informed.package",
-
".irm" => "application/vnd.ibm.rights-management",
-
".irp" => "application/vnd.irepository.package+xml",
-
".iso" => "application/octet-stream",
-
".itp" => "application/vnd.shana.informed.formtemplate",
-
".ivp" => "application/vnd.immervision-ivp",
-
".ivu" => "application/vnd.immervision-ivu",
-
".jad" => "text/vnd.sun.j2me.app-descriptor",
-
".jam" => "application/vnd.jam",
-
".jar" => "application/java-archive",
-
".java" => "text/x-java-source",
-
".jisp" => "application/vnd.jisp",
-
".jlt" => "application/vnd.hp-jlyt",
-
".jnlp" => "application/x-java-jnlp-file",
-
".joda" => "application/vnd.joost.joda-archive",
-
".jp2" => "image/jp2",
-
".jpeg" => "image/jpeg",
-
".jpg" => "image/jpeg",
-
".jpgv" => "video/jpeg",
-
".jpm" => "video/jpm",
-
".js" => "application/javascript",
-
".json" => "application/json",
-
".karbon" => "application/vnd.kde.karbon",
-
".kfo" => "application/vnd.kde.kformula",
-
".kia" => "application/vnd.kidspiration",
-
".kml" => "application/vnd.google-earth.kml+xml",
-
".kmz" => "application/vnd.google-earth.kmz",
-
".kne" => "application/vnd.kinar",
-
".kon" => "application/vnd.kde.kontour",
-
".kpr" => "application/vnd.kde.kpresenter",
-
".ksp" => "application/vnd.kde.kspread",
-
".ktz" => "application/vnd.kahootz",
-
".kwd" => "application/vnd.kde.kword",
-
".latex" => "application/x-latex",
-
".lbd" => "application/vnd.llamagraphics.life-balance.desktop",
-
".lbe" => "application/vnd.llamagraphics.life-balance.exchange+xml",
-
".les" => "application/vnd.hhe.lesson-player",
-
".link66" => "application/vnd.route66.link66+xml",
-
".log" => "text/plain",
-
".lostxml" => "application/lost+xml",
-
".lrm" => "application/vnd.ms-lrm",
-
".ltf" => "application/vnd.frogans.ltf",
-
".lvp" => "audio/vnd.lucent.voice",
-
".lwp" => "application/vnd.lotus-wordpro",
-
".m3u" => "audio/x-mpegurl",
-
".m4a" => "audio/mp4a-latm",
-
".m4v" => "video/mp4",
-
".ma" => "application/mathematica",
-
".mag" => "application/vnd.ecowin.chart",
-
".man" => "text/troff",
-
".manifest" => "text/cache-manifest",
-
".mathml" => "application/mathml+xml",
-
".mbk" => "application/vnd.mobius.mbk",
-
".mbox" => "application/mbox",
-
".mc1" => "application/vnd.medcalcdata",
-
".mcd" => "application/vnd.mcd",
-
".mdb" => "application/x-msaccess",
-
".mdi" => "image/vnd.ms-modi",
-
".mdoc" => "text/troff",
-
".me" => "text/troff",
-
".mfm" => "application/vnd.mfmp",
-
".mgz" => "application/vnd.proteus.magazine",
-
".mid" => "audio/midi",
-
".midi" => "audio/midi",
-
".mif" => "application/vnd.mif",
-
".mime" => "message/rfc822",
-
".mj2" => "video/mj2",
-
".mlp" => "application/vnd.dolby.mlp",
-
".mmd" => "application/vnd.chipnuts.karaoke-mmd",
-
".mmf" => "application/vnd.smaf",
-
".mml" => "application/mathml+xml",
-
".mmr" => "image/vnd.fujixerox.edmics-mmr",
-
".mng" => "video/x-mng",
-
".mny" => "application/x-msmoney",
-
".mov" => "video/quicktime",
-
".movie" => "video/x-sgi-movie",
-
".mp3" => "audio/mpeg",
-
".mp4" => "video/mp4",
-
".mp4a" => "audio/mp4",
-
".mp4s" => "application/mp4",
-
".mp4v" => "video/mp4",
-
".mpc" => "application/vnd.mophun.certificate",
-
".mpeg" => "video/mpeg",
-
".mpg" => "video/mpeg",
-
".mpga" => "audio/mpeg",
-
".mpkg" => "application/vnd.apple.installer+xml",
-
".mpm" => "application/vnd.blueice.multipass",
-
".mpn" => "application/vnd.mophun.application",
-
".mpp" => "application/vnd.ms-project",
-
".mpy" => "application/vnd.ibm.minipay",
-
".mqy" => "application/vnd.mobius.mqy",
-
".mrc" => "application/marc",
-
".ms" => "text/troff",
-
".mscml" => "application/mediaservercontrol+xml",
-
".mseq" => "application/vnd.mseq",
-
".msf" => "application/vnd.epson.msf",
-
".msh" => "model/mesh",
-
".msi" => "application/x-msdownload",
-
".msl" => "application/vnd.mobius.msl",
-
".msty" => "application/vnd.muvee.style",
-
".mts" => "model/vnd.mts",
-
".mus" => "application/vnd.musician",
-
".mvb" => "application/x-msmediaview",
-
".mwf" => "application/vnd.mfer",
-
".mxf" => "application/mxf",
-
".mxl" => "application/vnd.recordare.musicxml",
-
".mxml" => "application/xv+xml",
-
".mxs" => "application/vnd.triscape.mxs",
-
".mxu" => "video/vnd.mpegurl",
-
".n" => "application/vnd.nokia.n-gage.symbian.install",
-
".nc" => "application/x-netcdf",
-
".ngdat" => "application/vnd.nokia.n-gage.data",
-
".nlu" => "application/vnd.neurolanguage.nlu",
-
".nml" => "application/vnd.enliven",
-
".nnd" => "application/vnd.noblenet-directory",
-
".nns" => "application/vnd.noblenet-sealer",
-
".nnw" => "application/vnd.noblenet-web",
-
".npx" => "image/vnd.net-fpx",
-
".nsf" => "application/vnd.lotus-notes",
-
".oa2" => "application/vnd.fujitsu.oasys2",
-
".oa3" => "application/vnd.fujitsu.oasys3",
-
".oas" => "application/vnd.fujitsu.oasys",
-
".obd" => "application/x-msbinder",
-
".oda" => "application/oda",
-
".odc" => "application/vnd.oasis.opendocument.chart",
-
".odf" => "application/vnd.oasis.opendocument.formula",
-
".odg" => "application/vnd.oasis.opendocument.graphics",
-
".odi" => "application/vnd.oasis.opendocument.image",
-
".odp" => "application/vnd.oasis.opendocument.presentation",
-
".ods" => "application/vnd.oasis.opendocument.spreadsheet",
-
".odt" => "application/vnd.oasis.opendocument.text",
-
".oga" => "audio/ogg",
-
".ogg" => "application/ogg",
-
".ogv" => "video/ogg",
-
".ogx" => "application/ogg",
-
".org" => "application/vnd.lotus-organizer",
-
".otc" => "application/vnd.oasis.opendocument.chart-template",
-
".otf" => "application/vnd.oasis.opendocument.formula-template",
-
".otg" => "application/vnd.oasis.opendocument.graphics-template",
-
".oth" => "application/vnd.oasis.opendocument.text-web",
-
".oti" => "application/vnd.oasis.opendocument.image-template",
-
".otm" => "application/vnd.oasis.opendocument.text-master",
-
".ots" => "application/vnd.oasis.opendocument.spreadsheet-template",
-
".ott" => "application/vnd.oasis.opendocument.text-template",
-
".oxt" => "application/vnd.openofficeorg.extension",
-
".p" => "text/x-pascal",
-
".p10" => "application/pkcs10",
-
".p12" => "application/x-pkcs12",
-
".p7b" => "application/x-pkcs7-certificates",
-
".p7m" => "application/pkcs7-mime",
-
".p7r" => "application/x-pkcs7-certreqresp",
-
".p7s" => "application/pkcs7-signature",
-
".pas" => "text/x-pascal",
-
".pbd" => "application/vnd.powerbuilder6",
-
".pbm" => "image/x-portable-bitmap",
-
".pcl" => "application/vnd.hp-pcl",
-
".pclxl" => "application/vnd.hp-pclxl",
-
".pcx" => "image/x-pcx",
-
".pdb" => "chemical/x-pdb",
-
".pdf" => "application/pdf",
-
".pem" => "application/x-x509-ca-cert",
-
".pfr" => "application/font-tdpfr",
-
".pgm" => "image/x-portable-graymap",
-
".pgn" => "application/x-chess-pgn",
-
".pgp" => "application/pgp-encrypted",
-
".pic" => "image/x-pict",
-
".pict" => "image/pict",
-
".pkg" => "application/octet-stream",
-
".pki" => "application/pkixcmp",
-
".pkipath" => "application/pkix-pkipath",
-
".pl" => "text/x-script.perl",
-
".plb" => "application/vnd.3gpp.pic-bw-large",
-
".plc" => "application/vnd.mobius.plc",
-
".plf" => "application/vnd.pocketlearn",
-
".pls" => "application/pls+xml",
-
".pm" => "text/x-script.perl-module",
-
".pml" => "application/vnd.ctc-posml",
-
".png" => "image/png",
-
".pnm" => "image/x-portable-anymap",
-
".pntg" => "image/x-macpaint",
-
".portpkg" => "application/vnd.macports.portpkg",
-
".ppd" => "application/vnd.cups-ppd",
-
".ppm" => "image/x-portable-pixmap",
-
".pps" => "application/vnd.ms-powerpoint",
-
".ppt" => "application/vnd.ms-powerpoint",
-
".prc" => "application/vnd.palm",
-
".pre" => "application/vnd.lotus-freelance",
-
".prf" => "application/pics-rules",
-
".ps" => "application/postscript",
-
".psb" => "application/vnd.3gpp.pic-bw-small",
-
".psd" => "image/vnd.adobe.photoshop",
-
".ptid" => "application/vnd.pvi.ptid1",
-
".pub" => "application/x-mspublisher",
-
".pvb" => "application/vnd.3gpp.pic-bw-var",
-
".pwn" => "application/vnd.3m.post-it-notes",
-
".py" => "text/x-script.python",
-
".pya" => "audio/vnd.ms-playready.media.pya",
-
".pyv" => "video/vnd.ms-playready.media.pyv",
-
".qam" => "application/vnd.epson.quickanime",
-
".qbo" => "application/vnd.intu.qbo",
-
".qfx" => "application/vnd.intu.qfx",
-
".qps" => "application/vnd.publishare-delta-tree",
-
".qt" => "video/quicktime",
-
".qtif" => "image/x-quicktime",
-
".qxd" => "application/vnd.quark.quarkxpress",
-
".ra" => "audio/x-pn-realaudio",
-
".rake" => "text/x-script.ruby",
-
".ram" => "audio/x-pn-realaudio",
-
".rar" => "application/x-rar-compressed",
-
".ras" => "image/x-cmu-raster",
-
".rb" => "text/x-script.ruby",
-
".rcprofile" => "application/vnd.ipunplugged.rcprofile",
-
".rdf" => "application/rdf+xml",
-
".rdz" => "application/vnd.data-vision.rdz",
-
".rep" => "application/vnd.businessobjects",
-
".rgb" => "image/x-rgb",
-
".rif" => "application/reginfo+xml",
-
".rl" => "application/resource-lists+xml",
-
".rlc" => "image/vnd.fujixerox.edmics-rlc",
-
".rld" => "application/resource-lists-diff+xml",
-
".rm" => "application/vnd.rn-realmedia",
-
".rmp" => "audio/x-pn-realaudio-plugin",
-
".rms" => "application/vnd.jcp.javame.midlet-rms",
-
".rnc" => "application/relax-ng-compact-syntax",
-
".roff" => "text/troff",
-
".rpm" => "application/x-redhat-package-manager",
-
".rpss" => "application/vnd.nokia.radio-presets",
-
".rpst" => "application/vnd.nokia.radio-preset",
-
".rq" => "application/sparql-query",
-
".rs" => "application/rls-services+xml",
-
".rsd" => "application/rsd+xml",
-
".rss" => "application/rss+xml",
-
".rtf" => "application/rtf",
-
".rtx" => "text/richtext",
-
".ru" => "text/x-script.ruby",
-
".s" => "text/x-asm",
-
".saf" => "application/vnd.yamaha.smaf-audio",
-
".sbml" => "application/sbml+xml",
-
".sc" => "application/vnd.ibm.secure-container",
-
".scd" => "application/x-msschedule",
-
".scm" => "application/vnd.lotus-screencam",
-
".scq" => "application/scvp-cv-request",
-
".scs" => "application/scvp-cv-response",
-
".sdkm" => "application/vnd.solent.sdkm+xml",
-
".sdp" => "application/sdp",
-
".see" => "application/vnd.seemail",
-
".sema" => "application/vnd.sema",
-
".semd" => "application/vnd.semd",
-
".semf" => "application/vnd.semf",
-
".setpay" => "application/set-payment-initiation",
-
".setreg" => "application/set-registration-initiation",
-
".sfd" => "application/vnd.hydrostatix.sof-data",
-
".sfs" => "application/vnd.spotfire.sfs",
-
".sgm" => "text/sgml",
-
".sgml" => "text/sgml",
-
".sh" => "application/x-sh",
-
".shar" => "application/x-shar",
-
".shf" => "application/shf+xml",
-
".sig" => "application/pgp-signature",
-
".sit" => "application/x-stuffit",
-
".sitx" => "application/x-stuffitx",
-
".skp" => "application/vnd.koan",
-
".slt" => "application/vnd.epson.salt",
-
".smi" => "application/smil+xml",
-
".snd" => "audio/basic",
-
".so" => "application/octet-stream",
-
".spf" => "application/vnd.yamaha.smaf-phrase",
-
".spl" => "application/x-futuresplash",
-
".spot" => "text/vnd.in3d.spot",
-
".spp" => "application/scvp-vp-response",
-
".spq" => "application/scvp-vp-request",
-
".src" => "application/x-wais-source",
-
".srx" => "application/sparql-results+xml",
-
".sse" => "application/vnd.kodak-descriptor",
-
".ssf" => "application/vnd.epson.ssf",
-
".ssml" => "application/ssml+xml",
-
".stf" => "application/vnd.wt.stf",
-
".stk" => "application/hyperstudio",
-
".str" => "application/vnd.pg.format",
-
".sus" => "application/vnd.sus-calendar",
-
".sv4cpio" => "application/x-sv4cpio",
-
".sv4crc" => "application/x-sv4crc",
-
".svd" => "application/vnd.svd",
-
".svg" => "image/svg+xml",
-
".svgz" => "image/svg+xml",
-
".swf" => "application/x-shockwave-flash",
-
".swi" => "application/vnd.arastra.swi",
-
".t" => "text/troff",
-
".tao" => "application/vnd.tao.intent-module-archive",
-
".tar" => "application/x-tar",
-
".tbz" => "application/x-bzip-compressed-tar",
-
".tcap" => "application/vnd.3gpp2.tcap",
-
".tcl" => "application/x-tcl",
-
".tex" => "application/x-tex",
-
".texi" => "application/x-texinfo",
-
".texinfo" => "application/x-texinfo",
-
".text" => "text/plain",
-
".tif" => "image/tiff",
-
".tiff" => "image/tiff",
-
".tmo" => "application/vnd.tmobile-livetv",
-
".torrent" => "application/x-bittorrent",
-
".tpl" => "application/vnd.groove-tool-template",
-
".tpt" => "application/vnd.trid.tpt",
-
".tr" => "text/troff",
-
".tra" => "application/vnd.trueapp",
-
".trm" => "application/x-msterminal",
-
".tsv" => "text/tab-separated-values",
-
".ttf" => "application/octet-stream",
-
".twd" => "application/vnd.simtech-mindmapper",
-
".txd" => "application/vnd.genomatix.tuxedo",
-
".txf" => "application/vnd.mobius.txf",
-
".txt" => "text/plain",
-
".ufd" => "application/vnd.ufdl",
-
".umj" => "application/vnd.umajin",
-
".unityweb" => "application/vnd.unity",
-
".uoml" => "application/vnd.uoml+xml",
-
".uri" => "text/uri-list",
-
".ustar" => "application/x-ustar",
-
".utz" => "application/vnd.uiq.theme",
-
".uu" => "text/x-uuencode",
-
".vcd" => "application/x-cdlink",
-
".vcf" => "text/x-vcard",
-
".vcg" => "application/vnd.groove-vcard",
-
".vcs" => "text/x-vcalendar",
-
".vcx" => "application/vnd.vcx",
-
".vis" => "application/vnd.visionary",
-
".viv" => "video/vnd.vivo",
-
".vrml" => "model/vrml",
-
".vsd" => "application/vnd.visio",
-
".vsf" => "application/vnd.vsf",
-
".vtu" => "model/vnd.vtu",
-
".vxml" => "application/voicexml+xml",
-
".war" => "application/java-archive",
-
".wav" => "audio/x-wav",
-
".wax" => "audio/x-ms-wax",
-
".wbmp" => "image/vnd.wap.wbmp",
-
".wbs" => "application/vnd.criticaltools.wbs+xml",
-
".wbxml" => "application/vnd.wap.wbxml",
-
".webm" => "video/webm",
-
".wm" => "video/x-ms-wm",
-
".wma" => "audio/x-ms-wma",
-
".wmd" => "application/x-ms-wmd",
-
".wmf" => "application/x-msmetafile",
-
".wml" => "text/vnd.wap.wml",
-
".wmlc" => "application/vnd.wap.wmlc",
-
".wmls" => "text/vnd.wap.wmlscript",
-
".wmlsc" => "application/vnd.wap.wmlscriptc",
-
".wmv" => "video/x-ms-wmv",
-
".wmx" => "video/x-ms-wmx",
-
".wmz" => "application/x-ms-wmz",
-
".woff" => "application/font-woff",
-
".wpd" => "application/vnd.wordperfect",
-
".wpl" => "application/vnd.ms-wpl",
-
".wps" => "application/vnd.ms-works",
-
".wqd" => "application/vnd.wqd",
-
".wri" => "application/x-mswrite",
-
".wrl" => "model/vrml",
-
".wsdl" => "application/wsdl+xml",
-
".wspolicy" => "application/wspolicy+xml",
-
".wtb" => "application/vnd.webturbo",
-
".wvx" => "video/x-ms-wvx",
-
".x3d" => "application/vnd.hzn-3d-crossword",
-
".xar" => "application/vnd.xara",
-
".xbd" => "application/vnd.fujixerox.docuworks.binder",
-
".xbm" => "image/x-xbitmap",
-
".xdm" => "application/vnd.syncml.dm+xml",
-
".xdp" => "application/vnd.adobe.xdp+xml",
-
".xdw" => "application/vnd.fujixerox.docuworks",
-
".xenc" => "application/xenc+xml",
-
".xer" => "application/patch-ops-error+xml",
-
".xfdf" => "application/vnd.adobe.xfdf",
-
".xfdl" => "application/vnd.xfdl",
-
".xhtml" => "application/xhtml+xml",
-
".xif" => "image/vnd.xiff",
-
".xls" => "application/vnd.ms-excel",
-
".xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
-
".xml" => "application/xml",
-
".xo" => "application/vnd.olpc-sugar",
-
".xop" => "application/xop+xml",
-
".xpm" => "image/x-xpixmap",
-
".xpr" => "application/vnd.is-xpr",
-
".xps" => "application/vnd.ms-xpsdocument",
-
".xpw" => "application/vnd.intercon.formnet",
-
".xsl" => "application/xml",
-
".xslt" => "application/xslt+xml",
-
".xsm" => "application/vnd.syncml+xml",
-
".xspf" => "application/xspf+xml",
-
".xul" => "application/vnd.mozilla.xul+xml",
-
".xwd" => "image/x-xwindowdump",
-
".xyz" => "chemical/x-xyz",
-
".yaml" => "text/yaml",
-
".yml" => "text/yaml",
-
".zaz" => "application/vnd.zzazz.deck+xml",
-
".zip" => "application/zip",
-
".zmm" => "application/vnd.handheld-entertainment+xml",
-
}
-
end
-
end
-
1
require 'uri'
-
1
require 'stringio'
-
1
require 'rack'
-
1
require 'rack/lint'
-
1
require 'rack/utils'
-
1
require 'rack/response'
-
-
1
module Rack
-
# Rack::MockRequest helps testing your Rack application without
-
# actually using HTTP.
-
#
-
# After performing a request on a URL with get/post/put/patch/delete, it
-
# returns a MockResponse with useful helper methods for effective
-
# testing.
-
#
-
# You can pass a hash with additional configuration to the
-
# get/post/put/patch/delete.
-
# <tt>:input</tt>:: A String or IO-like to be used as rack.input.
-
# <tt>:fatal</tt>:: Raise a FatalWarning if the app writes to rack.errors.
-
# <tt>:lint</tt>:: If true, wrap the application in a Rack::Lint.
-
-
1
class MockRequest
-
1
class FatalWarning < RuntimeError
-
end
-
-
1
class FatalWarner
-
1
def puts(warning)
-
raise FatalWarning, warning
-
end
-
-
1
def write(warning)
-
raise FatalWarning, warning
-
end
-
-
1
def flush
-
end
-
-
1
def string
-
""
-
end
-
end
-
-
1
DEFAULT_ENV = {
-
"rack.version" => Rack::VERSION,
-
"rack.input" => StringIO.new,
-
"rack.errors" => StringIO.new,
-
"rack.multithread" => true,
-
"rack.multiprocess" => true,
-
"rack.run_once" => false,
-
}
-
-
1
def initialize(app)
-
@app = app
-
end
-
-
1
def get(uri, opts={}) request("GET", uri, opts) end
-
1
def post(uri, opts={}) request("POST", uri, opts) end
-
1
def put(uri, opts={}) request("PUT", uri, opts) end
-
1
def patch(uri, opts={}) request("PATCH", uri, opts) end
-
1
def delete(uri, opts={}) request("DELETE", uri, opts) end
-
1
def head(uri, opts={}) request("HEAD", uri, opts) end
-
-
1
def request(method="GET", uri="", opts={})
-
env = self.class.env_for(uri, opts.merge(:method => method))
-
-
if opts[:lint]
-
app = Rack::Lint.new(@app)
-
else
-
app = @app
-
end
-
-
errors = env["rack.errors"]
-
status, headers, body = app.call(env)
-
MockResponse.new(status, headers, body, errors)
-
ensure
-
body.close if body.respond_to?(:close)
-
end
-
-
# Return the Rack environment used for a request to +uri+.
-
1
def self.env_for(uri="", opts={})
-
1
uri = URI(uri)
-
1
uri.path = "/#{uri.path}" unless uri.path[0] == ?/
-
-
1
env = DEFAULT_ENV.dup
-
-
1
env["REQUEST_METHOD"] = opts[:method] ? opts[:method].to_s.upcase : "GET"
-
1
env["SERVER_NAME"] = uri.host || "example.org"
-
1
env["SERVER_PORT"] = uri.port ? uri.port.to_s : "80"
-
1
env["QUERY_STRING"] = uri.query.to_s
-
1
env["PATH_INFO"] = (!uri.path || uri.path.empty?) ? "/" : uri.path
-
1
env["rack.url_scheme"] = uri.scheme || "http"
-
1
env["HTTPS"] = env["rack.url_scheme"] == "https" ? "on" : "off"
-
-
1
env["SCRIPT_NAME"] = opts[:script_name] || ""
-
-
1
if opts[:fatal]
-
env["rack.errors"] = FatalWarner.new
-
else
-
1
env["rack.errors"] = StringIO.new
-
end
-
-
1
if params = opts[:params]
-
if env["REQUEST_METHOD"] == "GET"
-
params = Utils.parse_nested_query(params) if params.is_a?(String)
-
params.update(Utils.parse_nested_query(env["QUERY_STRING"]))
-
env["QUERY_STRING"] = Utils.build_nested_query(params)
-
elsif !opts.has_key?(:input)
-
opts["CONTENT_TYPE"] = "application/x-www-form-urlencoded"
-
if params.is_a?(Hash)
-
if data = Utils::Multipart.build_multipart(params)
-
opts[:input] = data
-
opts["CONTENT_LENGTH"] ||= data.length.to_s
-
opts["CONTENT_TYPE"] = "multipart/form-data; boundary=#{Utils::Multipart::MULTIPART_BOUNDARY}"
-
else
-
opts[:input] = Utils.build_nested_query(params)
-
end
-
else
-
opts[:input] = params
-
end
-
end
-
end
-
-
1
empty_str = ""
-
1
empty_str.force_encoding("ASCII-8BIT") if empty_str.respond_to? :force_encoding
-
1
opts[:input] ||= empty_str
-
1
if String === opts[:input]
-
1
rack_input = StringIO.new(opts[:input])
-
else
-
rack_input = opts[:input]
-
end
-
-
1
rack_input.set_encoding(Encoding::BINARY) if rack_input.respond_to?(:set_encoding)
-
1
env['rack.input'] = rack_input
-
-
1
env["CONTENT_LENGTH"] ||= env["rack.input"].length.to_s
-
-
1
opts.each { |field, value|
-
4
env[field] = value if String === field
-
}
-
-
1
env
-
end
-
end
-
-
# Rack::MockResponse provides useful helpers for testing your apps.
-
# Usually, you don't create the MockResponse on your own, but use
-
# MockRequest.
-
-
1
class MockResponse < Rack::Response
-
# Headers
-
1
attr_reader :original_headers
-
-
# Errors
-
1
attr_accessor :errors
-
-
1
def initialize(status, headers, body, errors=StringIO.new(""))
-
@original_headers = headers
-
@errors = errors.string if errors.respond_to?(:string)
-
@body_string = nil
-
-
super(body, status, headers)
-
end
-
-
1
def =~(other)
-
body =~ other
-
end
-
-
1
def match(other)
-
body.match other
-
end
-
-
1
def body
-
# FIXME: apparently users of MockResponse expect the return value of
-
# MockResponse#body to be a string. However, the real response object
-
# returns the body as a list.
-
#
-
# See spec_showstatus.rb:
-
#
-
# should "not replace existing messages" do
-
# ...
-
# res.body.should == "foo!"
-
# end
-
super.join
-
end
-
-
1
def empty?
-
[201, 204, 205, 304].include? status
-
end
-
end
-
end
-
1
module Rack
-
# A multipart form data parser, adapted from IOWA.
-
#
-
# Usually, Rack::Request#POST takes care of calling this.
-
1
module Multipart
-
1
autoload :UploadedFile, 'rack/multipart/uploaded_file'
-
1
autoload :Parser, 'rack/multipart/parser'
-
1
autoload :Generator, 'rack/multipart/generator'
-
-
1
EOL = "\r\n"
-
1
MULTIPART_BOUNDARY = "AaB03x"
-
1
MULTIPART = %r|\Amultipart/.*boundary=\"?([^\";,]+)\"?|n
-
1
TOKEN = /[^\s()<>,;:\\"\/\[\]?=]+/
-
1
CONDISP = /Content-Disposition:\s*#{TOKEN}\s*/i
-
1
DISPPARM = /;\s*(#{TOKEN})=("(?:\\"|[^"])*"|#{TOKEN})/
-
1
RFC2183 = /^#{CONDISP}(#{DISPPARM})+$/i
-
1
BROKEN_QUOTED = /^#{CONDISP}.*;\sfilename="(.*?)"(?:\s*$|\s*;\s*#{TOKEN}=)/i
-
1
BROKEN_UNQUOTED = /^#{CONDISP}.*;\sfilename=(#{TOKEN})/i
-
1
MULTIPART_CONTENT_TYPE = /Content-Type: (.*)#{EOL}/ni
-
1
MULTIPART_CONTENT_DISPOSITION = /Content-Disposition:.*\s+name="?([^\";]*)"?/ni
-
1
MULTIPART_CONTENT_ID = /Content-ID:\s*([^#{EOL}]*)/ni
-
-
1
class << self
-
1
def parse_multipart(env)
-
Parser.new(env).parse
-
end
-
-
1
def build_multipart(params, first = true)
-
Generator.new(params, first).dump
-
end
-
end
-
-
end
-
end
-
1
require 'rack/utils'
-
-
1
module Rack
-
# Rack::Request provides a convenient interface to a Rack
-
# environment. It is stateless, the environment +env+ passed to the
-
# constructor will be directly modified.
-
#
-
# req = Rack::Request.new(env)
-
# req.post?
-
# req.params["data"]
-
#
-
# The environment hash passed will store a reference to the Request object
-
# instantiated so that it will only instantiate if an instance of the Request
-
# object doesn't already exist.
-
-
1
class Request
-
# The environment of the request.
-
1
attr_reader :env
-
-
1
def initialize(env)
-
@env = env
-
end
-
-
1
def body; @env["rack.input"] end
-
1
def script_name; @env["SCRIPT_NAME"].to_s end
-
1
def path_info; @env["PATH_INFO"].to_s end
-
1
def request_method; @env["REQUEST_METHOD"] end
-
1
def query_string; @env["QUERY_STRING"].to_s end
-
1
def content_length; @env['CONTENT_LENGTH'] end
-
-
1
def content_type
-
content_type = @env['CONTENT_TYPE']
-
content_type.nil? || content_type.empty? ? nil : content_type
-
end
-
-
1
def session; @env['rack.session'] ||= {} end
-
1
def session_options; @env['rack.session.options'] ||= {} end
-
1
def logger; @env['rack.logger'] end
-
-
# The media type (type/subtype) portion of the CONTENT_TYPE header
-
# without any media type parameters. e.g., when CONTENT_TYPE is
-
# "text/plain;charset=utf-8", the media-type is "text/plain".
-
#
-
# For more information on the use of media types in HTTP, see:
-
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7
-
1
def media_type
-
content_type && content_type.split(/\s*[;,]\s*/, 2).first.downcase
-
end
-
-
# The media type parameters provided in CONTENT_TYPE as a Hash, or
-
# an empty Hash if no CONTENT_TYPE or media-type parameters were
-
# provided. e.g., when the CONTENT_TYPE is "text/plain;charset=utf-8",
-
# this method responds with the following Hash:
-
# { 'charset' => 'utf-8' }
-
1
def media_type_params
-
return {} if content_type.nil?
-
Hash[*content_type.split(/\s*[;,]\s*/)[1..-1].
-
collect { |s| s.split('=', 2) }.
-
map { |k,v| [k.downcase, v] }.flatten]
-
end
-
-
# The character set of the request body if a "charset" media type
-
# parameter was given, or nil if no "charset" was specified. Note
-
# that, per RFC2616, text/* media types that specify no explicit
-
# charset are to be considered ISO-8859-1.
-
1
def content_charset
-
media_type_params['charset']
-
end
-
-
1
def scheme
-
if @env['HTTPS'] == 'on'
-
'https'
-
elsif @env['HTTP_X_FORWARDED_SSL'] == 'on'
-
'https'
-
elsif @env['HTTP_X_FORWARDED_SCHEME']
-
@env['HTTP_X_FORWARDED_SCHEME']
-
elsif @env['HTTP_X_FORWARDED_PROTO']
-
@env['HTTP_X_FORWARDED_PROTO'].split(',')[0]
-
else
-
@env["rack.url_scheme"]
-
end
-
end
-
-
1
def ssl?
-
scheme == 'https'
-
end
-
-
1
def host_with_port
-
if forwarded = @env["HTTP_X_FORWARDED_HOST"]
-
forwarded.split(/,\s?/).last
-
else
-
@env['HTTP_HOST'] || "#{@env['SERVER_NAME'] || @env['SERVER_ADDR']}:#{@env['SERVER_PORT']}"
-
end
-
end
-
-
1
def port
-
if port = host_with_port.split(/:/)[1]
-
port.to_i
-
elsif port = @env['HTTP_X_FORWARDED_PORT']
-
port.to_i
-
elsif @env.has_key?("HTTP_X_FORWARDED_HOST")
-
DEFAULT_PORTS[scheme]
-
else
-
@env["SERVER_PORT"].to_i
-
end
-
end
-
-
1
def host
-
# Remove port number.
-
host_with_port.to_s.gsub(/:\d+\z/, '')
-
end
-
-
1
def script_name=(s); @env["SCRIPT_NAME"] = s.to_s end
-
1
def path_info=(s); @env["PATH_INFO"] = s.to_s end
-
-
-
# Checks the HTTP request method (or verb) to see if it was of type DELETE
-
1
def delete?; request_method == "DELETE" end
-
-
# Checks the HTTP request method (or verb) to see if it was of type GET
-
1
def get?; request_method == "GET" end
-
-
# Checks the HTTP request method (or verb) to see if it was of type HEAD
-
1
def head?; request_method == "HEAD" end
-
-
# Checks the HTTP request method (or verb) to see if it was of type OPTIONS
-
1
def options?; request_method == "OPTIONS" end
-
-
# Checks the HTTP request method (or verb) to see if it was of type PATCH
-
1
def patch?; request_method == "PATCH" end
-
-
# Checks the HTTP request method (or verb) to see if it was of type POST
-
1
def post?; request_method == "POST" end
-
-
# Checks the HTTP request method (or verb) to see if it was of type PUT
-
1
def put?; request_method == "PUT" end
-
-
# Checks the HTTP request method (or verb) to see if it was of type TRACE
-
1
def trace?; request_method == "TRACE" end
-
-
-
# The set of form-data media-types. Requests that do not indicate
-
# one of the media types presents in this list will not be eligible
-
# for form-data / param parsing.
-
1
FORM_DATA_MEDIA_TYPES = [
-
'application/x-www-form-urlencoded',
-
'multipart/form-data'
-
]
-
-
# The set of media-types. Requests that do not indicate
-
# one of the media types presents in this list will not be eligible
-
# for param parsing like soap attachments or generic multiparts
-
1
PARSEABLE_DATA_MEDIA_TYPES = [
-
'multipart/related',
-
'multipart/mixed'
-
]
-
-
# Default ports depending on scheme. Used to decide whether or not
-
# to include the port in a generated URI.
-
1
DEFAULT_PORTS = { 'http' => 80, 'https' => 443, 'coffee' => 80 }
-
-
# Determine whether the request body contains form-data by checking
-
# the request Content-Type for one of the media-types:
-
# "application/x-www-form-urlencoded" or "multipart/form-data". The
-
# list of form-data media types can be modified through the
-
# +FORM_DATA_MEDIA_TYPES+ array.
-
#
-
# A request body is also assumed to contain form-data when no
-
# Content-Type header is provided and the request_method is POST.
-
1
def form_data?
-
type = media_type
-
meth = env["rack.methodoverride.original_method"] || env['REQUEST_METHOD']
-
(meth == 'POST' && type.nil?) || FORM_DATA_MEDIA_TYPES.include?(type)
-
end
-
-
# Determine whether the request body contains data by checking
-
# the request media_type against registered parse-data media-types
-
1
def parseable_data?
-
PARSEABLE_DATA_MEDIA_TYPES.include?(media_type)
-
end
-
-
# Returns the data received in the query string.
-
1
def GET
-
if @env["rack.request.query_string"] == query_string
-
@env["rack.request.query_hash"]
-
else
-
@env["rack.request.query_string"] = query_string
-
@env["rack.request.query_hash"] = parse_query(query_string)
-
end
-
end
-
-
# Returns the data received in the request body.
-
#
-
# This method support both application/x-www-form-urlencoded and
-
# multipart/form-data.
-
1
def POST
-
if @env["rack.input"].nil?
-
raise "Missing rack.input"
-
elsif @env["rack.request.form_input"].eql? @env["rack.input"]
-
@env["rack.request.form_hash"]
-
elsif form_data? || parseable_data?
-
@env["rack.request.form_input"] = @env["rack.input"]
-
unless @env["rack.request.form_hash"] = parse_multipart(env)
-
form_vars = @env["rack.input"].read
-
-
# Fix for Safari Ajax postings that always append \0
-
# form_vars.sub!(/\0\z/, '') # performance replacement:
-
form_vars.slice!(-1) if form_vars[-1] == ?\0
-
-
@env["rack.request.form_vars"] = form_vars
-
@env["rack.request.form_hash"] = parse_query(form_vars)
-
-
@env["rack.input"].rewind
-
end
-
@env["rack.request.form_hash"]
-
else
-
{}
-
end
-
end
-
-
# The union of GET and POST data.
-
#
-
# Note that modifications will not be persisted in the env. Use update_param or delete_param if you want to destructively modify params.
-
1
def params
-
@params ||= self.GET.merge(self.POST)
-
rescue EOFError
-
self.GET.dup
-
end
-
-
# Destructively update a parameter, whether it's in GET and/or POST. Returns nil.
-
#
-
# The parameter is updated wherever it was previous defined, so GET, POST, or both. If it wasn't previously defined, it's inserted into GET.
-
#
-
# env['rack.input'] is not touched.
-
1
def update_param(k, v)
-
found = false
-
if self.GET.has_key?(k)
-
found = true
-
self.GET[k] = v
-
end
-
if self.POST.has_key?(k)
-
found = true
-
self.POST[k] = v
-
end
-
unless found
-
self.GET[k] = v
-
end
-
@params = nil
-
nil
-
end
-
-
# Destructively delete a parameter, whether it's in GET or POST. Returns the value of the deleted parameter.
-
#
-
# If the parameter is in both GET and POST, the POST value takes precedence since that's how #params works.
-
#
-
# env['rack.input'] is not touched.
-
1
def delete_param(k)
-
v = [ self.POST.delete(k), self.GET.delete(k) ].compact.first
-
@params = nil
-
v
-
end
-
-
# shortcut for request.params[key]
-
1
def [](key)
-
params[key.to_s]
-
end
-
-
# shortcut for request.params[key] = value
-
#
-
# Note that modifications will not be persisted in the env. Use update_param or delete_param if you want to destructively modify params.
-
1
def []=(key, value)
-
params[key.to_s] = value
-
end
-
-
# like Hash#values_at
-
1
def values_at(*keys)
-
keys.map{|key| params[key] }
-
end
-
-
# the referer of the client
-
1
def referer
-
@env['HTTP_REFERER']
-
end
-
1
alias referrer referer
-
-
1
def user_agent
-
@env['HTTP_USER_AGENT']
-
end
-
-
1
def cookies
-
hash = @env["rack.request.cookie_hash"] ||= {}
-
string = @env["HTTP_COOKIE"]
-
-
return hash if string == @env["rack.request.cookie_string"]
-
hash.clear
-
-
# According to RFC 2109:
-
# If multiple cookies satisfy the criteria above, they are ordered in
-
# the Cookie header such that those with more specific Path attributes
-
# precede those with less specific. Ordering with respect to other
-
# attributes (e.g., Domain) is unspecified.
-
cookies = Utils.parse_query(string, ';,') { |s| Rack::Utils.unescape(s) rescue s }
-
cookies.each { |k,v| hash[k] = Array === v ? v.first : v }
-
@env["rack.request.cookie_string"] = string
-
hash
-
end
-
-
1
def xhr?
-
@env["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest"
-
end
-
-
1
def base_url
-
url = "#{scheme}://#{host}"
-
url << ":#{port}" if port != DEFAULT_PORTS[scheme]
-
url
-
end
-
-
# Tries to return a remake of the original request URL as a string.
-
1
def url
-
base_url + fullpath
-
end
-
-
1
def path
-
script_name + path_info
-
end
-
-
1
def fullpath
-
query_string.empty? ? path : "#{path}?#{query_string}"
-
end
-
-
1
def accept_encoding
-
@env["HTTP_ACCEPT_ENCODING"].to_s.split(/\s*,\s*/).map do |part|
-
encoding, parameters = part.split(/\s*;\s*/, 2)
-
quality = 1.0
-
if parameters and /\Aq=([\d.]+)/ =~ parameters
-
quality = $1.to_f
-
end
-
[encoding, quality]
-
end
-
end
-
-
1
def trusted_proxy?(ip)
-
ip =~ /\A127\.0\.0\.1\Z|\A(10|172\.(1[6-9]|2[0-9]|30|31)|192\.168)\.|\A::1\Z|\Afd[0-9a-f]{2}:.+|\Alocalhost\Z|\Aunix\Z|\Aunix:/i
-
end
-
-
1
def ip
-
remote_addrs = split_ip_addresses(@env['REMOTE_ADDR'])
-
remote_addrs = reject_trusted_ip_addresses(remote_addrs)
-
-
return remote_addrs.first if remote_addrs.any?
-
-
forwarded_ips = split_ip_addresses(@env['HTTP_X_FORWARDED_FOR'])
-
-
if client_ip = @env['HTTP_CLIENT_IP']
-
# If forwarded_ips doesn't include the client_ip, it might be an
-
# ip spoofing attempt, so we ignore HTTP_CLIENT_IP
-
return client_ip if forwarded_ips.include?(client_ip)
-
end
-
-
return reject_trusted_ip_addresses(forwarded_ips).last || @env["REMOTE_ADDR"]
-
end
-
-
1
protected
-
1
def split_ip_addresses(ip_addresses)
-
ip_addresses ? ip_addresses.strip.split(/[,\s]+/) : []
-
end
-
-
1
def reject_trusted_ip_addresses(ip_addresses)
-
ip_addresses.reject { |ip| trusted_proxy?(ip) }
-
end
-
-
1
def parse_query(qs)
-
Utils.parse_nested_query(qs)
-
end
-
-
1
def parse_multipart(env)
-
Rack::Multipart.parse_multipart(env)
-
end
-
end
-
end
-
1
require 'rack/request'
-
1
require 'rack/utils'
-
1
require 'time'
-
-
1
module Rack
-
# Rack::Response provides a convenient interface to create a Rack
-
# response.
-
#
-
# It allows setting of headers and cookies, and provides useful
-
# defaults (a OK response containing HTML).
-
#
-
# You can use Response#write to iteratively generate your response,
-
# but note that this is buffered by Rack::Response until you call
-
# +finish+. +finish+ however can take a block inside which calls to
-
# +write+ are synchronous with the Rack response.
-
#
-
# Your application's +call+ should end returning Response#finish.
-
-
1
class Response
-
1
attr_accessor :length
-
-
1
def initialize(body=[], status=200, header={})
-
@status = status.to_i
-
@header = Utils::HeaderHash.new.merge(header)
-
-
@chunked = "chunked" == @header['Transfer-Encoding']
-
@writer = lambda { |x| @body << x }
-
@block = nil
-
@length = 0
-
-
@body = []
-
-
if body.respond_to? :to_str
-
write body.to_str
-
elsif body.respond_to?(:each)
-
body.each { |part|
-
write part.to_s
-
}
-
else
-
raise TypeError, "stringable or iterable required"
-
end
-
-
yield self if block_given?
-
end
-
-
1
attr_reader :header
-
1
attr_accessor :status, :body
-
-
1
def [](key)
-
header[key]
-
end
-
-
1
def []=(key, value)
-
header[key] = value
-
end
-
-
1
def set_cookie(key, value)
-
Utils.set_cookie_header!(header, key, value)
-
end
-
-
1
def delete_cookie(key, value={})
-
Utils.delete_cookie_header!(header, key, value)
-
end
-
-
1
def redirect(target, status=302)
-
self.status = status
-
self["Location"] = target
-
end
-
-
1
def finish(&block)
-
@block = block
-
-
if [204, 205, 304].include?(status.to_i)
-
header.delete "Content-Type"
-
header.delete "Content-Length"
-
close
-
[status.to_i, header, []]
-
else
-
[status.to_i, header, BodyProxy.new(self){}]
-
end
-
end
-
1
alias to_a finish # For *response
-
1
alias to_ary finish # For implicit-splat on Ruby 1.9.2
-
-
1
def each(&callback)
-
@body.each(&callback)
-
@writer = callback
-
@block.call(self) if @block
-
end
-
-
# Append to body and update Content-Length.
-
#
-
# NOTE: Do not mix #write and direct #body access!
-
#
-
1
def write(str)
-
s = str.to_s
-
@length += Rack::Utils.bytesize(s) unless @chunked
-
@writer.call s
-
-
header["Content-Length"] = @length.to_s unless @chunked
-
str
-
end
-
-
1
def close
-
body.close if body.respond_to?(:close)
-
end
-
-
1
def empty?
-
@block == nil && @body.empty?
-
end
-
-
1
alias headers header
-
-
1
module Helpers
-
1
def invalid?; status < 100 || status >= 600; end
-
-
1
def informational?; status >= 100 && status < 200; end
-
1
def successful?; status >= 200 && status < 300; end
-
1
def redirection?; status >= 300 && status < 400; end
-
1
def client_error?; status >= 400 && status < 500; end
-
1
def server_error?; status >= 500 && status < 600; end
-
-
1
def ok?; status == 200; end
-
1
def bad_request?; status == 400; end
-
1
def forbidden?; status == 403; end
-
1
def not_found?; status == 404; end
-
1
def method_not_allowed?; status == 405; end
-
1
def unprocessable?; status == 422; end
-
-
1
def redirect?; [301, 302, 303, 307].include? status; end
-
-
# Headers
-
1
attr_reader :headers, :original_headers
-
-
1
def include?(header)
-
!!headers[header]
-
end
-
-
1
def content_type
-
headers["Content-Type"]
-
end
-
-
1
def content_length
-
cl = headers["Content-Length"]
-
cl ? cl.to_i : cl
-
end
-
-
1
def location
-
headers["Location"]
-
end
-
end
-
-
1
include Helpers
-
end
-
end
-
1
module Rack
-
# Sets an "X-Runtime" response header, indicating the response
-
# time of the request, in seconds
-
#
-
# You can put it right before the application to see the processing
-
# time, or before all the other middlewares to include time for them,
-
# too.
-
1
class Runtime
-
1
def initialize(app, name = nil)
-
1
@app = app
-
1
@header_name = "X-Runtime"
-
1
@header_name << "-#{name}" if name
-
end
-
-
1
def call(env)
-
start_time = Time.now
-
status, headers, body = @app.call(env)
-
request_time = Time.now - start_time
-
-
if !headers.has_key?(@header_name)
-
headers[@header_name] = "%0.6f" % request_time
-
end
-
-
[status, headers, body]
-
end
-
end
-
end
-
1
require 'rack/file'
-
-
1
module Rack
-
-
# = Sendfile
-
#
-
# The Sendfile middleware intercepts responses whose body is being
-
# served from a file and replaces it with a server specific X-Sendfile
-
# header. The web server is then responsible for writing the file contents
-
# to the client. This can dramatically reduce the amount of work required
-
# by the Ruby backend and takes advantage of the web server's optimized file
-
# delivery code.
-
#
-
# In order to take advantage of this middleware, the response body must
-
# respond to +to_path+ and the request must include an X-Sendfile-Type
-
# header. Rack::File and other components implement +to_path+ so there's
-
# rarely anything you need to do in your application. The X-Sendfile-Type
-
# header is typically set in your web servers configuration. The following
-
# sections attempt to document
-
#
-
# === Nginx
-
#
-
# Nginx supports the X-Accel-Redirect header. This is similar to X-Sendfile
-
# but requires parts of the filesystem to be mapped into a private URL
-
# hierarachy.
-
#
-
# The following example shows the Nginx configuration required to create
-
# a private "/files/" area, enable X-Accel-Redirect, and pass the special
-
# X-Sendfile-Type and X-Accel-Mapping headers to the backend:
-
#
-
# location ~ /files/(.*) {
-
# internal;
-
# alias /var/www/$1;
-
# }
-
#
-
# location / {
-
# proxy_redirect off;
-
#
-
# proxy_set_header Host $host;
-
# proxy_set_header X-Real-IP $remote_addr;
-
# proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
-
#
-
# proxy_set_header X-Sendfile-Type X-Accel-Redirect;
-
# proxy_set_header X-Accel-Mapping /var/www/=/files/;
-
#
-
# proxy_pass http://127.0.0.1:8080/;
-
# }
-
#
-
# Note that the X-Sendfile-Type header must be set exactly as shown above.
-
# The X-Accel-Mapping header should specify the location on the file system,
-
# followed by an equals sign (=), followed name of the private URL pattern
-
# that it maps to. The middleware performs a simple substitution on the
-
# resulting path.
-
#
-
# See Also: http://wiki.codemongers.com/NginxXSendfile
-
#
-
# === lighttpd
-
#
-
# Lighttpd has supported some variation of the X-Sendfile header for some
-
# time, although only recent version support X-Sendfile in a reverse proxy
-
# configuration.
-
#
-
# $HTTP["host"] == "example.com" {
-
# proxy-core.protocol = "http"
-
# proxy-core.balancer = "round-robin"
-
# proxy-core.backends = (
-
# "127.0.0.1:8000",
-
# "127.0.0.1:8001",
-
# ...
-
# )
-
#
-
# proxy-core.allow-x-sendfile = "enable"
-
# proxy-core.rewrite-request = (
-
# "X-Sendfile-Type" => (".*" => "X-Sendfile")
-
# )
-
# }
-
#
-
# See Also: http://redmine.lighttpd.net/wiki/lighttpd/Docs:ModProxyCore
-
#
-
# === Apache
-
#
-
# X-Sendfile is supported under Apache 2.x using a separate module:
-
#
-
# https://tn123.org/mod_xsendfile/
-
#
-
# Once the module is compiled and installed, you can enable it using
-
# XSendFile config directive:
-
#
-
# RequestHeader Set X-Sendfile-Type X-Sendfile
-
# ProxyPassReverse / http://localhost:8001/
-
# XSendFile on
-
#
-
# === Mapping parameter
-
#
-
# The third parameter allows for an overriding extension of the
-
# X-Accel-Mapping header. Mappings should be provided in tuples of internal to
-
# external. The internal values may contain regular expression syntax, they
-
# will be matched with case indifference.
-
-
1
class Sendfile
-
1
F = ::File
-
-
1
def initialize(app, variation=nil, mappings=[])
-
1
@app = app
-
1
@variation = variation
-
1
@mappings = mappings.map do |internal, external|
-
[/^#{internal}/i, external]
-
end
-
end
-
-
1
def call(env)
-
status, headers, body = @app.call(env)
-
if body.respond_to?(:to_path)
-
case type = variation(env)
-
when 'X-Accel-Redirect'
-
path = F.expand_path(body.to_path)
-
if url = map_accel_path(env, path)
-
headers['Content-Length'] = '0'
-
headers[type] = url
-
body.close if body.respond_to?(:close)
-
body = []
-
else
-
env['rack.errors'].puts "X-Accel-Mapping header missing"
-
end
-
when 'X-Sendfile', 'X-Lighttpd-Send-File'
-
path = F.expand_path(body.to_path)
-
headers['Content-Length'] = '0'
-
headers[type] = path
-
body.close if body.respond_to?(:close)
-
body = []
-
when '', nil
-
else
-
env['rack.errors'].puts "Unknown x-sendfile variation: '#{variation}'.\n"
-
end
-
end
-
[status, headers, body]
-
end
-
-
1
private
-
1
def variation(env)
-
@variation ||
-
env['sendfile.type'] ||
-
env['HTTP_X_SENDFILE_TYPE']
-
end
-
-
1
def map_accel_path(env, path)
-
if mapping = @mappings.find { |internal,_| internal =~ path }
-
path.sub(*mapping)
-
elsif mapping = env['HTTP_X_ACCEL_MAPPING']
-
internal, external = mapping.split('=', 2).map{ |p| p.strip }
-
path.sub(/^#{internal}/i, external)
-
end
-
end
-
end
-
end
-
# AUTHOR: blink <blinketje@gmail.com>; blink#ruby-lang@irc.freenode.net
-
# bugrep: Andreas Zehnder
-
-
1
require 'time'
-
1
require 'rack/request'
-
1
require 'rack/response'
-
1
begin
-
1
require 'securerandom'
-
rescue LoadError
-
# We just won't get securerandom
-
end
-
-
1
module Rack
-
-
1
module Session
-
-
1
module Abstract
-
1
ENV_SESSION_KEY = 'rack.session'.freeze
-
1
ENV_SESSION_OPTIONS_KEY = 'rack.session.options'.freeze
-
-
# SessionHash is responsible to lazily load the session from store.
-
-
1
class SessionHash
-
1
include Enumerable
-
1
attr_writer :id
-
-
1
def self.find(env)
-
env[ENV_SESSION_KEY]
-
end
-
-
1
def self.set(env, session)
-
env[ENV_SESSION_KEY] = session
-
end
-
-
1
def self.set_options(env, options)
-
env[ENV_SESSION_OPTIONS_KEY] = options.dup
-
end
-
-
1
def initialize(store, env)
-
@store = store
-
@env = env
-
@loaded = false
-
end
-
-
1
def id
-
return @id if @loaded or instance_variable_defined?(:@id)
-
@id = @store.send(:extract_session_id, @env)
-
end
-
-
1
def options
-
@env[ENV_SESSION_OPTIONS_KEY]
-
end
-
-
1
def each(&block)
-
load_for_read!
-
@data.each(&block)
-
end
-
-
1
def [](key)
-
load_for_read!
-
@data[key.to_s]
-
end
-
1
alias :fetch :[]
-
-
1
def has_key?(key)
-
load_for_read!
-
@data.has_key?(key.to_s)
-
end
-
1
alias :key? :has_key?
-
1
alias :include? :has_key?
-
-
1
def []=(key, value)
-
load_for_write!
-
@data[key.to_s] = value
-
end
-
1
alias :store :[]=
-
-
1
def clear
-
load_for_write!
-
@data.clear
-
end
-
-
1
def destroy
-
clear
-
@id = @store.send(:destroy_session, @env, id, options)
-
end
-
-
1
def to_hash
-
load_for_read!
-
@data.dup
-
end
-
-
1
def update(hash)
-
load_for_write!
-
@data.update(stringify_keys(hash))
-
end
-
1
alias :merge! :update
-
-
1
def replace(hash)
-
load_for_write!
-
@data.replace(stringify_keys(hash))
-
end
-
-
1
def delete(key)
-
load_for_write!
-
@data.delete(key.to_s)
-
end
-
-
1
def inspect
-
if loaded?
-
@data.inspect
-
else
-
"#<#{self.class}:0x#{self.object_id.to_s(16)} not yet loaded>"
-
end
-
end
-
-
1
def exists?
-
return @exists if instance_variable_defined?(:@exists)
-
@data = {}
-
@exists = @store.send(:session_exists?, @env)
-
end
-
-
1
def loaded?
-
@loaded
-
end
-
-
1
def empty?
-
load_for_read!
-
@data.empty?
-
end
-
-
1
def keys
-
@data.keys
-
end
-
-
1
def values
-
@data.values
-
end
-
-
1
private
-
-
1
def load_for_read!
-
load! if !loaded? && exists?
-
end
-
-
1
def load_for_write!
-
load! unless loaded?
-
end
-
-
1
def load!
-
@id, session = @store.send(:load_session, @env)
-
@data = stringify_keys(session)
-
@loaded = true
-
end
-
-
1
def stringify_keys(other)
-
hash = {}
-
other.each do |key, value|
-
hash[key.to_s] = value
-
end
-
hash
-
end
-
end
-
-
# ID sets up a basic framework for implementing an id based sessioning
-
# service. Cookies sent to the client for maintaining sessions will only
-
# contain an id reference. Only #get_session and #set_session are
-
# required to be overwritten.
-
#
-
# All parameters are optional.
-
# * :key determines the name of the cookie, by default it is
-
# 'rack.session'
-
# * :path, :domain, :expire_after, :secure, and :httponly set the related
-
# cookie options as by Rack::Response#add_cookie
-
# * :skip will not a set a cookie in the response nor update the session state
-
# * :defer will not set a cookie in the response but still update the session
-
# state if it is used with a backend
-
# * :renew (implementation dependent) will prompt the generation of a new
-
# session id, and migration of data to be referenced at the new id. If
-
# :defer is set, it will be overridden and the cookie will be set.
-
# * :sidbits sets the number of bits in length that a generated session
-
# id will be.
-
#
-
# These options can be set on a per request basis, at the location of
-
# env['rack.session.options']. Additionally the id of the session can be
-
# found within the options hash at the key :id. It is highly not
-
# recommended to change its value.
-
#
-
# Is Rack::Utils::Context compatible.
-
#
-
# Not included by default; you must require 'rack/session/abstract/id'
-
# to use.
-
-
1
class ID
-
1
DEFAULT_OPTIONS = {
-
:key => 'rack.session',
-
:path => '/',
-
:domain => nil,
-
:expire_after => nil,
-
:secure => false,
-
:httponly => true,
-
:defer => false,
-
:renew => false,
-
:sidbits => 128,
-
:cookie_only => true,
-
1
:secure_random => (::SecureRandom rescue false)
-
}
-
-
1
attr_reader :key, :default_options
-
-
1
def initialize(app, options={})
-
1
@app = app
-
1
@default_options = self.class::DEFAULT_OPTIONS.merge(options)
-
1
@key = @default_options.delete(:key)
-
1
@cookie_only = @default_options.delete(:cookie_only)
-
1
initialize_sid
-
end
-
-
1
def call(env)
-
context(env)
-
end
-
-
1
def context(env, app=@app)
-
prepare_session(env)
-
status, headers, body = app.call(env)
-
commit_session(env, status, headers, body)
-
end
-
-
1
private
-
-
1
def initialize_sid
-
@sidbits = @default_options[:sidbits]
-
@sid_secure = @default_options[:secure_random]
-
@sid_length = @sidbits / 4
-
end
-
-
# Generate a new session id using Ruby #rand. The size of the
-
# session id is controlled by the :sidbits option.
-
# Monkey patch this to use custom methods for session id generation.
-
-
1
def generate_sid(secure = @sid_secure)
-
if secure
-
secure.hex(@sid_length)
-
else
-
"%0#{@sid_length}x" % Kernel.rand(2**@sidbits - 1)
-
end
-
rescue NotImplementedError
-
generate_sid(false)
-
end
-
-
# Sets the lazy session at 'rack.session' and places options and session
-
# metadata into 'rack.session.options'.
-
-
1
def prepare_session(env)
-
session_was = env[ENV_SESSION_KEY]
-
env[ENV_SESSION_KEY] = session_class.new(self, env)
-
env[ENV_SESSION_OPTIONS_KEY] = @default_options.dup
-
env[ENV_SESSION_KEY].merge! session_was if session_was
-
end
-
-
# Extracts the session id from provided cookies and passes it and the
-
# environment to #get_session.
-
-
1
def load_session(env)
-
sid = current_session_id(env)
-
sid, session = get_session(env, sid)
-
[sid, session || {}]
-
end
-
-
# Extract session id from request object.
-
-
1
def extract_session_id(env)
-
request = Rack::Request.new(env)
-
sid = request.cookies[@key]
-
sid ||= request.params[@key] unless @cookie_only
-
sid
-
end
-
-
# Returns the current session id from the SessionHash.
-
-
1
def current_session_id(env)
-
env[ENV_SESSION_KEY].id
-
end
-
-
# Check if the session exists or not.
-
-
1
def session_exists?(env)
-
value = current_session_id(env)
-
value && !value.empty?
-
end
-
-
# Session should be commited if it was loaded, any of specific options like :renew, :drop
-
# or :expire_after was given and the security permissions match. Skips if skip is given.
-
-
1
def commit_session?(env, session, options)
-
if options[:skip]
-
false
-
else
-
has_session = loaded_session?(session) || forced_session_update?(session, options)
-
has_session && security_matches?(env, options)
-
end
-
end
-
-
1
def loaded_session?(session)
-
!session.is_a?(session_class) || session.loaded?
-
end
-
-
1
def forced_session_update?(session, options)
-
force_options?(options) && session && !session.empty?
-
end
-
-
1
def force_options?(options)
-
options.values_at(:renew, :drop, :defer, :expire_after).any?
-
end
-
-
1
def security_matches?(env, options)
-
return true unless options[:secure]
-
request = Rack::Request.new(env)
-
request.ssl?
-
end
-
-
# Acquires the session from the environment and the session id from
-
# the session options and passes them to #set_session. If successful
-
# and the :defer option is not true, a cookie will be added to the
-
# response with the session's id.
-
-
1
def commit_session(env, status, headers, body)
-
session = env[ENV_SESSION_KEY]
-
options = session.options
-
-
if options[:drop] || options[:renew]
-
session_id = destroy_session(env, session.id || generate_sid, options)
-
return [status, headers, body] unless session_id
-
end
-
-
return [status, headers, body] unless commit_session?(env, session, options)
-
-
session.send(:load!) unless loaded_session?(session)
-
session_id ||= session.id
-
session_data = session.to_hash.delete_if { |k,v| v.nil? }
-
-
if not data = set_session(env, session_id, session_data, options)
-
env["rack.errors"].puts("Warning! #{self.class.name} failed to save session. Content dropped.")
-
elsif options[:defer] and not options[:renew]
-
env["rack.errors"].puts("Defering cookie for #{session_id}") if $VERBOSE
-
else
-
cookie = Hash.new
-
cookie[:value] = data
-
cookie[:expires] = Time.now + options[:expire_after] if options[:expire_after]
-
set_cookie(env, headers, cookie.merge!(options))
-
end
-
-
[status, headers, body]
-
end
-
-
# Sets the cookie back to the client with session id. We skip the cookie
-
# setting if the value didn't change (sid is the same) or expires was given.
-
-
1
def set_cookie(env, headers, cookie)
-
request = Rack::Request.new(env)
-
if request.cookies[@key] != cookie[:value] || cookie[:expires]
-
Utils.set_cookie_header!(headers, @key, cookie)
-
end
-
end
-
-
# Allow subclasses to prepare_session for different Session classes
-
-
1
def session_class
-
SessionHash
-
end
-
-
# All thread safety and session retrival proceedures should occur here.
-
# Should return [session_id, session].
-
# If nil is provided as the session id, generation of a new valid id
-
# should occur within.
-
-
1
def get_session(env, sid)
-
raise '#get_session not implemented.'
-
end
-
-
# All thread safety and session storage proceedures should occur here.
-
# Must return the session id if the session was saved successfully, or
-
# false if the session could not be saved.
-
-
1
def set_session(env, sid, session, options)
-
raise '#set_session not implemented.'
-
end
-
-
# All thread safety and session destroy proceedures should occur here.
-
# Should return a new session id or nil if options[:drop]
-
-
1
def destroy_session(env, sid, options)
-
raise '#destroy_session not implemented'
-
end
-
end
-
end
-
end
-
end
-
1
require 'openssl'
-
1
require 'rack/request'
-
1
require 'rack/response'
-
1
require 'rack/session/abstract/id'
-
-
1
module Rack
-
-
1
module Session
-
-
# Rack::Session::Cookie provides simple cookie based session management.
-
# By default, the session is a Ruby Hash stored as base64 encoded marshalled
-
# data set to :key (default: rack.session). The object that encodes the
-
# session data is configurable and must respond to +encode+ and +decode+.
-
# Both methods must take a string and return a string.
-
#
-
# When the secret key is set, cookie data is checked for data integrity.
-
# The old secret key is also accepted and allows graceful secret rotation.
-
#
-
# Example:
-
#
-
# use Rack::Session::Cookie, :key => 'rack.session',
-
# :domain => 'foo.com',
-
# :path => '/',
-
# :expire_after => 2592000,
-
# :secret => 'change_me',
-
# :old_secret => 'also_change_me'
-
#
-
# All parameters are optional.
-
#
-
# Example of a cookie with no encoding:
-
#
-
# Rack::Session::Cookie.new(application, {
-
# :coder => Rack::Session::Cookie::Identity.new
-
# })
-
#
-
# Example of a cookie with custom encoding:
-
#
-
# Rack::Session::Cookie.new(application, {
-
# :coder => Class.new {
-
# def encode(str); str.reverse; end
-
# def decode(str); str.reverse; end
-
# }.new
-
# })
-
#
-
-
1
class Cookie < Abstract::ID
-
# Encode session cookies as Base64
-
1
class Base64
-
1
def encode(str)
-
[str].pack('m')
-
end
-
-
1
def decode(str)
-
str.unpack('m').first
-
end
-
-
# Encode session cookies as Marshaled Base64 data
-
1
class Marshal < Base64
-
1
def encode(str)
-
super(::Marshal.dump(str))
-
end
-
-
1
def decode(str)
-
return unless str
-
::Marshal.load(super(str)) rescue nil
-
end
-
end
-
-
# N.B. Unlike other encoding methods, the contained objects must be a
-
# valid JSON composite type, either a Hash or an Array.
-
1
class JSON < Base64
-
1
def encode(obj)
-
super(::Rack::Utils::OkJson.encode(obj))
-
end
-
-
1
def decode(str)
-
return unless str
-
::Rack::Utils::OkJson.decode(super(str)) rescue nil
-
end
-
end
-
end
-
-
# Use no encoding for session cookies
-
1
class Identity
-
1
def encode(str); str; end
-
1
def decode(str); str; end
-
end
-
-
# Reverse string encoding. (trollface)
-
1
class Reverse
-
1
def encode(str); str.reverse; end
-
1
def decode(str); str.reverse; end
-
end
-
-
1
attr_reader :coder
-
-
1
def initialize(app, options={})
-
@secrets = options.values_at(:secret, :old_secret).compact
-
warn <<-MSG unless @secrets.size >= 1
-
SECURITY WARNING: No secret option provided to Rack::Session::Cookie.
-
This poses a security threat. It is strongly recommended that you
-
provide a secret to prevent exploits that may be possible from crafted
-
cookies. This will not be supported in future versions of Rack, and
-
future versions will even invalidate your existing user cookies.
-
-
Called from: #{caller[0]}.
-
MSG
-
@coder = options[:coder] ||= Base64::Marshal.new
-
super(app, options.merge!(:cookie_only => true))
-
end
-
-
1
private
-
-
1
def get_session(env, sid)
-
data = unpacked_cookie_data(env)
-
data = persistent_session_id!(data)
-
[data["session_id"], data]
-
end
-
-
1
def extract_session_id(env)
-
unpacked_cookie_data(env)["session_id"]
-
end
-
-
1
def unpacked_cookie_data(env)
-
env["rack.session.unpacked_cookie_data"] ||= begin
-
request = Rack::Request.new(env)
-
session_data = request.cookies[@key]
-
-
if @secrets.size > 0 && session_data
-
session_data, digest = session_data.split("--")
-
session_data = nil unless digest_match?(session_data, digest)
-
end
-
-
coder.decode(session_data) || {}
-
end
-
end
-
-
1
def persistent_session_id!(data, sid=nil)
-
data ||= {}
-
data["session_id"] ||= sid || generate_sid
-
data
-
end
-
-
1
def set_session(env, session_id, session, options)
-
session = session.merge("session_id" => session_id)
-
session_data = coder.encode(session)
-
-
if @secrets.first
-
session_data << "--#{generate_hmac(session_data, @secrets.first)}"
-
end
-
-
if session_data.size > (4096 - @key.size)
-
env["rack.errors"].puts("Warning! Rack::Session::Cookie data size exceeds 4K.")
-
nil
-
else
-
session_data
-
end
-
end
-
-
1
def destroy_session(env, session_id, options)
-
# Nothing to do here, data is in the client
-
generate_sid unless options[:drop]
-
end
-
-
1
def digest_match?(data, digest)
-
return unless data && digest
-
@secrets.any? do |secret|
-
Rack::Utils.secure_compare(digest, generate_hmac(data, secret))
-
end
-
end
-
-
1
def generate_hmac(data, secret)
-
OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA1.new, secret, data)
-
end
-
-
end
-
end
-
end
-
# -*- encoding: binary -*-
-
1
require 'fileutils'
-
1
require 'set'
-
1
require 'tempfile'
-
1
require 'rack/multipart'
-
1
require 'time'
-
-
4
major, minor, patch = RUBY_VERSION.split('.').map { |v| v.to_i }
-
-
1
if major == 1 && minor < 9
-
require 'rack/backports/uri/common_18'
-
elsif major == 1 && minor == 9 && patch == 2 && RUBY_PATCHLEVEL <= 320 && RUBY_ENGINE != 'jruby'
-
require 'rack/backports/uri/common_192'
-
elsif major == 1 && minor == 9 && patch == 3 && RUBY_PATCHLEVEL < 125
-
require 'rack/backports/uri/common_193'
-
else
-
1
require 'uri/common'
-
end
-
-
1
module Rack
-
# Rack::Utils contains a grab-bag of useful methods for writing web
-
# applications adopted from all kinds of Ruby libraries.
-
-
1
module Utils
-
# URI escapes. (CGI style space to +)
-
1
def escape(s)
-
URI.encode_www_form_component(s)
-
end
-
1
module_function :escape
-
-
# Like URI escaping, but with %20 instead of +. Strictly speaking this is
-
# true URI escaping.
-
1
def escape_path(s)
-
escape(s).gsub('+', '%20')
-
end
-
1
module_function :escape_path
-
-
# Unescapes a URI escaped string with +encoding+. +encoding+ will be the
-
# target encoding of the string returned, and it defaults to UTF-8
-
1
if defined?(::Encoding)
-
1
def unescape(s, encoding = Encoding::UTF_8)
-
URI.decode_www_form_component(s, encoding)
-
end
-
else
-
def unescape(s, encoding = nil)
-
URI.decode_www_form_component(s, encoding)
-
end
-
end
-
1
module_function :unescape
-
-
1
DEFAULT_SEP = /[&;] */n
-
-
1
class << self
-
1
attr_accessor :key_space_limit
-
end
-
-
# The default number of bytes to allow parameter keys to take up.
-
# This helps prevent a rogue client from flooding a Request.
-
1
self.key_space_limit = 65536
-
-
# Stolen from Mongrel, with some small modifications:
-
# Parses a query string by breaking it up at the '&'
-
# and ';' characters. You can also use this to parse
-
# cookies by changing the characters used in the second
-
# parameter (which defaults to '&;').
-
1
def parse_query(qs, d = nil, &unescaper)
-
unescaper ||= method(:unescape)
-
-
params = KeySpaceConstrainedParams.new
-
-
(qs || '').split(d ? /[#{d}] */n : DEFAULT_SEP).each do |p|
-
next if p.empty?
-
k, v = p.split('=', 2).map(&unescaper)
-
-
if cur = params[k]
-
if cur.class == Array
-
params[k] << v
-
else
-
params[k] = [cur, v]
-
end
-
else
-
params[k] = v
-
end
-
end
-
-
return params.to_params_hash
-
end
-
1
module_function :parse_query
-
-
1
def parse_nested_query(qs, d = nil)
-
params = KeySpaceConstrainedParams.new
-
-
(qs || '').split(d ? /[#{d}] */n : DEFAULT_SEP).each do |p|
-
k, v = p.split('=', 2).map { |s| unescape(s) }
-
-
normalize_params(params, k, v)
-
end
-
-
return params.to_params_hash
-
end
-
1
module_function :parse_nested_query
-
-
1
def normalize_params(params, name, v = nil)
-
name =~ %r(\A[\[\]]*([^\[\]]+)\]*)
-
k = $1 || ''
-
after = $' || ''
-
-
return if k.empty?
-
-
if after == ""
-
params[k] = v
-
elsif after == "[]"
-
params[k] ||= []
-
raise TypeError, "expected Array (got #{params[k].class.name}) for param `#{k}'" unless params[k].is_a?(Array)
-
params[k] << v
-
elsif after =~ %r(^\[\]\[([^\[\]]+)\]$) || after =~ %r(^\[\](.+)$)
-
child_key = $1
-
params[k] ||= []
-
raise TypeError, "expected Array (got #{params[k].class.name}) for param `#{k}'" unless params[k].is_a?(Array)
-
if params_hash_type?(params[k].last) && !params[k].last.key?(child_key)
-
normalize_params(params[k].last, child_key, v)
-
else
-
params[k] << normalize_params(params.class.new, child_key, v)
-
end
-
else
-
params[k] ||= params.class.new
-
raise TypeError, "expected Hash (got #{params[k].class.name}) for param `#{k}'" unless params_hash_type?(params[k])
-
params[k] = normalize_params(params[k], after, v)
-
end
-
-
return params
-
end
-
1
module_function :normalize_params
-
-
1
def params_hash_type?(obj)
-
obj.kind_of?(KeySpaceConstrainedParams) || obj.kind_of?(Hash)
-
end
-
1
module_function :params_hash_type?
-
-
1
def build_query(params)
-
params.map { |k, v|
-
if v.class == Array
-
build_query(v.map { |x| [k, x] })
-
else
-
v.nil? ? escape(k) : "#{escape(k)}=#{escape(v)}"
-
end
-
}.join("&")
-
end
-
1
module_function :build_query
-
-
1
def build_nested_query(value, prefix = nil)
-
case value
-
when Array
-
value.map { |v|
-
build_nested_query(v, "#{prefix}[]")
-
}.join("&")
-
when Hash
-
value.map { |k, v|
-
build_nested_query(v, prefix ? "#{prefix}[#{escape(k)}]" : escape(k))
-
}.join("&")
-
when String
-
raise ArgumentError, "value must be a Hash" if prefix.nil?
-
"#{prefix}=#{escape(value)}"
-
else
-
prefix
-
end
-
end
-
1
module_function :build_nested_query
-
-
1
def q_values(q_value_header)
-
q_value_header.to_s.split(/\s*,\s*/).map do |part|
-
value, parameters = part.split(/\s*;\s*/, 2)
-
quality = 1.0
-
if md = /\Aq=([\d.]+)/.match(parameters)
-
quality = md[1].to_f
-
end
-
[value, quality]
-
end
-
end
-
1
module_function :q_values
-
-
1
def best_q_match(q_value_header, available_mimes)
-
values = q_values(q_value_header)
-
-
values.map do |req_mime, quality|
-
match = available_mimes.first { |am| Rack::Mime.match?(am, req_mime) }
-
next unless match
-
[match, quality]
-
end.compact.sort_by do |match, quality|
-
(match.split('/', 2).count('*') * -10) + quality
-
end.last.first
-
end
-
1
module_function :best_q_match
-
-
1
ESCAPE_HTML = {
-
"&" => "&",
-
"<" => "<",
-
">" => ">",
-
"'" => "'",
-
'"' => """,
-
"/" => "/"
-
}
-
1
if //.respond_to?(:encoding)
-
1
ESCAPE_HTML_PATTERN = Regexp.union(*ESCAPE_HTML.keys)
-
else
-
# On 1.8, there is a kcode = 'u' bug that allows for XSS otherwhise
-
# TODO doesn't apply to jruby, so a better condition above might be preferable?
-
ESCAPE_HTML_PATTERN = /#{Regexp.union(*ESCAPE_HTML.keys)}/n
-
end
-
-
# Escape ampersands, brackets and quotes to their HTML/XML entities.
-
1
def escape_html(string)
-
string.to_s.gsub(ESCAPE_HTML_PATTERN){|c| ESCAPE_HTML[c] }
-
end
-
1
module_function :escape_html
-
-
1
def select_best_encoding(available_encodings, accept_encoding)
-
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
-
-
expanded_accept_encoding =
-
accept_encoding.map { |m, q|
-
if m == "*"
-
(available_encodings - accept_encoding.map { |m2, _| m2 }).map { |m2| [m2, q] }
-
else
-
[[m, q]]
-
end
-
}.inject([]) { |mem, list|
-
mem + list
-
}
-
-
encoding_candidates = expanded_accept_encoding.sort_by { |_, q| -q }.map { |m, _| m }
-
-
unless encoding_candidates.include?("identity")
-
encoding_candidates.push("identity")
-
end
-
-
expanded_accept_encoding.find_all { |m, q|
-
q == 0.0
-
}.each { |m, _|
-
encoding_candidates.delete(m)
-
}
-
-
return (encoding_candidates & available_encodings)[0]
-
end
-
1
module_function :select_best_encoding
-
-
1
def set_cookie_header!(header, key, value)
-
case value
-
when Hash
-
domain = "; domain=" + value[:domain] if value[:domain]
-
path = "; path=" + value[:path] if value[:path]
-
max_age = "; max-age=" + value[:max_age] if value[:max_age]
-
# There is an RFC mess in the area of date formatting for Cookies. Not
-
# only are there contradicting RFCs and examples within RFC text, but
-
# there are also numerous conflicting names of fields and partially
-
# cross-applicable specifications.
-
#
-
# These are best described in RFC 2616 3.3.1. This RFC text also
-
# specifies that RFC 822 as updated by RFC 1123 is preferred. That is a
-
# fixed length format with space-date delimeted fields.
-
#
-
# See also RFC 1123 section 5.2.14.
-
#
-
# RFC 6265 also specifies "sane-cookie-date" as RFC 1123 date, defined
-
# in RFC 2616 3.3.1. RFC 6265 also gives examples that clearly denote
-
# the space delimited format. These formats are compliant with RFC 2822.
-
#
-
# For reference, all involved RFCs are:
-
# RFC 822
-
# RFC 1123
-
# RFC 2109
-
# RFC 2616
-
# RFC 2822
-
# RFC 2965
-
# RFC 6265
-
expires = "; expires=" +
-
rfc2822(value[:expires].clone.gmtime) if value[:expires]
-
secure = "; secure" if value[:secure]
-
httponly = "; HttpOnly" if value[:httponly]
-
value = value[:value]
-
end
-
value = [value] unless Array === value
-
cookie = escape(key) + "=" +
-
value.map { |v| escape v }.join("&") +
-
"#{domain}#{path}#{max_age}#{expires}#{secure}#{httponly}"
-
-
case header["Set-Cookie"]
-
when nil, ''
-
header["Set-Cookie"] = cookie
-
when String
-
header["Set-Cookie"] = [header["Set-Cookie"], cookie].join("\n")
-
when Array
-
header["Set-Cookie"] = (header["Set-Cookie"] + [cookie]).join("\n")
-
end
-
-
nil
-
end
-
1
module_function :set_cookie_header!
-
-
1
def delete_cookie_header!(header, key, value = {})
-
case header["Set-Cookie"]
-
when nil, ''
-
cookies = []
-
when String
-
cookies = header["Set-Cookie"].split("\n")
-
when Array
-
cookies = header["Set-Cookie"]
-
end
-
-
cookies.reject! { |cookie|
-
if value[:domain]
-
cookie =~ /\A#{escape(key)}=.*domain=#{value[:domain]}/
-
elsif value[:path]
-
cookie =~ /\A#{escape(key)}=.*path=#{value[:path]}/
-
else
-
cookie =~ /\A#{escape(key)}=/
-
end
-
}
-
-
header["Set-Cookie"] = cookies.join("\n")
-
-
set_cookie_header!(header, key,
-
{:value => '', :path => nil, :domain => nil,
-
:max_age => '0',
-
:expires => Time.at(0) }.merge(value))
-
-
nil
-
end
-
1
module_function :delete_cookie_header!
-
-
# Return the bytesize of String; uses String#size under Ruby 1.8 and
-
# String#bytesize under 1.9.
-
1
if ''.respond_to?(:bytesize)
-
1
def bytesize(string)
-
string.bytesize
-
end
-
else
-
def bytesize(string)
-
string.size
-
end
-
end
-
1
module_function :bytesize
-
-
1
def rfc2822(time)
-
time.rfc2822
-
end
-
1
module_function :rfc2822
-
-
# Modified version of stdlib time.rb Time#rfc2822 to use '%d-%b-%Y' instead
-
# of '% %b %Y'.
-
# It assumes that the time is in GMT to comply to the RFC 2109.
-
#
-
# NOTE: I'm not sure the RFC says it requires GMT, but is ambigous enough
-
# that I'm certain someone implemented only that option.
-
# Do not use %a and %b from Time.strptime, it would use localized names for
-
# weekday and month.
-
#
-
1
def rfc2109(time)
-
wday = Time::RFC2822_DAY_NAME[time.wday]
-
mon = Time::RFC2822_MONTH_NAME[time.mon - 1]
-
time.strftime("#{wday}, %d-#{mon}-%Y %H:%M:%S GMT")
-
end
-
1
module_function :rfc2109
-
-
# Parses the "Range:" header, if present, into an array of Range objects.
-
# Returns nil if the header is missing or syntactically invalid.
-
# Returns an empty array if none of the ranges are satisfiable.
-
1
def byte_ranges(env, size)
-
# See <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35>
-
http_range = env['HTTP_RANGE']
-
return nil unless http_range && http_range =~ /bytes=([^;]+)/
-
ranges = []
-
$1.split(/,\s*/).each do |range_spec|
-
return nil unless range_spec =~ /(\d*)-(\d*)/
-
r0,r1 = $1, $2
-
if r0.empty?
-
return nil if r1.empty?
-
# suffix-byte-range-spec, represents trailing suffix of file
-
r0 = size - r1.to_i
-
r0 = 0 if r0 < 0
-
r1 = size - 1
-
else
-
r0 = r0.to_i
-
if r1.empty?
-
r1 = size - 1
-
else
-
r1 = r1.to_i
-
return nil if r1 < r0 # backwards range is syntactically invalid
-
r1 = size-1 if r1 >= size
-
end
-
end
-
ranges << (r0..r1) if r0 <= r1
-
end
-
ranges
-
end
-
1
module_function :byte_ranges
-
-
# Constant time string comparison.
-
1
def secure_compare(a, b)
-
return false unless bytesize(a) == bytesize(b)
-
-
l = a.unpack("C*")
-
-
r, i = 0, -1
-
b.each_byte { |v| r |= v ^ l[i+=1] }
-
r == 0
-
end
-
1
module_function :secure_compare
-
-
# Context allows the use of a compatible middleware at different points
-
# in a request handling stack. A compatible middleware must define
-
# #context which should take the arguments env and app. The first of which
-
# would be the request environment. The second of which would be the rack
-
# application that the request would be forwarded to.
-
1
class Context
-
1
attr_reader :for, :app
-
-
1
def initialize(app_f, app_r)
-
raise 'running context does not respond to #context' unless app_f.respond_to? :context
-
@for, @app = app_f, app_r
-
end
-
-
1
def call(env)
-
@for.context(env, @app)
-
end
-
-
1
def recontext(app)
-
self.class.new(@for, app)
-
end
-
-
1
def context(env, app=@app)
-
recontext(app).call(env)
-
end
-
end
-
-
# A case-insensitive Hash that preserves the original case of a
-
# header when set.
-
1
class HeaderHash < Hash
-
1
def self.new(hash={})
-
HeaderHash === hash ? hash : super(hash)
-
end
-
-
1
def initialize(hash={})
-
super()
-
@names = {}
-
hash.each { |k, v| self[k] = v }
-
end
-
-
1
def each
-
super do |k, v|
-
yield(k, v.respond_to?(:to_ary) ? v.to_ary.join("\n") : v)
-
end
-
end
-
-
1
def to_hash
-
hash = {}
-
each { |k,v| hash[k] = v }
-
hash
-
end
-
-
1
def [](k)
-
super(k) || super(@names[k.downcase])
-
end
-
-
1
def []=(k, v)
-
canonical = k.downcase
-
delete k if @names[canonical] && @names[canonical] != k # .delete is expensive, don't invoke it unless necessary
-
@names[k] = @names[canonical] = k
-
super k, v
-
end
-
-
1
def delete(k)
-
canonical = k.downcase
-
result = super @names.delete(canonical)
-
@names.delete_if { |name,| name.downcase == canonical }
-
result
-
end
-
-
1
def include?(k)
-
@names.include?(k) || @names.include?(k.downcase)
-
end
-
-
1
alias_method :has_key?, :include?
-
1
alias_method :member?, :include?
-
1
alias_method :key?, :include?
-
-
1
def merge!(other)
-
other.each { |k, v| self[k] = v }
-
self
-
end
-
-
1
def merge(other)
-
hash = dup
-
hash.merge! other
-
end
-
-
1
def replace(other)
-
clear
-
other.each { |k, v| self[k] = v }
-
self
-
end
-
end
-
-
1
class KeySpaceConstrainedParams
-
1
def initialize(limit = Utils.key_space_limit)
-
@limit = limit
-
@size = 0
-
@params = {}
-
end
-
-
1
def [](key)
-
@params[key]
-
end
-
-
1
def []=(key, value)
-
@size += key.size if key && !@params.key?(key)
-
raise RangeError, 'exceeded available parameter key space' if @size > @limit
-
@params[key] = value
-
end
-
-
1
def key?(key)
-
@params.key?(key)
-
end
-
-
1
def to_params_hash
-
hash = @params
-
hash.keys.each do |key|
-
value = hash[key]
-
if value.kind_of?(self.class)
-
hash[key] = value.to_params_hash
-
elsif value.kind_of?(Array)
-
value.map! {|x| x.kind_of?(self.class) ? x.to_params_hash : x}
-
end
-
end
-
hash
-
end
-
end
-
-
# Every standard HTTP code mapped to the appropriate message.
-
# Generated with:
-
# irb -ropen-uri -rnokogiri
-
# > Nokogiri::XML(open("http://www.iana.org/assignments/http-status-codes/http-status-codes.xml")).css("record").each{|r|
-
# puts "#{r.css('value').text} => '#{r.css('description').text}'"}
-
1
HTTP_STATUS_CODES = {
-
100 => 'Continue',
-
101 => 'Switching Protocols',
-
102 => 'Processing',
-
200 => 'OK',
-
201 => 'Created',
-
202 => 'Accepted',
-
203 => 'Non-Authoritative Information',
-
204 => 'No Content',
-
205 => 'Reset Content',
-
206 => 'Partial Content',
-
207 => 'Multi-Status',
-
208 => 'Already Reported',
-
226 => 'IM Used',
-
300 => 'Multiple Choices',
-
301 => 'Moved Permanently',
-
302 => 'Found',
-
303 => 'See Other',
-
304 => 'Not Modified',
-
305 => 'Use Proxy',
-
306 => 'Reserved',
-
307 => 'Temporary Redirect',
-
308 => 'Permanent Redirect',
-
400 => 'Bad Request',
-
401 => 'Unauthorized',
-
402 => 'Payment Required',
-
403 => 'Forbidden',
-
404 => 'Not Found',
-
405 => 'Method Not Allowed',
-
406 => 'Not Acceptable',
-
407 => 'Proxy Authentication Required',
-
408 => 'Request Timeout',
-
409 => 'Conflict',
-
410 => 'Gone',
-
411 => 'Length Required',
-
412 => 'Precondition Failed',
-
413 => 'Request Entity Too Large',
-
414 => 'Request-URI Too Long',
-
415 => 'Unsupported Media Type',
-
416 => 'Requested Range Not Satisfiable',
-
417 => 'Expectation Failed',
-
422 => 'Unprocessable Entity',
-
423 => 'Locked',
-
424 => 'Failed Dependency',
-
425 => 'Reserved for WebDAV advanced collections expired proposal',
-
426 => 'Upgrade Required',
-
427 => 'Unassigned',
-
428 => 'Precondition Required',
-
429 => 'Too Many Requests',
-
430 => 'Unassigned',
-
431 => 'Request Header Fields Too Large',
-
500 => 'Internal Server Error',
-
501 => 'Not Implemented',
-
502 => 'Bad Gateway',
-
503 => 'Service Unavailable',
-
504 => 'Gateway Timeout',
-
505 => 'HTTP Version Not Supported',
-
506 => 'Variant Also Negotiates (Experimental)',
-
507 => 'Insufficient Storage',
-
508 => 'Loop Detected',
-
509 => 'Unassigned',
-
510 => 'Not Extended',
-
511 => 'Network Authentication Required'
-
}
-
-
# Responses with HTTP status codes that should not have an entity body
-
1
STATUS_WITH_NO_ENTITY_BODY = Set.new((100..199).to_a << 204 << 205 << 304)
-
-
1
SYMBOL_TO_STATUS_CODE = Hash[*HTTP_STATUS_CODES.map { |code, message|
-
62
[message.downcase.gsub(/\s|-/, '_').to_sym, code]
-
}.flatten]
-
-
1
def status_code(status)
-
if status.is_a?(Symbol)
-
SYMBOL_TO_STATUS_CODE[status] || 500
-
else
-
status.to_i
-
end
-
end
-
1
module_function :status_code
-
-
1
Multipart = Rack::Multipart
-
-
end
-
end
-
1
module Rack
-
-
1
class MockSession # :nodoc:
-
1
attr_writer :cookie_jar
-
1
attr_reader :default_host
-
-
1
def initialize(app, default_host = Rack::Test::DEFAULT_HOST)
-
@app = app
-
@after_request = []
-
@default_host = default_host
-
@last_request = nil
-
@last_response = nil
-
end
-
-
1
def after_request(&block)
-
@after_request << block
-
end
-
-
1
def clear_cookies
-
@cookie_jar = Rack::Test::CookieJar.new([], @default_host)
-
end
-
-
1
def set_cookie(cookie, uri = nil)
-
cookie_jar.merge(cookie, uri)
-
end
-
-
1
def request(uri, env)
-
env["HTTP_COOKIE"] ||= cookie_jar.for(uri)
-
@last_request = Rack::Request.new(env)
-
status, headers, body = @app.call(@last_request.env)
-
-
@last_response = MockResponse.new(status, headers, body, env["rack.errors"].flush)
-
body.close if body.respond_to?(:close)
-
-
cookie_jar.merge(last_response.headers["Set-Cookie"], uri)
-
-
@after_request.each { |hook| hook.call }
-
-
if @last_response.respond_to?(:finish)
-
@last_response.finish
-
else
-
@last_response
-
end
-
end
-
-
# Return the last request issued in the session. Raises an error if no
-
# requests have been sent yet.
-
1
def last_request
-
raise Rack::Test::Error.new("No request yet. Request a page first.") unless @last_request
-
@last_request
-
end
-
-
# Return the last response received in the session. Raises an error if
-
# no requests have been sent yet.
-
1
def last_response
-
raise Rack::Test::Error.new("No response yet. Request a page first.") unless @last_response
-
@last_response
-
end
-
-
1
def cookie_jar
-
@cookie_jar ||= Rack::Test::CookieJar.new([], @default_host)
-
end
-
-
end
-
-
end
-
1
require "uri"
-
1
require "rack"
-
1
require "rack/mock_session"
-
1
require "rack/test/cookie_jar"
-
1
require "rack/test/mock_digest_request"
-
1
require "rack/test/utils"
-
1
require "rack/test/methods"
-
1
require "rack/test/uploaded_file"
-
-
1
module Rack
-
1
module Test
-
1
VERSION = "0.6.2"
-
-
1
DEFAULT_HOST = "example.org"
-
1
MULTIPART_BOUNDARY = "----------XnJLe9ZIbbGUYtzPQJ16u1"
-
-
# The common base class for exceptions raised by Rack::Test
-
1
class Error < StandardError; end
-
-
# This class represents a series of requests issued to a Rack app, sharing
-
# a single cookie jar
-
#
-
# Rack::Test::Session's methods are most often called through Rack::Test::Methods,
-
# which will automatically build a session when it's first used.
-
1
class Session
-
1
extend Forwardable
-
1
include Rack::Test::Utils
-
-
1
def_delegators :@rack_mock_session, :clear_cookies, :set_cookie, :last_response, :last_request
-
-
# Creates a Rack::Test::Session for a given Rack app or Rack::MockSession.
-
#
-
# Note: Generally, you won't need to initialize a Rack::Test::Session directly.
-
# Instead, you should include Rack::Test::Methods into your testing context.
-
# (See README.rdoc for an example)
-
1
def initialize(mock_session)
-
@headers = {}
-
-
if mock_session.is_a?(MockSession)
-
@rack_mock_session = mock_session
-
else
-
@rack_mock_session = MockSession.new(mock_session)
-
end
-
-
@default_host = @rack_mock_session.default_host
-
end
-
-
# Issue a GET request for the given URI with the given params and Rack
-
# environment. Stores the issues request object in #last_request and
-
# the app's response in #last_response. Yield #last_response to a block
-
# if given.
-
#
-
# Example:
-
# get "/"
-
1
def get(uri, params = {}, env = {}, &block)
-
env = env_for(uri, env.merge(:method => "GET", :params => params))
-
process_request(uri, env, &block)
-
end
-
-
# Issue a POST request for the given URI. See #get
-
#
-
# Example:
-
# post "/signup", "name" => "Bryan"
-
1
def post(uri, params = {}, env = {}, &block)
-
env = env_for(uri, env.merge(:method => "POST", :params => params))
-
process_request(uri, env, &block)
-
end
-
-
# Issue a PUT request for the given URI. See #get
-
#
-
# Example:
-
# put "/"
-
1
def put(uri, params = {}, env = {}, &block)
-
env = env_for(uri, env.merge(:method => "PUT", :params => params))
-
process_request(uri, env, &block)
-
end
-
-
# Issue a PATCH request for the given URI. See #get
-
#
-
# Example:
-
# patch "/"
-
1
def patch(uri, params = {}, env = {}, &block)
-
env = env_for(uri, env.merge(:method => "PATCH", :params => params))
-
process_request(uri, env, &block)
-
end
-
-
# Issue a DELETE request for the given URI. See #get
-
#
-
# Example:
-
# delete "/"
-
1
def delete(uri, params = {}, env = {}, &block)
-
env = env_for(uri, env.merge(:method => "DELETE", :params => params))
-
process_request(uri, env, &block)
-
end
-
-
# Issue an OPTIONS request for the given URI. See #get
-
#
-
# Example:
-
# options "/"
-
1
def options(uri, params = {}, env = {}, &block)
-
env = env_for(uri, env.merge(:method => "OPTIONS", :params => params))
-
process_request(uri, env, &block)
-
end
-
-
# Issue a HEAD request for the given URI. See #get
-
#
-
# Example:
-
# head "/"
-
1
def head(uri, params = {}, env = {}, &block)
-
env = env_for(uri, env.merge(:method => "HEAD", :params => params))
-
process_request(uri, env, &block)
-
end
-
-
# Issue a request to the Rack app for the given URI and optional Rack
-
# environment. Stores the issues request object in #last_request and
-
# the app's response in #last_response. Yield #last_response to a block
-
# if given.
-
#
-
# Example:
-
# request "/"
-
1
def request(uri, env = {}, &block)
-
env = env_for(uri, env)
-
process_request(uri, env, &block)
-
end
-
-
# Set a header to be included on all subsequent requests through the
-
# session. Use a value of nil to remove a previously configured header.
-
#
-
# In accordance with the Rack spec, headers will be included in the Rack
-
# environment hash in HTTP_USER_AGENT form.
-
#
-
# Example:
-
# header "User-Agent", "Firefox"
-
1
def header(name, value)
-
if value.nil?
-
@headers.delete(name)
-
else
-
@headers[name] = value
-
end
-
end
-
-
# Set the username and password for HTTP Basic authorization, to be
-
# included in subsequent requests in the HTTP_AUTHORIZATION header.
-
#
-
# Example:
-
# basic_authorize "bryan", "secret"
-
1
def basic_authorize(username, password)
-
encoded_login = ["#{username}:#{password}"].pack("m*")
-
header('Authorization', "Basic #{encoded_login}")
-
end
-
-
1
alias_method :authorize, :basic_authorize
-
-
# Set the username and password for HTTP Digest authorization, to be
-
# included in subsequent requests in the HTTP_AUTHORIZATION header.
-
#
-
# Example:
-
# digest_authorize "bryan", "secret"
-
1
def digest_authorize(username, password)
-
@digest_username = username
-
@digest_password = password
-
end
-
-
# Rack::Test will not follow any redirects automatically. This method
-
# will follow the redirect returned (including setting the Referer header
-
# on the new request) in the last response. If the last response was not
-
# a redirect, an error will be raised.
-
1
def follow_redirect!
-
unless last_response.redirect?
-
raise Error.new("Last response was not a redirect. Cannot follow_redirect!")
-
end
-
-
get(last_response["Location"], {}, { "HTTP_REFERER" => last_request.url })
-
end
-
-
1
private
-
-
1
def env_for(path, env)
-
uri = URI.parse(path)
-
uri.path = "/#{uri.path}" unless uri.path[0] == ?/
-
uri.host ||= @default_host
-
-
env = default_env.merge(env)
-
-
env["HTTP_HOST"] ||= [uri.host, (uri.port if uri.port != uri.default_port)].compact.join(":")
-
-
env.update("HTTPS" => "on") if URI::HTTPS === uri
-
env["HTTP_X_REQUESTED_WITH"] = "XMLHttpRequest" if env[:xhr]
-
-
# TODO: Remove this after Rack 1.1 has been released.
-
# Stringifying and upcasing methods has be commit upstream
-
env["REQUEST_METHOD"] ||= env[:method] ? env[:method].to_s.upcase : "GET"
-
-
if env["REQUEST_METHOD"] == "GET"
-
# merge :params with the query string
-
if params = env[:params]
-
params = parse_nested_query(params) if params.is_a?(String)
-
params.update(parse_nested_query(uri.query))
-
uri.query = build_nested_query(params)
-
end
-
elsif !env.has_key?(:input)
-
env["CONTENT_TYPE"] ||= "application/x-www-form-urlencoded"
-
-
if env[:params].is_a?(Hash)
-
if data = build_multipart(env[:params])
-
env[:input] = data
-
env["CONTENT_LENGTH"] ||= data.length.to_s
-
env["CONTENT_TYPE"] = "multipart/form-data; boundary=#{MULTIPART_BOUNDARY}"
-
else
-
env[:input] = params_to_string(env[:params])
-
end
-
else
-
env[:input] = env[:params]
-
end
-
end
-
-
env.delete(:params)
-
-
if env.has_key?(:cookie)
-
set_cookie(env.delete(:cookie), uri)
-
end
-
-
Rack::MockRequest.env_for(uri.to_s, env)
-
end
-
-
1
def process_request(uri, env)
-
uri = URI.parse(uri)
-
uri.host ||= @default_host
-
-
@rack_mock_session.request(uri, env)
-
-
if retry_with_digest_auth?(env)
-
auth_env = env.merge({
-
"HTTP_AUTHORIZATION" => digest_auth_header,
-
"rack-test.digest_auth_retry" => true
-
})
-
auth_env.delete('rack.request')
-
process_request(uri.path, auth_env)
-
else
-
yield last_response if block_given?
-
-
last_response
-
end
-
end
-
-
1
def digest_auth_header
-
challenge = last_response["WWW-Authenticate"].split(" ", 2).last
-
params = Rack::Auth::Digest::Params.parse(challenge)
-
-
params.merge!({
-
"username" => @digest_username,
-
"nc" => "00000001",
-
"cnonce" => "nonsensenonce",
-
"uri" => last_request.fullpath,
-
"method" => last_request.env["REQUEST_METHOD"],
-
})
-
-
params["response"] = MockDigestRequest.new(params).response(@digest_password)
-
-
"Digest #{params}"
-
end
-
-
1
def retry_with_digest_auth?(env)
-
last_response.status == 401 &&
-
digest_auth_configured? &&
-
!env["rack-test.digest_auth_retry"]
-
end
-
-
1
def digest_auth_configured?
-
@digest_username
-
end
-
-
1
def default_env
-
{ "rack.test" => true, "REMOTE_ADDR" => "127.0.0.1" }.merge(headers_for_env)
-
end
-
-
1
def headers_for_env
-
converted_headers = {}
-
-
@headers.each do |name, value|
-
env_key = name.upcase.gsub("-", "_")
-
env_key = "HTTP_" + env_key unless "CONTENT_TYPE" == env_key
-
converted_headers[env_key] = value
-
end
-
-
converted_headers
-
end
-
-
1
def params_to_string(params)
-
case params
-
when Hash then build_nested_query(params)
-
when nil then ""
-
else params
-
end
-
end
-
-
end
-
-
1
def self.encoding_aware_strings?
-
defined?(Encoding) && "".respond_to?(:encode)
-
end
-
-
end
-
end
-
1
module Rails12factor
-
end
-
-
1
require 'rails_serve_static_assets'
-
1
require 'rails_stdout_logging'
-
1
require 'rails_serve_static_assets/version'
-
1
require 'rails_serve_static_assets/railtie' if defined?(Rails)
-
1
module RailsServeStaticAssets
-
1
class Railtie < Rails::Railtie
-
1
config.before_initialize do
-
1
::Rails.configuration.serve_static_assets = true
-
1
::Rails.configuration.action_dispatch.x_sendfile_header = nil
-
end
-
end
-
end
-
1
module RailsServeStaticAssets
-
1
VERSION = "0.0.2"
-
end
-
1
require "rails_stdout_logging/version"
-
1
require "rails_stdout_logging/railtie" if defined?(Rails)
-
1
module RailsStdoutLogging
-
1
class Rails
-
1
def self.heroku_stdout_logger
-
1
logger = Logger.new(STDOUT)
-
1
logger = ActiveSupport::TaggedLogging.new(logger) if defined?(ActiveSupport::TaggedLogging)
-
1
logger.level = Logger.const_get(log_level)
-
1
logger
-
end
-
-
1
def self.log_level
-
1
([(ENV['LOG_LEVEL'] || ::Rails.application.config.log_level).to_s.upcase, "INFO"] & %w[DEBUG INFO WARN ERROR FATAL UNKNOWN]).compact.first
-
end
-
-
1
def self.set_logger
-
1
STDOUT.sync = true
-
end
-
end
-
end
-
1
require 'rails_stdout_logging/rails'
-
-
1
module RailsStdoutLogging
-
1
class Rails3 < Rails
-
1
def self.set_logger(config)
-
1
super()
-
1
::Rails.logger = config.logger = heroku_stdout_logger
-
end
-
end
-
end
-
1
require 'rails_stdout_logging/rails3'
-
-
1
module RailsStdoutLogging
-
1
class Railtie < ::Rails::Railtie
-
1
config.before_initialize do
-
1
Rails3.set_logger(config)
-
end
-
end
-
end
-
1
module RailsStdoutLogging
-
1
VERSION = "0.0.3"
-
end
-
1
require 'rails/ruby_version_check'
-
-
1
require 'pathname'
-
-
1
require 'active_support'
-
1
require 'active_support/dependencies/autoload'
-
1
require 'active_support/core_ext/kernel/reporting'
-
1
require 'active_support/core_ext/module/delegation'
-
1
require 'active_support/core_ext/array/extract_options'
-
-
1
require 'rails/application'
-
1
require 'rails/version'
-
-
1
require 'active_support/railtie'
-
1
require 'action_dispatch/railtie'
-
-
# For Ruby 1.9, UTF-8 is the default internal and external encoding.
-
1
silence_warnings do
-
1
Encoding.default_external = Encoding::UTF_8
-
1
Encoding.default_internal = Encoding::UTF_8
-
end
-
-
1
module Rails
-
1
extend ActiveSupport::Autoload
-
-
1
autoload :Info
-
1
autoload :InfoController
-
1
autoload :MailersController
-
1
autoload :WelcomeController
-
-
1
class << self
-
1
attr_accessor :application, :cache, :logger
-
-
1
delegate :initialize!, :initialized?, to: :application
-
-
# The Configuration instance used to configure the Rails environment
-
1
def configuration
-
2
application.config
-
end
-
-
1
def backtrace_cleaner
-
@backtrace_cleaner ||= begin
-
# Relies on Active Support, so we have to lazy load to postpone definition until AS has been loaded
-
require 'rails/backtrace_cleaner'
-
Rails::BacktraceCleaner.new
-
end
-
end
-
-
1
def root
-
7
application && application.config.root
-
end
-
-
1
def env
-
32
@_env ||= ActiveSupport::StringInquirer.new(ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development")
-
end
-
-
1
def env=(environment)
-
@_env = ActiveSupport::StringInquirer.new(environment)
-
end
-
-
# Returns all rails groups for loading based on:
-
#
-
# * The Rails environment;
-
# * The environment variable RAILS_GROUPS;
-
# * The optional envs given as argument and the hash with group dependencies;
-
#
-
# groups assets: [:development, :test]
-
#
-
# # Returns
-
# # => [:default, :development, :assets] for Rails.env == "development"
-
# # => [:default, :production] for Rails.env == "production"
-
1
def groups(*groups)
-
hash = groups.extract_options!
-
env = Rails.env
-
groups.unshift(:default, env)
-
groups.concat ENV["RAILS_GROUPS"].to_s.split(",")
-
groups.concat hash.map { |k, v| k if v.map(&:to_s).include?(env) }
-
groups.compact!
-
groups.uniq!
-
groups
-
end
-
-
1
def public_path
-
2
application && Pathname.new(application.paths["public"].first)
-
end
-
end
-
end
-
1
require "rails"
-
-
%w(
-
active_record
-
action_controller
-
action_view
-
action_mailer
-
rails/test_unit
-
sprockets
-
1
).each do |framework|
-
6
begin
-
6
require "#{framework}/railtie"
-
rescue LoadError
-
end
-
end
-
1
require 'fileutils'
-
1
require 'active_support/core_ext/hash/keys'
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'active_support/key_generator'
-
1
require 'active_support/message_verifier'
-
1
require 'rails/engine'
-
-
1
module Rails
-
# In Rails 3.0, a Rails::Application object was introduced which is nothing more than
-
# an Engine but with the responsibility of coordinating the whole boot process.
-
#
-
# == Initialization
-
#
-
# Rails::Application is responsible for executing all railties and engines
-
# initializers. It also executes some bootstrap initializers (check
-
# Rails::Application::Bootstrap) and finishing initializers, after all the others
-
# are executed (check Rails::Application::Finisher).
-
#
-
# == Configuration
-
#
-
# Besides providing the same configuration as Rails::Engine and Rails::Railtie,
-
# the application object has several specific configurations, for example
-
# "cache_classes", "consider_all_requests_local", "filter_parameters",
-
# "logger" and so forth.
-
#
-
# Check Rails::Application::Configuration to see them all.
-
#
-
# == Routes
-
#
-
# The application object is also responsible for holding the routes and reloading routes
-
# whenever the files change in development.
-
#
-
# == Middlewares
-
#
-
# The Application is also responsible for building the middleware stack.
-
#
-
# == Booting process
-
#
-
# The application is also responsible for setting up and executing the booting
-
# process. From the moment you require "config/application.rb" in your app,
-
# the booting process goes like this:
-
#
-
# 1) require "config/boot.rb" to setup load paths
-
# 2) require railties and engines
-
# 3) Define Rails.application as "class MyApp::Application < Rails::Application"
-
# 4) Run config.before_configuration callbacks
-
# 5) Load config/environments/ENV.rb
-
# 6) Run config.before_initialize callbacks
-
# 7) Run Railtie#initializer defined by railties, engines and application.
-
# One by one, each engine sets up its load paths, routes and runs its config/initializers/* files.
-
# 8) Custom Railtie#initializers added by railties, engines and applications are executed
-
# 9) Build the middleware stack and run to_prepare callbacks
-
# 10) Run config.before_eager_load and eager_load! if eager_load is true
-
# 11) Run config.after_initialize callbacks
-
#
-
# == Multiple Applications
-
#
-
# If you decide to define multiple applications, then the first application
-
# that is initialized will be set to +Rails.application+, unless you override
-
# it with a different application.
-
#
-
# To create a new application, you can instantiate a new instance of a class
-
# that has already been created:
-
#
-
# class Application < Rails::Application
-
# end
-
#
-
# first_application = Application.new
-
# second_application = Application.new(config: first_application.config)
-
#
-
# In the above example, the configuration from the first application was used
-
# to initialize the second application. You can also use the +initialize_copy+
-
# on one of the applications to create a copy of the application which shares
-
# the configuration.
-
#
-
# If you decide to define rake tasks, runners, or initializers in an
-
# application other than +Rails.application+, then you must run those
-
# these manually.
-
1
class Application < Engine
-
1
autoload :Bootstrap, 'rails/application/bootstrap'
-
1
autoload :Configuration, 'rails/application/configuration'
-
1
autoload :DefaultMiddlewareStack, 'rails/application/default_middleware_stack'
-
1
autoload :Finisher, 'rails/application/finisher'
-
1
autoload :Railties, 'rails/engine/railties'
-
1
autoload :RoutesReloader, 'rails/application/routes_reloader'
-
-
1
class << self
-
1
def inherited(base)
-
1
super
-
1
base.instance
-
end
-
-
# Makes the +new+ method public.
-
#
-
# Note that Rails::Application inherits from Rails::Engine, which
-
# inherits from Rails::Railtie and the +new+ method on Rails::Railtie is
-
# private
-
1
public :new
-
end
-
-
1
attr_accessor :assets, :sandbox
-
1
alias_method :sandbox?, :sandbox
-
1
attr_reader :reloaders
-
-
1
delegate :default_url_options, :default_url_options=, to: :routes
-
-
1
INITIAL_VARIABLES = [:config, :railties, :routes_reloader, :reloaders,
-
:routes, :helpers, :app_env_config, :secrets] # :nodoc:
-
-
1
def initialize(initial_variable_values = {}, &block)
-
1
super()
-
1
@initialized = false
-
1
@reloaders = []
-
1
@routes_reloader = nil
-
1
@app_env_config = nil
-
1
@ordered_railties = nil
-
1
@railties = nil
-
1
@message_verifiers = {}
-
-
1
Rails.application ||= self
-
-
1
add_lib_to_load_path!
-
1
ActiveSupport.run_load_hooks(:before_configuration, self)
-
-
1
initial_variable_values.each do |variable_name, value|
-
if INITIAL_VARIABLES.include?(variable_name)
-
instance_variable_set("@#{variable_name}", value)
-
end
-
end
-
-
1
instance_eval(&block) if block_given?
-
end
-
-
# Returns true if the application is initialized.
-
1
def initialized?
-
@initialized
-
end
-
-
# Implements call according to the Rack API. It simply
-
# dispatches the request to the underlying middleware stack.
-
1
def call(env)
-
env["ORIGINAL_FULLPATH"] = build_original_fullpath(env)
-
env["ORIGINAL_SCRIPT_NAME"] = env["SCRIPT_NAME"]
-
super(env)
-
end
-
-
# Reload application routes regardless if they changed or not.
-
1
def reload_routes!
-
routes_reloader.reload!
-
end
-
-
# Return the application's KeyGenerator
-
1
def key_generator
-
# number of iterations selected based on consultation with the google security
-
# team. Details at https://github.com/rails/rails/pull/6952#issuecomment-7661220
-
@caching_key_generator ||= begin
-
if secrets.secret_key_base
-
key_generator = ActiveSupport::KeyGenerator.new(secrets.secret_key_base, iterations: 1000)
-
ActiveSupport::CachingKeyGenerator.new(key_generator)
-
else
-
ActiveSupport::LegacyKeyGenerator.new(config.secret_token)
-
end
-
end
-
end
-
-
# Returns a message verifier object.
-
#
-
# This verifier can be used to generate and verify signed messages in the application.
-
#
-
# It is recommended not to use the same verifier for different things, so you can get different
-
# verifiers passing the +verifier_name+ argument.
-
#
-
# ==== Parameters
-
#
-
# * +verifier_name+ - the name of the message verifier.
-
#
-
# ==== Examples
-
#
-
# message = Rails.application.message_verifier('sensitive_data').generate('my sensible data')
-
# Rails.application.message_verifier('sensitive_data').verify(message)
-
# # => 'my sensible data'
-
#
-
# See the +ActiveSupport::MessageVerifier+ documentation for more information.
-
1
def message_verifier(verifier_name)
-
@message_verifiers[verifier_name] ||= begin
-
secret = key_generator.generate_key(verifier_name.to_s)
-
ActiveSupport::MessageVerifier.new(secret)
-
end
-
end
-
-
# Stores some of the Rails initial environment parameters which
-
# will be used by middlewares and engines to configure themselves.
-
1
def env_config
-
@app_env_config ||= begin
-
validate_secret_key_config!
-
-
super.merge({
-
"action_dispatch.parameter_filter" => config.filter_parameters,
-
"action_dispatch.redirect_filter" => config.filter_redirect,
-
"action_dispatch.secret_token" => config.secret_token,
-
"action_dispatch.secret_key_base" => secrets.secret_key_base,
-
"action_dispatch.show_exceptions" => config.action_dispatch.show_exceptions,
-
"action_dispatch.show_detailed_exceptions" => config.consider_all_requests_local,
-
"action_dispatch.logger" => Rails.logger,
-
"action_dispatch.backtrace_cleaner" => Rails.backtrace_cleaner,
-
"action_dispatch.key_generator" => key_generator,
-
"action_dispatch.http_auth_salt" => config.action_dispatch.http_auth_salt,
-
"action_dispatch.signed_cookie_salt" => config.action_dispatch.signed_cookie_salt,
-
"action_dispatch.encrypted_cookie_salt" => config.action_dispatch.encrypted_cookie_salt,
-
"action_dispatch.encrypted_signed_cookie_salt" => config.action_dispatch.encrypted_signed_cookie_salt,
-
"action_dispatch.cookies_serializer" => config.action_dispatch.cookies_serializer
-
})
-
end
-
end
-
-
# If you try to define a set of rake tasks on the instance, these will get
-
# passed up to the rake tasks defined on the application's class.
-
1
def rake_tasks(&block)
-
self.class.rake_tasks(&block)
-
end
-
-
# Sends the initializers to the +initializer+ method defined in the
-
# Rails::Initializable module. Each Rails::Application class has its own
-
# set of initializers, as defined by the Initializable module.
-
1
def initializer(name, opts={}, &block)
-
self.class.initializer(name, opts, &block)
-
end
-
-
# Sends any runner called in the instance of a new application up
-
# to the +runner+ method defined in Rails::Railtie.
-
1
def runner(&blk)
-
self.class.runner(&blk)
-
end
-
-
# Sends the +isolate_namespace+ method up to the class method.
-
1
def isolate_namespace(mod)
-
self.class.isolate_namespace(mod)
-
end
-
-
## Rails internal API
-
-
# This method is called just after an application inherits from Rails::Application,
-
# allowing the developer to load classes in lib and use them during application
-
# configuration.
-
#
-
# class MyApplication < Rails::Application
-
# require "my_backend" # in lib/my_backend
-
# config.i18n.backend = MyBackend
-
# end
-
#
-
# Notice this method takes into consideration the default root path. So if you
-
# are changing config.root inside your application definition or having a custom
-
# Rails application, you will need to add lib to $LOAD_PATH on your own in case
-
# you need to load files in lib/ during the application configuration as well.
-
1
def add_lib_to_load_path! #:nodoc:
-
1
path = File.join config.root, 'lib'
-
1
if File.exist?(path) && !$LOAD_PATH.include?(path)
-
$LOAD_PATH.unshift(path)
-
end
-
end
-
-
1
def require_environment! #:nodoc:
-
environment = paths["config/environment"].existent.first
-
require environment if environment
-
end
-
-
1
def routes_reloader #:nodoc:
-
5
@routes_reloader ||= RoutesReloader.new
-
end
-
-
# Returns an array of file paths appended with a hash of
-
# directories-extensions suitable for ActiveSupport::FileUpdateChecker
-
# API.
-
1
def watchable_args #:nodoc:
-
1
files, dirs = config.watchable_files.dup, config.watchable_dirs.dup
-
-
1
ActiveSupport::Dependencies.autoload_paths.each do |path|
-
15
dirs[path.to_s] = [:rb]
-
end
-
-
1
[files, dirs]
-
end
-
-
# Initialize the application passing the given group. By default, the
-
# group is :default
-
1
def initialize!(group=:default) #:nodoc:
-
1
raise "Application has been already initialized." if @initialized
-
1
run_initializers(group, self)
-
1
@initialized = true
-
1
self
-
end
-
-
1
def initializers #:nodoc:
-
Bootstrap.initializers_for(self) +
-
railties_initializers(super) +
-
1
Finisher.initializers_for(self)
-
end
-
-
1
def config #:nodoc:
-
172
@config ||= Application::Configuration.new(find_root_with_flag("config.ru", Dir.pwd))
-
end
-
-
1
def config=(configuration) #:nodoc:
-
@config = configuration
-
end
-
-
1
def secrets #:nodoc:
-
@secrets ||= begin
-
secrets = ActiveSupport::OrderedOptions.new
-
yaml = config.paths["config/secrets"].first
-
if File.exist?(yaml)
-
require "erb"
-
all_secrets = YAML.load(ERB.new(IO.read(yaml)).result) || {}
-
env_secrets = all_secrets[Rails.env]
-
secrets.merge!(env_secrets.symbolize_keys) if env_secrets
-
end
-
-
# Fallback to config.secret_key_base if secrets.secret_key_base isn't set
-
secrets.secret_key_base ||= config.secret_key_base
-
-
secrets
-
end
-
end
-
-
1
def secrets=(secrets) #:nodoc:
-
@secrets = secrets
-
end
-
-
1
def to_app #:nodoc:
-
self
-
end
-
-
1
def helpers_paths #:nodoc:
-
1
config.helpers_paths
-
end
-
-
1
console do
-
require "pp"
-
end
-
-
1
console do
-
unless ::Kernel.private_method_defined?(:y)
-
if RUBY_VERSION >= '2.0'
-
require "psych/y"
-
else
-
module ::Kernel
-
def y(*objects)
-
puts ::Psych.dump_stream(*objects)
-
end
-
private :y
-
end
-
end
-
end
-
end
-
-
1
protected
-
-
1
alias :build_middleware_stack :app
-
-
1
def run_tasks_blocks(app) #:nodoc:
-
railties.each { |r| r.run_tasks_blocks(app) }
-
super
-
require "rails/tasks"
-
task :environment do
-
ActiveSupport.on_load(:before_initialize) { config.eager_load = false }
-
-
require_environment!
-
end
-
end
-
-
1
def run_generators_blocks(app) #:nodoc:
-
railties.each { |r| r.run_generators_blocks(app) }
-
super
-
end
-
-
1
def run_runner_blocks(app) #:nodoc:
-
railties.each { |r| r.run_runner_blocks(app) }
-
super
-
end
-
-
1
def run_console_blocks(app) #:nodoc:
-
railties.each { |r| r.run_console_blocks(app) }
-
super
-
end
-
-
# Returns the ordered railties for this application considering railties_order.
-
1
def ordered_railties #:nodoc:
-
@ordered_railties ||= begin
-
1
order = config.railties_order.map do |railtie|
-
1
if railtie == :main_app
-
self
-
elsif railtie.respond_to?(:instance)
-
railtie.instance
-
else
-
1
railtie
-
end
-
end
-
-
1
all = (railties - order)
-
1
all.push(self) unless (all + order).include?(self)
-
1
order.push(:all) unless order.include?(:all)
-
-
1
index = order.index(:all)
-
1
order[index] = all
-
1
order.reverse.flatten
-
1
end
-
end
-
-
1
def railties_initializers(current) #:nodoc:
-
1
initializers = []
-
1
ordered_railties.each do |r|
-
34
if r == self
-
1
initializers += current
-
else
-
33
initializers += r.initializers
-
end
-
end
-
1
initializers
-
end
-
-
1
def default_middleware_stack #:nodoc:
-
1
default_stack = DefaultMiddlewareStack.new(self, config, paths)
-
1
default_stack.build_stack
-
end
-
-
1
def build_original_fullpath(env) #:nodoc:
-
path_info = env["PATH_INFO"]
-
query_string = env["QUERY_STRING"]
-
script_name = env["SCRIPT_NAME"]
-
-
if query_string.present?
-
"#{script_name}#{path_info}?#{query_string}"
-
else
-
"#{script_name}#{path_info}"
-
end
-
end
-
-
1
def validate_secret_key_config! #:nodoc:
-
if secrets.secret_key_base.blank? && config.secret_token.blank?
-
raise "Missing `secret_key_base` for '#{Rails.env}' environment, set this value in `config/secrets.yml`"
-
end
-
end
-
end
-
end
-
1
require "active_support/notifications"
-
1
require "active_support/dependencies"
-
1
require "active_support/descendants_tracker"
-
-
1
module Rails
-
1
class Application
-
1
module Bootstrap
-
1
include Initializable
-
-
1
initializer :load_environment_hook, group: :all do end
-
-
1
initializer :load_active_support, group: :all do
-
1
require "active_support/all" unless config.active_support.bare
-
end
-
-
1
initializer :set_eager_load, group: :all do
-
1
if config.eager_load.nil?
-
warn <<-INFO
-
config.eager_load is set to nil. Please update your config/environments/*.rb files accordingly:
-
-
* development - set it to false
-
* test - set it to false (unless you use a tool that preloads your test environment)
-
* production - set it to true
-
-
INFO
-
config.eager_load = config.cache_classes
-
end
-
end
-
-
# Initialize the logger early in the stack in case we need to log some deprecation.
-
1
initializer :initialize_logger, group: :all do
-
1
Rails.logger ||= config.logger || begin
-
1
path = config.paths["log"].first
-
1
unless File.exist? File.dirname path
-
FileUtils.mkdir_p File.dirname path
-
end
-
-
1
f = File.open path, 'a'
-
1
f.binmode
-
1
f.sync = config.autoflush_log # if true make sure every write flushes
-
-
1
logger = ActiveSupport::Logger.new f
-
1
logger.formatter = config.log_formatter
-
1
logger = ActiveSupport::TaggedLogging.new(logger)
-
1
logger
-
rescue StandardError
-
logger = ActiveSupport::TaggedLogging.new(ActiveSupport::Logger.new(STDERR))
-
logger.level = ActiveSupport::Logger::WARN
-
logger.warn(
-
"Rails Error: Unable to access log file. Please ensure that #{path} exists and is chmod 0666. " +
-
"The log level has been raised to WARN and the output directed to STDERR until the problem is fixed."
-
)
-
logger
-
end
-
-
1
Rails.logger.level = ActiveSupport::Logger.const_get(config.log_level.to_s.upcase)
-
end
-
-
# Initialize cache early in the stack so railties can make use of it.
-
1
initializer :initialize_cache, group: :all do
-
1
unless Rails.cache
-
1
Rails.cache = ActiveSupport::Cache.lookup_store(config.cache_store)
-
-
1
if Rails.cache.respond_to?(:middleware)
-
1
config.middleware.insert_before("Rack::Runtime", Rails.cache.middleware)
-
end
-
end
-
end
-
-
# Sets the dependency loading mechanism.
-
1
initializer :initialize_dependency_mechanism, group: :all do
-
1
ActiveSupport::Dependencies.mechanism = config.cache_classes ? :require : :load
-
end
-
-
1
initializer :bootstrap_hook, group: :all do |app|
-
1
ActiveSupport.run_load_hooks(:before_initialize, app)
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/kernel/reporting'
-
1
require 'active_support/file_update_checker'
-
1
require 'rails/engine/configuration'
-
-
1
module Rails
-
1
class Application
-
1
class Configuration < ::Rails::Engine::Configuration
-
1
attr_accessor :allow_concurrency, :asset_host, :assets, :autoflush_log,
-
:cache_classes, :cache_store, :consider_all_requests_local, :console,
-
:eager_load, :exceptions_app, :file_watcher, :filter_parameters,
-
:force_ssl, :helpers_paths, :logger, :log_formatter, :log_tags,
-
:railties_order, :relative_url_root, :secret_key_base, :secret_token,
-
:serve_static_assets, :ssl_options, :static_cache_control, :session_options,
-
:time_zone, :reload_classes_only_on_change,
-
:beginning_of_week, :filter_redirect
-
-
1
attr_writer :log_level
-
1
attr_reader :encoding
-
-
1
def initialize(*)
-
1
super
-
1
self.encoding = "utf-8"
-
1
@allow_concurrency = nil
-
1
@consider_all_requests_local = false
-
1
@filter_parameters = []
-
1
@filter_redirect = []
-
1
@helpers_paths = []
-
1
@serve_static_assets = true
-
1
@static_cache_control = nil
-
1
@force_ssl = false
-
1
@ssl_options = {}
-
1
@session_store = :cookie_store
-
1
@session_options = {}
-
1
@time_zone = "UTC"
-
1
@beginning_of_week = :monday
-
1
@log_level = nil
-
1
@middleware = app_middleware
-
1
@generators = app_generators
-
1
@cache_store = [ :file_store, "#{root}/tmp/cache/" ]
-
1
@railties_order = [:all]
-
1
@relative_url_root = ENV["RAILS_RELATIVE_URL_ROOT"]
-
1
@reload_classes_only_on_change = true
-
1
@file_watcher = ActiveSupport::FileUpdateChecker
-
1
@exceptions_app = nil
-
1
@autoflush_log = true
-
1
@log_formatter = ActiveSupport::Logger::SimpleFormatter.new
-
1
@eager_load = nil
-
1
@secret_token = nil
-
1
@secret_key_base = nil
-
-
1
@assets = ActiveSupport::OrderedOptions.new
-
1
@assets.enabled = true
-
1
@assets.paths = []
-
1
@assets.precompile = [ Proc.new { |path, fn| fn =~ /app\/assets/ && !%w(.js .css).include?(File.extname(path)) },
-
/(?:\/|\\|\A)application\.(css|js)$/ ]
-
1
@assets.prefix = "/assets"
-
1
@assets.version = '1.0'
-
1
@assets.debug = false
-
1
@assets.compile = true
-
1
@assets.digest = false
-
1
@assets.cache_store = [ :file_store, "#{root}/tmp/cache/assets/#{Rails.env}/" ]
-
1
@assets.js_compressor = nil
-
1
@assets.css_compressor = nil
-
1
@assets.logger = nil
-
end
-
-
1
def encoding=(value)
-
1
@encoding = value
-
1
silence_warnings do
-
1
Encoding.default_external = value
-
1
Encoding.default_internal = value
-
end
-
end
-
-
1
def paths
-
@paths ||= begin
-
1
paths = super
-
1
paths.add "config/database", with: "config/database.yml"
-
1
paths.add "config/secrets", with: "config/secrets.yml"
-
1
paths.add "config/environment", with: "config/environment.rb"
-
1
paths.add "lib/templates"
-
1
paths.add "log", with: "log/#{Rails.env}.log"
-
1
paths.add "public"
-
1
paths.add "public/javascripts"
-
1
paths.add "public/stylesheets"
-
1
paths.add "tmp"
-
1
paths
-
25
end
-
end
-
-
# Loads and returns the entire raw configuration of database from
-
# values stored in `config/database.yml`.
-
1
def database_configuration
-
1
yaml = Pathname.new(paths["config/database"].first || "")
-
-
1
config = if yaml.exist?
-
1
require "yaml"
-
1
require "erb"
-
1
YAML.load(ERB.new(yaml.read).result) || {}
-
elsif ENV['DATABASE_URL']
-
# Value from ENV['DATABASE_URL'] is set to default database connection
-
# by Active Record.
-
{}
-
else
-
raise "Could not load database configuration. No such file - #{yaml}"
-
end
-
-
1
config
-
rescue Psych::SyntaxError => e
-
raise "YAML syntax error occurred while parsing #{paths["config/database"].first}. " \
-
"Please note that YAML must be consistently indented using spaces. Tabs are not allowed. " \
-
"Error: #{e.message}"
-
rescue => e
-
raise e, "Cannot load `Rails.application.database_configuration`:\n#{e.message}", e.backtrace
-
end
-
-
1
def log_level
-
2
@log_level ||= Rails.env.production? ? :info : :debug
-
end
-
-
1
def colorize_logging
-
ActiveSupport::LogSubscriber.colorize_logging
-
end
-
-
1
def colorize_logging=(val)
-
ActiveSupport::LogSubscriber.colorize_logging = val
-
self.generators.colorize_logging = val
-
end
-
-
1
def session_store(*args)
-
3
if args.empty?
-
2
case @session_store
-
when :disabled
-
nil
-
when :active_record_store
-
begin
-
ActionDispatch::Session::ActiveRecordStore
-
rescue NameError
-
raise "`ActiveRecord::SessionStore` is extracted out of Rails into a gem. " \
-
"Please add `activerecord-session_store` to your Gemfile to use it."
-
end
-
when Symbol
-
2
ActionDispatch::Session.const_get(@session_store.to_s.camelize)
-
else
-
@session_store
-
end
-
else
-
1
@session_store = args.shift
-
1
@session_options = args.shift || {}
-
end
-
end
-
-
end
-
end
-
end
-
1
module Rails
-
1
class Application
-
1
class DefaultMiddlewareStack
-
1
attr_reader :config, :paths, :app
-
-
1
def initialize(app, config, paths)
-
1
@app = app
-
1
@config = config
-
1
@paths = paths
-
end
-
-
1
def build_stack
-
1
ActionDispatch::MiddlewareStack.new.tap do |middleware|
-
1
if config.force_ssl
-
middleware.use ::ActionDispatch::SSL, config.ssl_options
-
end
-
-
1
middleware.use ::Rack::Sendfile, config.action_dispatch.x_sendfile_header
-
-
1
if config.serve_static_assets
-
1
middleware.use ::ActionDispatch::Static, paths["public"].first, config.static_cache_control
-
end
-
-
1
if rack_cache = load_rack_cache
-
require "action_dispatch/http/rack_cache"
-
middleware.use ::Rack::Cache, rack_cache
-
end
-
-
1
middleware.use ::Rack::Lock unless allow_concurrency?
-
1
middleware.use ::Rack::Runtime
-
1
middleware.use ::Rack::MethodOverride
-
1
middleware.use ::ActionDispatch::RequestId
-
-
# Must come after Rack::MethodOverride to properly log overridden methods
-
1
middleware.use ::Rails::Rack::Logger, config.log_tags
-
1
middleware.use ::ActionDispatch::ShowExceptions, show_exceptions_app
-
1
middleware.use ::ActionDispatch::DebugExceptions, app
-
1
middleware.use ::ActionDispatch::RemoteIp, config.action_dispatch.ip_spoofing_check, config.action_dispatch.trusted_proxies
-
-
1
unless config.cache_classes
-
middleware.use ::ActionDispatch::Reloader, lambda { reload_dependencies? }
-
end
-
-
1
middleware.use ::ActionDispatch::Callbacks
-
1
middleware.use ::ActionDispatch::Cookies
-
-
1
if config.session_store
-
1
if config.force_ssl && !config.session_options.key?(:secure)
-
config.session_options[:secure] = true
-
end
-
1
middleware.use config.session_store, config.session_options
-
1
middleware.use ::ActionDispatch::Flash
-
end
-
-
1
middleware.use ::ActionDispatch::ParamsParser
-
1
middleware.use ::Rack::Head
-
1
middleware.use ::Rack::ConditionalGet
-
1
middleware.use ::Rack::ETag, "no-cache"
-
end
-
end
-
-
1
private
-
-
1
def reload_dependencies?
-
config.reload_classes_only_on_change != true || app.reloaders.map(&:updated?).any?
-
end
-
-
1
def allow_concurrency?
-
1
config.allow_concurrency.nil? ? config.cache_classes : config.allow_concurrency
-
end
-
-
1
def load_rack_cache
-
1
rack_cache = config.action_dispatch.rack_cache
-
1
return unless rack_cache
-
-
begin
-
require 'rack/cache'
-
rescue LoadError => error
-
error.message << ' Be sure to add rack-cache to your Gemfile'
-
raise
-
end
-
-
if rack_cache == true
-
{
-
metastore: "rails:/",
-
entitystore: "rails:/",
-
verbose: false
-
}
-
else
-
rack_cache
-
end
-
end
-
-
1
def show_exceptions_app
-
1
config.exceptions_app || ActionDispatch::PublicExceptions.new(Rails.public_path)
-
end
-
end
-
end
-
end
-
1
module Rails
-
1
class Application
-
1
module Finisher
-
1
include Initializable
-
-
1
initializer :add_generator_templates do
-
1
config.generators.templates.unshift(*paths["lib/templates"].existent)
-
end
-
-
1
initializer :ensure_autoload_once_paths_as_subset do
-
1
extra = ActiveSupport::Dependencies.autoload_once_paths -
-
ActiveSupport::Dependencies.autoload_paths
-
-
1
unless extra.empty?
-
abort <<-end_error
-
autoload_once_paths must be a subset of the autoload_paths.
-
Extra items in autoload_once_paths: #{extra * ','}
-
end_error
-
end
-
end
-
-
1
initializer :add_builtin_route do |app|
-
1
if Rails.env.development?
-
app.routes.append do
-
get '/rails/mailers' => "rails/mailers#index"
-
get '/rails/mailers/*path' => "rails/mailers#preview"
-
get '/rails/info/properties' => "rails/info#properties"
-
get '/rails/info/routes' => "rails/info#routes"
-
get '/rails/info' => "rails/info#index"
-
get '/' => "rails/welcome#index"
-
end
-
end
-
end
-
-
1
initializer :build_middleware_stack do
-
1
build_middleware_stack
-
end
-
-
1
initializer :define_main_app_helper do |app|
-
1
app.routes.define_mounted_helper(:main_app)
-
end
-
-
1
initializer :add_to_prepare_blocks do
-
1
config.to_prepare_blocks.each do |block|
-
ActionDispatch::Reloader.to_prepare(&block)
-
end
-
end
-
-
# This needs to happen before eager load so it happens
-
# in exactly the same point regardless of config.cache_classes
-
1
initializer :run_prepare_callbacks do
-
1
ActionDispatch::Reloader.prepare!
-
end
-
-
1
initializer :eager_load! do
-
1
if config.eager_load
-
ActiveSupport.run_load_hooks(:before_eager_load, self)
-
config.eager_load_namespaces.each(&:eager_load!)
-
end
-
end
-
-
# All initialization is done, including eager loading in production
-
1
initializer :finisher_hook do
-
1
ActiveSupport.run_load_hooks(:after_initialize, self)
-
end
-
-
# Set routes reload after the finisher hook to ensure routes added in
-
# the hook are taken into account.
-
1
initializer :set_routes_reloader_hook do
-
1
reloader = routes_reloader
-
1
reloader.execute_if_updated
-
1
self.reloaders << reloader
-
1
ActionDispatch::Reloader.to_prepare do
-
# We configure #execute rather than #execute_if_updated because if
-
# autoloaded constants are cleared we need to reload routes also in
-
# case any was used there, as in
-
#
-
# mount MailPreview => 'mail_view'
-
#
-
# This means routes are also reloaded if i18n is updated, which
-
# might not be necessary, but in order to be more precise we need
-
# some sort of reloaders dependency support, to be added.
-
reloader.execute
-
end
-
end
-
-
# Set clearing dependencies after the finisher hook to ensure paths
-
# added in the hook are taken into account.
-
1
initializer :set_clear_dependencies_hook, group: :all do
-
1
callback = lambda do
-
ActiveSupport::DescendantsTracker.clear
-
ActiveSupport::Dependencies.clear
-
end
-
-
1
if config.reload_classes_only_on_change
-
1
reloader = config.file_watcher.new(*watchable_args, &callback)
-
1
self.reloaders << reloader
-
-
# Prepend this callback to have autoloaded constants cleared before
-
# any other possible reloading, in case they need to autoload fresh
-
# constants.
-
1
ActionDispatch::Reloader.to_prepare(prepend: true) do
-
# In addition to changes detected by the file watcher, if routes
-
# or i18n have been updated we also need to clear constants,
-
# that's why we run #execute rather than #execute_if_updated, this
-
# callback has to clear autoloaded constants after any update.
-
reloader.execute
-
end
-
else
-
ActionDispatch::Reloader.to_cleanup(&callback)
-
end
-
end
-
end
-
end
-
end
-
1
require "active_support/core_ext/module/delegation"
-
-
1
module Rails
-
1
class Application
-
1
class RoutesReloader
-
1
attr_reader :route_sets, :paths
-
1
delegate :execute_if_updated, :execute, :updated?, to: :updater
-
-
1
def initialize
-
1
@paths = []
-
1
@route_sets = []
-
end
-
-
1
def reload!
-
1
clear!
-
1
load_paths
-
1
finalize!
-
ensure
-
1
revert
-
end
-
-
1
private
-
-
1
def updater
-
@updater ||= begin
-
2
updater = ActiveSupport::FileUpdateChecker.new(paths) { reload! }
-
1
updater.execute
-
1
updater
-
1
end
-
end
-
-
1
def clear!
-
1
route_sets.each do |routes|
-
2
routes.disable_clear_and_finalize = true
-
2
routes.clear!
-
end
-
end
-
-
1
def load_paths
-
2
paths.each { |path| load(path) }
-
end
-
-
1
def finalize!
-
1
route_sets.each do |routes|
-
2
routes.finalize!
-
end
-
end
-
-
1
def revert
-
1
route_sets.each do |routes|
-
2
routes.disable_clear_and_finalize = false
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/ordered_options'
-
1
require 'active_support/core_ext/object'
-
1
require 'rails/paths'
-
1
require 'rails/rack'
-
-
1
module Rails
-
1
module Configuration
-
# MiddlewareStackProxy is a proxy for the Rails middleware stack that allows
-
# you to configure middlewares in your application. It works basically as a
-
# command recorder, saving each command to be applied after initialization
-
# over the default middleware stack, so you can add, swap, or remove any
-
# middleware in Rails.
-
#
-
# You can add your own middlewares by using the +config.middleware.use+ method:
-
#
-
# config.middleware.use Magical::Unicorns
-
#
-
# This will put the <tt>Magical::Unicorns</tt> middleware on the end of the stack.
-
# You can use +insert_before+ if you wish to add a middleware before another:
-
#
-
# config.middleware.insert_before ActionDispatch::Head, Magical::Unicorns
-
#
-
# There's also +insert_after+ which will insert a middleware after another:
-
#
-
# config.middleware.insert_after ActionDispatch::Head, Magical::Unicorns
-
#
-
# Middlewares can also be completely swapped out and replaced with others:
-
#
-
# config.middleware.swap ActionDispatch::Flash, Magical::Unicorns
-
#
-
# And finally they can also be removed from the stack completely:
-
#
-
# config.middleware.delete ActionDispatch::Flash
-
#
-
1
class MiddlewareStackProxy
-
1
def initialize
-
1
@operations = []
-
end
-
-
1
def insert_before(*args, &block)
-
1
@operations << [__method__, args, block]
-
end
-
-
1
alias :insert :insert_before
-
-
1
def insert_after(*args, &block)
-
2
@operations << [__method__, args, block]
-
end
-
-
1
def swap(*args, &block)
-
@operations << [__method__, args, block]
-
end
-
-
1
def use(*args, &block)
-
1
@operations << [__method__, args, block]
-
end
-
-
1
def delete(*args, &block)
-
@operations << [__method__, args, block]
-
end
-
-
1
def unshift(*args, &block)
-
@operations << [__method__, args, block]
-
end
-
-
1
def merge_into(other) #:nodoc:
-
1
@operations.each do |operation, args, block|
-
4
other.send(operation, *args, &block)
-
end
-
1
other
-
end
-
end
-
-
1
class Generators #:nodoc:
-
1
attr_accessor :aliases, :options, :templates, :fallbacks, :colorize_logging
-
1
attr_reader :hidden_namespaces
-
-
1
def initialize
-
1
@aliases = Hash.new { |h,k| h[k] = {} }
-
5
@options = Hash.new { |h,k| h[k] = {} }
-
1
@fallbacks = {}
-
1
@templates = []
-
1
@colorize_logging = true
-
1
@hidden_namespaces = []
-
end
-
-
1
def initialize_copy(source)
-
14
@aliases = @aliases.deep_dup
-
14
@options = @options.deep_dup
-
14
@fallbacks = @fallbacks.deep_dup
-
14
@templates = @templates.dup
-
end
-
-
1
def hide_namespace(namespace)
-
1
@hidden_namespaces << namespace
-
end
-
-
1
def method_missing(method, *args)
-
10
method = method.to_s.sub(/=$/, '').to_sym
-
-
10
return @options[method] if args.empty?
-
-
10
if method == :rails || args.first.is_a?(Hash)
-
namespace, configuration = method, args.shift
-
else
-
10
namespace, configuration = args.shift, args.shift
-
10
namespace = namespace.to_sym if namespace.respond_to?(:to_sym)
-
10
@options[:rails][method] = namespace
-
end
-
-
10
if configuration
-
3
aliases = configuration.delete(:aliases)
-
3
@aliases[namespace].merge!(aliases) if aliases
-
3
@options[namespace].merge!(configuration)
-
end
-
end
-
end
-
end
-
end
-
1
require 'rails/railtie'
-
1
require 'rails/engine/railties'
-
1
require 'active_support/core_ext/module/delegation'
-
1
require 'pathname'
-
-
1
module Rails
-
# <tt>Rails::Engine</tt> allows you to wrap a specific Rails application or subset of
-
# functionality and share it with other applications or within a larger packaged application.
-
# Since Rails 3.0, every <tt>Rails::Application</tt> is just an engine, which allows for simple
-
# feature and application sharing.
-
#
-
# Any <tt>Rails::Engine</tt> is also a <tt>Rails::Railtie</tt>, so the same
-
# methods (like <tt>rake_tasks</tt> and +generators+) and configuration
-
# options that are available in railties can also be used in engines.
-
#
-
# == Creating an Engine
-
#
-
# In Rails versions prior to 3.0, your gems automatically behaved as engines, however,
-
# this coupled Rails to Rubygems. Since Rails 3.0, if you want a gem to automatically
-
# behave as an engine, you have to specify an +Engine+ for it somewhere inside
-
# your plugin's +lib+ folder (similar to how we specify a +Railtie+):
-
#
-
# # lib/my_engine.rb
-
# module MyEngine
-
# class Engine < Rails::Engine
-
# end
-
# end
-
#
-
# Then ensure that this file is loaded at the top of your <tt>config/application.rb</tt>
-
# (or in your +Gemfile+) and it will automatically load models, controllers and helpers
-
# inside +app+, load routes at <tt>config/routes.rb</tt>, load locales at
-
# <tt>config/locales/*</tt>, and load tasks at <tt>lib/tasks/*</tt>.
-
#
-
# == Configuration
-
#
-
# Besides the +Railtie+ configuration which is shared across the application, in a
-
# <tt>Rails::Engine</tt> you can access <tt>autoload_paths</tt>, <tt>eager_load_paths</tt>
-
# and <tt>autoload_once_paths</tt>, which, differently from a <tt>Railtie</tt>, are scoped to
-
# the current engine.
-
#
-
# class MyEngine < Rails::Engine
-
# # Add a load path for this specific Engine
-
# config.autoload_paths << File.expand_path("../lib/some/path", __FILE__)
-
#
-
# initializer "my_engine.add_middleware" do |app|
-
# app.middleware.use MyEngine::Middleware
-
# end
-
# end
-
#
-
# == Generators
-
#
-
# You can set up generators for engines with <tt>config.generators</tt> method:
-
#
-
# class MyEngine < Rails::Engine
-
# config.generators do |g|
-
# g.orm :active_record
-
# g.template_engine :erb
-
# g.test_framework :test_unit
-
# end
-
# end
-
#
-
# You can also set generators for an application by using <tt>config.app_generators</tt>:
-
#
-
# class MyEngine < Rails::Engine
-
# # note that you can also pass block to app_generators in the same way you
-
# # can pass it to generators method
-
# config.app_generators.orm :datamapper
-
# end
-
#
-
# == Paths
-
#
-
# Since Rails 3.0, applications and engines have more flexible path configuration (as
-
# opposed to the previous hardcoded path configuration). This means that you are not
-
# required to place your controllers at <tt>app/controllers</tt>, but in any place
-
# which you find convenient.
-
#
-
# For example, let's suppose you want to place your controllers in <tt>lib/controllers</tt>.
-
# You can set that as an option:
-
#
-
# class MyEngine < Rails::Engine
-
# paths["app/controllers"] = "lib/controllers"
-
# end
-
#
-
# You can also have your controllers loaded from both <tt>app/controllers</tt> and
-
# <tt>lib/controllers</tt>:
-
#
-
# class MyEngine < Rails::Engine
-
# paths["app/controllers"] << "lib/controllers"
-
# end
-
#
-
# The available paths in an engine are:
-
#
-
# class MyEngine < Rails::Engine
-
# paths["app"] # => ["app"]
-
# paths["app/controllers"] # => ["app/controllers"]
-
# paths["app/helpers"] # => ["app/helpers"]
-
# paths["app/models"] # => ["app/models"]
-
# paths["app/views"] # => ["app/views"]
-
# paths["lib"] # => ["lib"]
-
# paths["lib/tasks"] # => ["lib/tasks"]
-
# paths["config"] # => ["config"]
-
# paths["config/initializers"] # => ["config/initializers"]
-
# paths["config/locales"] # => ["config/locales"]
-
# paths["config/routes.rb"] # => ["config/routes.rb"]
-
# end
-
#
-
# The <tt>Application</tt> class adds a couple more paths to this set. And as in your
-
# <tt>Application</tt>, all folders under +app+ are automatically added to the load path.
-
# If you have an <tt>app/services</tt> folder for example, it will be added by default.
-
#
-
# == Endpoint
-
#
-
# An engine can be also a rack application. It can be useful if you have a rack application that
-
# you would like to wrap with +Engine+ and provide some of the +Engine+'s features.
-
#
-
# To do that, use the +endpoint+ method:
-
#
-
# module MyEngine
-
# class Engine < Rails::Engine
-
# endpoint MyRackApplication
-
# end
-
# end
-
#
-
# Now you can mount your engine in application's routes just like that:
-
#
-
# Rails.application.routes.draw do
-
# mount MyEngine::Engine => "/engine"
-
# end
-
#
-
# == Middleware stack
-
#
-
# As an engine can now be a rack endpoint, it can also have a middleware
-
# stack. The usage is exactly the same as in <tt>Application</tt>:
-
#
-
# module MyEngine
-
# class Engine < Rails::Engine
-
# middleware.use SomeMiddleware
-
# end
-
# end
-
#
-
# == Routes
-
#
-
# If you don't specify an endpoint, routes will be used as the default
-
# endpoint. You can use them just like you use an application's routes:
-
#
-
# # ENGINE/config/routes.rb
-
# MyEngine::Engine.routes.draw do
-
# get "/" => "posts#index"
-
# end
-
#
-
# == Mount priority
-
#
-
# Note that now there can be more than one router in your application, and it's better to avoid
-
# passing requests through many routers. Consider this situation:
-
#
-
# Rails.application.routes.draw do
-
# mount MyEngine::Engine => "/blog"
-
# get "/blog/omg" => "main#omg"
-
# end
-
#
-
# +MyEngine+ is mounted at <tt>/blog</tt>, and <tt>/blog/omg</tt> points to application's
-
# controller. In such a situation, requests to <tt>/blog/omg</tt> will go through +MyEngine+,
-
# and if there is no such route in +Engine+'s routes, it will be dispatched to <tt>main#omg</tt>.
-
# It's much better to swap that:
-
#
-
# Rails.application.routes.draw do
-
# get "/blog/omg" => "main#omg"
-
# mount MyEngine::Engine => "/blog"
-
# end
-
#
-
# Now, +Engine+ will get only requests that were not handled by +Application+.
-
#
-
# == Engine name
-
#
-
# There are some places where an Engine's name is used:
-
#
-
# * routes: when you mount an Engine with <tt>mount(MyEngine::Engine => '/my_engine')</tt>,
-
# it's used as default <tt>:as</tt> option
-
# * rake task for installing migrations <tt>my_engine:install:migrations</tt>
-
#
-
# Engine name is set by default based on class name. For <tt>MyEngine::Engine</tt> it will be
-
# <tt>my_engine_engine</tt>. You can change it manually using the <tt>engine_name</tt> method:
-
#
-
# module MyEngine
-
# class Engine < Rails::Engine
-
# engine_name "my_engine"
-
# end
-
# end
-
#
-
# == Isolated Engine
-
#
-
# Normally when you create controllers, helpers and models inside an engine, they are treated
-
# as if they were created inside the application itself. This means that all helpers and
-
# named routes from the application will be available to your engine's controllers as well.
-
#
-
# However, sometimes you want to isolate your engine from the application, especially if your engine
-
# has its own router. To do that, you simply need to call +isolate_namespace+. This method requires
-
# you to pass a module where all your controllers, helpers and models should be nested to:
-
#
-
# module MyEngine
-
# class Engine < Rails::Engine
-
# isolate_namespace MyEngine
-
# end
-
# end
-
#
-
# With such an engine, everything that is inside the +MyEngine+ module will be isolated from
-
# the application.
-
#
-
# Consider such controller:
-
#
-
# module MyEngine
-
# class FooController < ActionController::Base
-
# end
-
# end
-
#
-
# If an engine is marked as isolated, +FooController+ has access only to helpers from +Engine+ and
-
# <tt>url_helpers</tt> from <tt>MyEngine::Engine.routes</tt>.
-
#
-
# The next thing that changes in isolated engines is the behavior of routes. Normally, when you namespace
-
# your controllers, you also need to do namespace all your routes. With an isolated engine,
-
# the namespace is applied by default, so you can ignore it in routes:
-
#
-
# MyEngine::Engine.routes.draw do
-
# resources :articles
-
# end
-
#
-
# The routes above will automatically point to <tt>MyEngine::ArticlesController</tt>. Furthermore, you don't
-
# need to use longer url helpers like <tt>my_engine_articles_path</tt>. Instead, you should simply use
-
# <tt>articles_path</tt> as you would do with your application.
-
#
-
# To make that behavior consistent with other parts of the framework, an isolated engine also has influence on
-
# <tt>ActiveModel::Naming</tt>. When you use a namespaced model, like <tt>MyEngine::Article</tt>, it will normally
-
# use the prefix "my_engine". In an isolated engine, the prefix will be omitted in url helpers and
-
# form fields for convenience.
-
#
-
# polymorphic_url(MyEngine::Article.new) # => "articles_path"
-
#
-
# form_for(MyEngine::Article.new) do
-
# text_field :title # => <input type="text" name="article[title]" id="article_title" />
-
# end
-
#
-
# Additionally, an isolated engine will set its name according to namespace, so
-
# MyEngine::Engine.engine_name will be "my_engine". It will also set MyEngine.table_name_prefix
-
# to "my_engine_", changing the MyEngine::Article model to use the my_engine_articles table.
-
#
-
# == Using Engine's routes outside Engine
-
#
-
# Since you can now mount an engine inside application's routes, you do not have direct access to +Engine+'s
-
# <tt>url_helpers</tt> inside +Application+. When you mount an engine in an application's routes, a special helper is
-
# created to allow you to do that. Consider such a scenario:
-
#
-
# # config/routes.rb
-
# Rails.application.routes.draw do
-
# mount MyEngine::Engine => "/my_engine", as: "my_engine"
-
# get "/foo" => "foo#index"
-
# end
-
#
-
# Now, you can use the <tt>my_engine</tt> helper inside your application:
-
#
-
# class FooController < ApplicationController
-
# def index
-
# my_engine.root_url # => /my_engine/
-
# end
-
# end
-
#
-
# There is also a <tt>main_app</tt> helper that gives you access to application's routes inside Engine:
-
#
-
# module MyEngine
-
# class BarController
-
# def index
-
# main_app.foo_path # => /foo
-
# end
-
# end
-
# end
-
#
-
# Note that the <tt>:as</tt> option given to mount takes the <tt>engine_name</tt> as default, so most of the time
-
# you can simply omit it.
-
#
-
# Finally, if you want to generate a url to an engine's route using
-
# <tt>polymorphic_url</tt>, you also need to pass the engine helper. Let's
-
# say that you want to create a form pointing to one of the engine's routes.
-
# All you need to do is pass the helper as the first element in array with
-
# attributes for url:
-
#
-
# form_for([my_engine, @user])
-
#
-
# This code will use <tt>my_engine.user_path(@user)</tt> to generate the proper route.
-
#
-
# == Isolated engine's helpers
-
#
-
# Sometimes you may want to isolate engine, but use helpers that are defined for it.
-
# If you want to share just a few specific helpers you can add them to application's
-
# helpers in ApplicationController:
-
#
-
# class ApplicationController < ActionController::Base
-
# helper MyEngine::SharedEngineHelper
-
# end
-
#
-
# If you want to include all of the engine's helpers, you can use #helper method on an engine's
-
# instance:
-
#
-
# class ApplicationController < ActionController::Base
-
# helper MyEngine::Engine.helpers
-
# end
-
#
-
# It will include all of the helpers from engine's directory. Take into account that this does
-
# not include helpers defined in controllers with helper_method or other similar solutions,
-
# only helpers defined in the helpers directory will be included.
-
#
-
# == Migrations & seed data
-
#
-
# Engines can have their own migrations. The default path for migrations is exactly the same
-
# as in application: <tt>db/migrate</tt>
-
#
-
# To use engine's migrations in application you can use rake task, which copies them to
-
# application's dir:
-
#
-
# rake ENGINE_NAME:install:migrations
-
#
-
# Note that some of the migrations may be skipped if a migration with the same name already exists
-
# in application. In such a situation you must decide whether to leave that migration or rename the
-
# migration in the application and rerun copying migrations.
-
#
-
# If your engine has migrations, you may also want to prepare data for the database in
-
# the <tt>db/seeds.rb</tt> file. You can load that data using the <tt>load_seed</tt> method, e.g.
-
#
-
# MyEngine::Engine.load_seed
-
#
-
# == Loading priority
-
#
-
# In order to change engine's priority you can use +config.railties_order+ in main application.
-
# It will affect the priority of loading views, helpers, assets and all the other files
-
# related to engine or application.
-
#
-
# # load Blog::Engine with highest priority, followed by application and other railties
-
# config.railties_order = [Blog::Engine, :main_app, :all]
-
1
class Engine < Railtie
-
1
autoload :Configuration, "rails/engine/configuration"
-
-
1
class << self
-
1
attr_accessor :called_from, :isolated
-
-
1
alias :isolated? :isolated
-
1
alias :engine_name :railtie_name
-
-
1
delegate :eager_load!, to: :instance
-
-
1
def inherited(base)
-
15
unless base.abstract_railtie?
-
14
Rails::Railtie::Configuration.eager_load_namespaces << base
-
-
14
base.called_from = begin
-
14
call_stack = if Kernel.respond_to?(:caller_locations)
-
14
caller_locations.map(&:path)
-
else
-
# Remove the line number from backtraces making sure we don't leave anything behind
-
caller.map { |p| p.sub(/:\d+.*/, '') }
-
end
-
-
29
File.dirname(call_stack.detect { |p| p !~ %r[railties[\w.-]*/lib/rails|rack[\w.-]*/lib/rack] })
-
end
-
end
-
-
15
super
-
end
-
-
1
def endpoint(endpoint = nil)
-
1
@endpoint ||= nil
-
1
@endpoint = endpoint if endpoint
-
1
@endpoint
-
end
-
-
1
def isolate_namespace(mod)
-
1
engine_name(generate_railtie_name(mod))
-
-
1
self.routes.default_scope = { module: ActiveSupport::Inflector.underscore(mod.name) }
-
1
self.isolated = true
-
-
1
unless mod.respond_to?(:railtie_namespace)
-
1
name, railtie = engine_name, self
-
-
1
mod.singleton_class.instance_eval do
-
1
define_method(:railtie_namespace) { railtie }
-
-
1
unless mod.respond_to?(:table_name_prefix)
-
1
define_method(:table_name_prefix) { "#{name}_" }
-
end
-
-
1
unless mod.respond_to?(:use_relative_model_naming?)
-
1
class_eval "def use_relative_model_naming?; true; end", __FILE__, __LINE__
-
end
-
-
1
unless mod.respond_to?(:railtie_helpers_paths)
-
1
define_method(:railtie_helpers_paths) { railtie.helpers_paths }
-
end
-
-
1
unless mod.respond_to?(:railtie_routes_url_helpers)
-
1
define_method(:railtie_routes_url_helpers) { railtie.routes.url_helpers }
-
end
-
end
-
end
-
end
-
-
# Finds engine with given path
-
1
def find(path)
-
expanded_path = File.expand_path path
-
Rails::Engine.subclasses.each do |klass|
-
engine = klass.instance
-
return engine if File.expand_path(engine.root) == expanded_path
-
end
-
nil
-
end
-
end
-
-
1
delegate :middleware, :root, :paths, to: :config
-
1
delegate :engine_name, :isolated?, to: :class
-
-
1
def initialize
-
14
@_all_autoload_paths = nil
-
14
@_all_load_paths = nil
-
14
@app = nil
-
14
@config = nil
-
14
@env_config = nil
-
14
@helpers = nil
-
14
@routes = nil
-
14
super
-
end
-
-
# Load console and invoke the registered hooks.
-
# Check <tt>Rails::Railtie.console</tt> for more info.
-
1
def load_console(app=self)
-
require "rails/console/app"
-
require "rails/console/helpers"
-
run_console_blocks(app)
-
self
-
end
-
-
# Load Rails runner and invoke the registered hooks.
-
# Check <tt>Rails::Railtie.runner</tt> for more info.
-
1
def load_runner(app=self)
-
run_runner_blocks(app)
-
self
-
end
-
-
# Load Rake, railties tasks and invoke the registered hooks.
-
# Check <tt>Rails::Railtie.rake_tasks</tt> for more info.
-
1
def load_tasks(app=self)
-
require "rake"
-
run_tasks_blocks(app)
-
self
-
end
-
-
# Load Rails generators and invoke the registered hooks.
-
# Check <tt>Rails::Railtie.generators</tt> for more info.
-
1
def load_generators(app=self)
-
require "rails/generators"
-
run_generators_blocks(app)
-
Rails::Generators.configure!(app.config.generators)
-
self
-
end
-
-
# Eager load the application by loading all ruby
-
# files inside eager_load paths.
-
1
def eager_load!
-
config.eager_load_paths.each do |load_path|
-
matcher = /\A#{Regexp.escape(load_path.to_s)}\/(.*)\.rb\Z/
-
Dir.glob("#{load_path}/**/*.rb").sort.each do |file|
-
require_dependency file.sub(matcher, '\1')
-
end
-
end
-
end
-
-
1
def railties
-
1
@railties ||= Railties.new
-
end
-
-
# Returns a module with all the helpers defined for the engine.
-
1
def helpers
-
@helpers ||= begin
-
helpers = Module.new
-
all = ActionController::Base.all_helpers_from_path(helpers_paths)
-
ActionController::Base.modules_for_helpers(all).each do |mod|
-
helpers.send(:include, mod)
-
end
-
helpers
-
end
-
end
-
-
# Returns all registered helpers paths.
-
1
def helpers_paths
-
paths["app/helpers"].existent
-
end
-
-
# Returns the underlying rack application for this engine.
-
1
def app
-
@app ||= begin
-
1
config.middleware = config.middleware.merge_into(default_middleware_stack)
-
1
config.middleware.build(endpoint)
-
1
end
-
end
-
-
# Returns the endpoint for this engine. If none is registered,
-
# defaults to an ActionDispatch::Routing::RouteSet.
-
1
def endpoint
-
1
self.class.endpoint || routes
-
end
-
-
# Define the Rack API for this engine.
-
1
def call(env)
-
env.merge!(env_config)
-
if env['SCRIPT_NAME']
-
env.merge! "ROUTES_#{routes.object_id}_SCRIPT_NAME" => env['SCRIPT_NAME'].dup
-
end
-
app.call(env)
-
end
-
-
# Defines additional Rack env configuration that is added on each call.
-
1
def env_config
-
@env_config ||= {
-
'action_dispatch.routes' => routes
-
}
-
end
-
-
# Defines the routes for this engine. If a block is given to
-
# routes, it is appended to the engine.
-
1
def routes
-
14
@routes ||= ActionDispatch::Routing::RouteSet.new
-
14
@routes.append(&Proc.new) if block_given?
-
14
@routes
-
end
-
-
# Define the configuration object for the engine.
-
1
def config
-
237
@config ||= Engine::Configuration.new(find_root_with_flag("lib"))
-
end
-
-
# Load data from db/seeds.rb file. It can be used in to load engines'
-
# seeds, e.g.:
-
#
-
# Blog::Engine.load_seed
-
1
def load_seed
-
seed_file = paths["db/seeds.rb"].existent.first
-
load(seed_file) if seed_file
-
end
-
-
# Add configured load paths to ruby load paths and remove duplicates.
-
1
initializer :set_load_path, before: :bootstrap_hook do
-
14
_all_load_paths.reverse_each do |path|
-
36
$LOAD_PATH.unshift(path) if File.directory?(path)
-
end
-
14
$LOAD_PATH.uniq!
-
end
-
-
# Set the paths from which Rails will automatically load source files,
-
# and the load_once paths.
-
#
-
# This needs to be an initializer, since it needs to run once
-
# per engine and get the engine as a block parameter
-
1
initializer :set_autoload_paths, before: :bootstrap_hook do
-
14
ActiveSupport::Dependencies.autoload_paths.unshift(*_all_autoload_paths)
-
14
ActiveSupport::Dependencies.autoload_once_paths.unshift(*_all_autoload_once_paths)
-
-
# Freeze so future modifications will fail rather than do nothing mysteriously
-
14
config.autoload_paths.freeze
-
14
config.eager_load_paths.freeze
-
14
config.autoload_once_paths.freeze
-
end
-
-
1
initializer :add_routing_paths do |app|
-
14
paths = self.paths["config/routes.rb"].existent
-
-
14
if routes? || paths.any?
-
2
app.routes_reloader.paths.unshift(*paths)
-
2
app.routes_reloader.route_sets << routes
-
end
-
end
-
-
# I18n load paths are a special case since the ones added
-
# later have higher priority.
-
1
initializer :add_locales do
-
14
config.i18n.railties_load_path.concat(paths["config/locales"].existent)
-
end
-
-
1
initializer :add_view_paths do
-
14
views = paths["app/views"].existent
-
14
unless views.empty?
-
6
ActiveSupport.on_load(:action_controller){ prepend_view_path(views) if respond_to?(:prepend_view_path) }
-
6
ActiveSupport.on_load(:action_mailer){ prepend_view_path(views) }
-
end
-
end
-
-
1
initializer :load_environment_config, before: :load_environment_hook, group: :all do
-
14
paths["config/environments"].existent.each do |environment|
-
1
require environment
-
end
-
end
-
-
1
initializer :append_assets_path, group: :all do |app|
-
14
app.config.assets.paths.unshift(*paths["vendor/assets"].existent_directories)
-
14
app.config.assets.paths.unshift(*paths["lib/assets"].existent_directories)
-
14
app.config.assets.paths.unshift(*paths["app/assets"].existent_directories)
-
end
-
-
1
initializer :prepend_helpers_path do |app|
-
14
if !isolated? || (app == self)
-
13
app.config.helpers_paths.unshift(*paths["app/helpers"].existent)
-
end
-
end
-
-
1
initializer :load_config_initializers do
-
14
config.paths["config/initializers"].existent.sort.each do |initializer|
-
8
load_config_initializer(initializer)
-
end
-
end
-
-
1
initializer :engines_blank_point do
-
# We need this initializer so all extra initializers added in engines are
-
# consistently executed after all the initializers above across all engines.
-
end
-
-
1
rake_tasks do
-
next if self.is_a?(Rails::Application)
-
next unless has_migrations?
-
-
namespace railtie_name do
-
namespace :install do
-
desc "Copy migrations from #{railtie_name} to application"
-
task :migrations do
-
ENV["FROM"] = railtie_name
-
if Rake::Task.task_defined?("railties:install:migrations")
-
Rake::Task["railties:install:migrations"].invoke
-
else
-
Rake::Task["app:railties:install:migrations"].invoke
-
end
-
end
-
end
-
end
-
end
-
-
1
def routes? #:nodoc:
-
14
@routes
-
end
-
-
1
protected
-
-
1
def load_config_initializer(initializer)
-
8
ActiveSupport::Notifications.instrument('load_config_initializer.railties', initializer: initializer) do
-
8
load(initializer)
-
end
-
end
-
-
1
def run_tasks_blocks(*) #:nodoc:
-
super
-
paths["lib/tasks"].existent.sort.each { |ext| load(ext) }
-
end
-
-
1
def has_migrations? #:nodoc:
-
paths["db/migrate"].existent.any?
-
end
-
-
1
def find_root_with_flag(flag, default=nil) #:nodoc:
-
14
root_path = self.class.called_from
-
-
14
while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}")
-
27
parent = File.dirname(root_path)
-
27
root_path = parent != root_path && parent
-
end
-
-
14
root = File.exist?("#{root_path}/#{flag}") ? root_path : default
-
14
raise "Could not find root path for #{self}" unless root
-
-
14
Pathname.new File.realpath root
-
end
-
-
1
def default_middleware_stack #:nodoc:
-
ActionDispatch::MiddlewareStack.new
-
end
-
-
1
def _all_autoload_once_paths #:nodoc:
-
14
config.autoload_once_paths
-
end
-
-
1
def _all_autoload_paths #:nodoc:
-
28
@_all_autoload_paths ||= (config.autoload_paths + config.eager_load_paths + config.autoload_once_paths).uniq
-
end
-
-
1
def _all_load_paths #:nodoc:
-
14
@_all_load_paths ||= (config.paths.load_paths + _all_autoload_paths).uniq
-
end
-
end
-
end
-
1
require 'rails/railtie/configuration'
-
-
1
module Rails
-
1
class Engine
-
1
class Configuration < ::Rails::Railtie::Configuration
-
1
attr_reader :root
-
1
attr_writer :middleware, :eager_load_paths, :autoload_once_paths, :autoload_paths
-
-
1
def initialize(root=nil)
-
14
super()
-
14
@root = root
-
14
@generators = app_generators.dup
-
end
-
-
# Returns the middleware stack for the engine.
-
1
def middleware
-
3
@middleware ||= Rails::Configuration::MiddlewareStackProxy.new
-
end
-
-
# Holds generators configuration:
-
#
-
# config.generators do |g|
-
# g.orm :data_mapper, migration: true
-
# g.template_engine :haml
-
# g.test_framework :rspec
-
# end
-
#
-
# If you want to disable color in console, do:
-
#
-
# config.generators.colorize_logging = false
-
#
-
1
def generators #:nodoc:
-
2
@generators ||= Rails::Configuration::Generators.new
-
2
yield(@generators) if block_given?
-
2
@generators
-
end
-
-
1
def paths
-
@paths ||= begin
-
14
paths = Rails::Paths::Root.new(@root)
-
-
14
paths.add "app", eager_load: true, glob: "*"
-
14
paths.add "app/assets", glob: "*"
-
14
paths.add "app/controllers", eager_load: true
-
14
paths.add "app/helpers", eager_load: true
-
14
paths.add "app/models", eager_load: true
-
14
paths.add "app/mailers", eager_load: true
-
14
paths.add "app/views"
-
-
14
paths.add "app/controllers/concerns", eager_load: true
-
14
paths.add "app/models/concerns", eager_load: true
-
-
14
paths.add "lib", load_path: true
-
14
paths.add "lib/assets", glob: "*"
-
14
paths.add "lib/tasks", glob: "**/*.rake"
-
-
14
paths.add "config"
-
14
paths.add "config/environments", glob: "#{Rails.env}.rb"
-
14
paths.add "config/initializers", glob: "**/*.rb"
-
14
paths.add "config/locales", glob: "*.{rb,yml}"
-
14
paths.add "config/routes.rb"
-
-
14
paths.add "db"
-
14
paths.add "db/migrate"
-
14
paths.add "db/seeds.rb"
-
-
14
paths.add "vendor", load_path: true
-
14
paths.add "vendor/assets", glob: "*"
-
-
14
paths
-
169
end
-
end
-
-
1
def root=(value)
-
@root = paths.path = Pathname.new(value).expand_path
-
end
-
-
1
def eager_load_paths
-
28
@eager_load_paths ||= paths.eager_load
-
end
-
-
1
def autoload_once_paths
-
42
@autoload_once_paths ||= paths.autoload_once
-
end
-
-
1
def autoload_paths
-
28
@autoload_paths ||= paths.autoload_paths
-
end
-
end
-
end
-
end
-
1
module Rails
-
1
class Engine < Railtie
-
1
class Railties
-
1
include Enumerable
-
1
attr_reader :_all
-
-
1
def initialize
-
@_all ||= ::Rails::Railtie.subclasses.map(&:instance) +
-
1
::Rails::Engine.subclasses.map(&:instance)
-
end
-
-
1
def each(*args, &block)
-
_all.each(*args, &block)
-
end
-
-
1
def -(others)
-
1
_all - others
-
end
-
end
-
end
-
end
-
1
module Rails
-
# Returns the version of the currently loaded Rails as a <tt>Gem::Version</tt>
-
1
def self.gem_version
-
Gem::Version.new VERSION::STRING
-
end
-
-
1
module VERSION
-
1
MAJOR = 4
-
1
MINOR = 1
-
1
TINY = 0
-
1
PRE = nil
-
-
1
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
-
end
-
end
-
1
require 'tsort'
-
-
1
module Rails
-
1
module Initializable
-
1
def self.included(base) #:nodoc:
-
3
base.extend ClassMethods
-
end
-
-
1
class Initializer
-
1
attr_reader :name, :block
-
-
1
def initialize(name, context, options, &block)
-
274
options[:group] ||= :default
-
274
@name, @context, @options, @block = name, context, options, block
-
end
-
-
1
def before
-
40804
@options[:before]
-
end
-
-
1
def after
-
40748
@options[:after]
-
end
-
-
1
def belongs_to?(group)
-
202
@options[:group] == group || @options[:group] == :all
-
end
-
-
1
def run(*args)
-
202
@context.instance_exec(*args, &block)
-
end
-
-
1
def bind(context)
-
202
return self if @context
-
202
Initializer.new(@name, context, @options, &block)
-
end
-
end
-
-
1
class Collection < Array
-
1
include TSort
-
-
1
alias :tsort_each_node :each
-
1
def tsort_each_child(initializer, &block)
-
41006
select { |i| i.before == initializer.name || i.name == initializer.after }.each(&block)
-
end
-
-
1
def +(other)
-
87
Collection.new(to_a + other.to_a)
-
end
-
end
-
-
1
def run_initializers(group=:default, *args)
-
1
return if instance_variable_defined?(:@ran)
-
1
initializers.tsort_each do |initializer|
-
202
initializer.run(*args) if initializer.belongs_to?(group)
-
end
-
1
@ran = true
-
end
-
-
1
def initializers
-
34
@initializers ||= self.class.initializers_for(self)
-
end
-
-
1
module ClassMethods
-
1
def initializers
-
336
@initializers ||= Collection.new
-
end
-
-
1
def initializers_chain
-
36
initializers = Collection.new
-
36
ancestors.reverse_each do |klass|
-
325
next unless klass.respond_to?(:initializers)
-
85
initializers = initializers + klass.initializers
-
end
-
36
initializers
-
end
-
-
1
def initializers_for(binding)
-
238
Collection.new(initializers_chain.map { |i| i.bind(binding) })
-
end
-
-
1
def initializer(name, opts = {}, &blk)
-
72
raise ArgumentError, "A block must be passed when defining an initializer" unless blk
-
270
opts[:after] ||= initializers.last.name unless initializers.empty? || initializers.find { |i| i.name == opts[:before] }
-
72
initializers << Initializer.new(name, nil, opts, &blk)
-
end
-
end
-
end
-
end
-
1
module Rails
-
1
module Paths
-
# This object is an extended hash that behaves as root of the <tt>Rails::Paths</tt> system.
-
# It allows you to collect information about how you want to structure your application
-
# paths by a Hash like API. It requires you to give a physical path on initialization.
-
#
-
# root = Root.new "/rails"
-
# root.add "app/controllers", eager_load: true
-
#
-
# The command above creates a new root object and add "app/controllers" as a path.
-
# This means we can get a <tt>Rails::Paths::Path</tt> object back like below:
-
#
-
# path = root["app/controllers"]
-
# path.eager_load? # => true
-
# path.is_a?(Rails::Paths::Path) # => true
-
#
-
# The +Path+ object is simply an enumerable and allows you to easily add extra paths:
-
#
-
# path.is_a?(Enumerable) # => true
-
# path.to_ary.inspect # => ["app/controllers"]
-
#
-
# path << "lib/controllers"
-
# path.to_ary.inspect # => ["app/controllers", "lib/controllers"]
-
#
-
# Notice that when you add a path using +add+, the path object created already
-
# contains the path with the same path value given to +add+. In some situations,
-
# you may not want this behavior, so you can give <tt>:with</tt> as option.
-
#
-
# root.add "config/routes", with: "config/routes.rb"
-
# root["config/routes"].inspect # => ["config/routes.rb"]
-
#
-
# The +add+ method accepts the following options as arguments:
-
# eager_load, autoload, autoload_once and glob.
-
#
-
# Finally, the +Path+ object also provides a few helpers:
-
#
-
# root = Root.new "/rails"
-
# root.add "app/controllers"
-
#
-
# root["app/controllers"].expanded # => ["/rails/app/controllers"]
-
# root["app/controllers"].existent # => ["/rails/app/controllers"]
-
#
-
# Check the <tt>Rails::Paths::Path</tt> documentation for more information.
-
1
class Root
-
1
attr_accessor :path
-
-
1
def initialize(path)
-
14
@current = nil
-
14
@path = path
-
14
@root = {}
-
end
-
-
1
def []=(path, value)
-
glob = self[path] ? self[path].glob : nil
-
add(path, with: value, glob: glob)
-
end
-
-
1
def add(path, options = {})
-
317
with = Array(options.fetch(:with, path))
-
317
@root[path] = Path.new(self, path, with, options)
-
end
-
-
1
def [](path)
-
140
@root[path]
-
end
-
-
1
def values
-
56
@root.values
-
end
-
-
1
def keys
-
126
@root.keys
-
end
-
-
1
def values_at(*list)
-
126
@root.values_at(*list)
-
end
-
-
1
def all_paths
-
112
values.tap { |v| v.uniq! }
-
end
-
-
1
def autoload_once
-
331
filter_by { |p| p.autoload_once? }
-
end
-
-
1
def eager_load
-
471
filter_by { |p| p.eager_load? }
-
end
-
-
1
def autoload_paths
-
331
filter_by { |p| p.autoload? }
-
end
-
-
1
def load_paths
-
374
filter_by { |p| p.load_path? }
-
end
-
-
1
private
-
-
1
def filter_by(&block)
-
all_paths.find_all(&block).flat_map { |path|
-
126
paths = path.existent
-
309
paths - path.children.map { |p| yield(p) ? [] : p.existent }.flatten
-
56
}.uniq
-
end
-
end
-
-
1
class Path
-
1
include Enumerable
-
-
1
attr_accessor :glob
-
-
1
def initialize(root, current, paths, options = {})
-
317
@paths = paths
-
317
@current = current
-
317
@root = root
-
317
@glob = options[:glob]
-
-
317
options[:autoload_once] ? autoload_once! : skip_autoload_once!
-
317
options[:eager_load] ? eager_load! : skip_eager_load!
-
317
options[:autoload] ? autoload! : skip_autoload!
-
317
options[:load_path] ? load_path! : skip_load_path!
-
end
-
-
1
def children
-
126
keys = @root.keys.find_all { |k|
-
2853
k.start_with?(@current) && k != @current
-
}
-
126
@root.values_at(*keys.sort)
-
end
-
-
1
def first
-
14
expanded.first
-
end
-
-
1
def last
-
expanded.last
-
end
-
-
1
%w(autoload_once eager_load autoload load_path).each do |m|
-
4
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{m}! # def eager_load!
-
@#{m} = true # @eager_load = true
-
end # end
-
#
-
def skip_#{m}! # def skip_eager_load!
-
@#{m} = false # @eager_load = false
-
end # end
-
#
-
def #{m}? # def eager_load?
-
@#{m} # @eager_load
-
end # end
-
RUBY
-
end
-
-
1
def each(&block)
-
337
@paths.each(&block)
-
end
-
-
1
def <<(path)
-
@paths << path
-
end
-
1
alias :push :<<
-
-
1
def concat(paths)
-
@paths.concat paths
-
end
-
-
1
def unshift(path)
-
@paths.unshift path
-
end
-
-
1
def to_ary
-
@paths
-
end
-
-
# Expands all paths against the root and return all unique values.
-
1
def expanded
-
337
raise "You need to set a path root" unless @root.path
-
337
result = []
-
-
337
each do |p|
-
337
path = File.expand_path(p, @root.path)
-
-
337
if @glob && File.directory?(path)
-
40
Dir.chdir(path) do
-
126
result.concat(Dir.glob(@glob).map { |file| File.join path, file }.sort)
-
end
-
else
-
297
result << path
-
end
-
end
-
-
337
result.uniq!
-
337
result
-
end
-
-
# Returns all expanded paths but only if they exist in the filesystem.
-
1
def existent
-
594
expanded.select { |f| File.exist?(f) }
-
end
-
-
1
def existent_directories
-
98
expanded.select { |d| File.directory?(d) }
-
end
-
-
1
alias to_a expanded
-
end
-
end
-
end
-
1
module Rails
-
1
module Rack
-
1
autoload :Debugger, "rails/rack/debugger"
-
1
autoload :Logger, "rails/rack/logger"
-
1
autoload :LogTailer, "rails/rack/log_tailer"
-
end
-
end
-
1
require 'active_support/core_ext/time/conversions'
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'active_support/log_subscriber'
-
1
require 'action_dispatch/http/request'
-
1
require 'rack/body_proxy'
-
-
1
module Rails
-
1
module Rack
-
# Sets log tags, logs the request, calls the app, and flushes the logs.
-
1
class Logger < ActiveSupport::LogSubscriber
-
1
def initialize(app, taggers = nil)
-
1
@app = app
-
1
@taggers = taggers || []
-
end
-
-
1
def call(env)
-
request = ActionDispatch::Request.new(env)
-
-
if logger.respond_to?(:tagged)
-
logger.tagged(compute_tags(request)) { call_app(request, env) }
-
else
-
call_app(request, env)
-
end
-
end
-
-
1
protected
-
-
1
def call_app(request, env)
-
# Put some space between requests in development logs.
-
if development?
-
logger.debug ''
-
logger.debug ''
-
end
-
-
instrumenter = ActiveSupport::Notifications.instrumenter
-
instrumenter.start 'request.action_dispatch', request: request
-
logger.info started_request_message(request)
-
resp = @app.call(env)
-
resp[2] = ::Rack::BodyProxy.new(resp[2]) { finish(request) }
-
resp
-
rescue Exception
-
finish(request)
-
raise
-
ensure
-
ActiveSupport::LogSubscriber.flush_all!
-
end
-
-
# Started GET "/session/new" for 127.0.0.1 at 2012-09-26 14:51:42 -0700
-
1
def started_request_message(request)
-
'Started %s "%s" for %s at %s' % [
-
request.request_method,
-
request.filtered_path,
-
request.ip,
-
Time.now.to_default_s ]
-
end
-
-
1
def compute_tags(request)
-
@taggers.collect do |tag|
-
case tag
-
when Proc
-
tag.call(request)
-
when Symbol
-
request.send(tag)
-
else
-
tag
-
end
-
end
-
end
-
-
1
private
-
-
1
def finish(request)
-
instrumenter = ActiveSupport::Notifications.instrumenter
-
instrumenter.finish 'request.action_dispatch', request: request
-
end
-
-
1
def development?
-
Rails.env.development?
-
end
-
-
1
def logger
-
Rails.logger
-
end
-
end
-
end
-
end
-
1
require 'rails/initializable'
-
1
require 'rails/configuration'
-
1
require 'active_support/inflector'
-
1
require 'active_support/core_ext/module/introspection'
-
1
require 'active_support/core_ext/module/delegation'
-
-
1
module Rails
-
# Railtie is the core of the Rails framework and provides several hooks to extend
-
# Rails and/or modify the initialization process.
-
#
-
# Every major component of Rails (Action Mailer, Action Controller,
-
# Action View and Active Record) is a Railtie. Each of
-
# them is responsible for their own initialization. This makes Rails itself
-
# absent of any component hooks, allowing other components to be used in
-
# place of any of the Rails defaults.
-
#
-
# Developing a Rails extension does _not_ require any implementation of
-
# Railtie, but if you need to interact with the Rails framework during
-
# or after boot, then Railtie is needed.
-
#
-
# For example, an extension doing any of the following would require Railtie:
-
#
-
# * creating initializers
-
# * configuring a Rails framework for the application, like setting a generator
-
# * adding <tt>config.*</tt> keys to the environment
-
# * setting up a subscriber with ActiveSupport::Notifications
-
# * adding rake tasks
-
#
-
# == Creating your Railtie
-
#
-
# To extend Rails using Railtie, create a Railtie class which inherits
-
# from Rails::Railtie within your extension's namespace. This class must be
-
# loaded during the Rails boot process.
-
#
-
# The following example demonstrates an extension which can be used with or without Rails.
-
#
-
# # lib/my_gem/railtie.rb
-
# module MyGem
-
# class Railtie < Rails::Railtie
-
# end
-
# end
-
#
-
# # lib/my_gem.rb
-
# require 'my_gem/railtie' if defined?(Rails)
-
#
-
# == Initializers
-
#
-
# To add an initialization step from your Railtie to Rails boot process, you just need
-
# to create an initializer block:
-
#
-
# class MyRailtie < Rails::Railtie
-
# initializer "my_railtie.configure_rails_initialization" do
-
# # some initialization behavior
-
# end
-
# end
-
#
-
# If specified, the block can also receive the application object, in case you
-
# need to access some application specific configuration, like middleware:
-
#
-
# class MyRailtie < Rails::Railtie
-
# initializer "my_railtie.configure_rails_initialization" do |app|
-
# app.middleware.use MyRailtie::Middleware
-
# end
-
# end
-
#
-
# Finally, you can also pass <tt>:before</tt> and <tt>:after</tt> as option to initializer,
-
# in case you want to couple it with a specific step in the initialization process.
-
#
-
# == Configuration
-
#
-
# Inside the Railtie class, you can access a config object which contains configuration
-
# shared by all railties and the application:
-
#
-
# class MyRailtie < Rails::Railtie
-
# # Customize the ORM
-
# config.app_generators.orm :my_railtie_orm
-
#
-
# # Add a to_prepare block which is executed once in production
-
# # and before each request in development
-
# config.to_prepare do
-
# MyRailtie.setup!
-
# end
-
# end
-
#
-
# == Loading rake tasks and generators
-
#
-
# If your railtie has rake tasks, you can tell Rails to load them through the method
-
# rake_tasks:
-
#
-
# class MyRailtie < Rails::Railtie
-
# rake_tasks do
-
# load "path/to/my_railtie.tasks"
-
# end
-
# end
-
#
-
# By default, Rails load generators from your load path. However, if you want to place
-
# your generators at a different location, you can specify in your Railtie a block which
-
# will load them during normal generators lookup:
-
#
-
# class MyRailtie < Rails::Railtie
-
# generators do
-
# require "path/to/my_railtie_generator"
-
# end
-
# end
-
#
-
# == Application and Engine
-
#
-
# A Rails::Engine is nothing more than a Railtie with some initializers already set.
-
# And since Rails::Application is an engine, the same configuration described here
-
# can be used in both.
-
#
-
# Be sure to look at the documentation of those specific classes for more information.
-
#
-
1
class Railtie
-
1
autoload :Configuration, "rails/railtie/configuration"
-
-
1
include Initializable
-
-
1
ABSTRACT_RAILTIES = %w(Rails::Railtie Rails::Engine Rails::Application)
-
-
1
class << self
-
1
private :new
-
1
delegate :config, to: :instance
-
-
1
def subclasses
-
36
@subclasses ||= []
-
end
-
-
1
def inherited(base)
-
36
unless base.abstract_railtie?
-
34
subclasses << base
-
end
-
end
-
-
1
def rake_tasks(&blk)
-
6
@rake_tasks ||= []
-
6
@rake_tasks << blk if blk
-
6
@rake_tasks
-
end
-
-
1
def console(&blk)
-
3
@load_console ||= []
-
3
@load_console << blk if blk
-
3
@load_console
-
end
-
-
1
def runner(&blk)
-
1
@load_runner ||= []
-
1
@load_runner << blk if blk
-
1
@load_runner
-
end
-
-
1
def generators(&blk)
-
1
@generators ||= []
-
1
@generators << blk if blk
-
1
@generators
-
end
-
-
1
def abstract_railtie?
-
85
ABSTRACT_RAILTIES.include?(name)
-
end
-
-
1
def railtie_name(name = nil)
-
2
@railtie_name = name.to_s if name
-
2
@railtie_name ||= generate_railtie_name(self.name)
-
end
-
-
# Since Rails::Railtie cannot be instantiated, any methods that call
-
# +instance+ are intended to be called only on subclasses of a Railtie.
-
1
def instance
-
125
@instance ||= new
-
end
-
-
1
def respond_to_missing?(*args)
-
instance.respond_to?(*args) || super
-
end
-
-
# Allows you to configure the railtie. This is the same method seen in
-
# Railtie::Configurable, but this module is no longer required for all
-
# subclasses of Railtie so we provide the class method here.
-
1
def configure(&block)
-
1
instance.configure(&block)
-
end
-
-
1
protected
-
1
def generate_railtie_name(class_or_module)
-
1
ActiveSupport::Inflector.underscore(class_or_module).tr("/", "_")
-
end
-
-
# If the class method does not have a method, then send the method call
-
# to the Railtie instance.
-
1
def method_missing(name, *args, &block)
-
3
if instance.respond_to?(name)
-
3
instance.public_send(name, *args, &block)
-
else
-
super
-
end
-
end
-
end
-
-
1
delegate :railtie_name, to: :class
-
-
1
def initialize
-
34
if self.class.abstract_railtie?
-
raise "#{self.class.name} is abstract, you cannot instantiate it directly."
-
end
-
end
-
-
1
def configure(&block)
-
1
instance_eval(&block)
-
end
-
-
1
def config
-
94
@config ||= Railtie::Configuration.new
-
end
-
-
1
def railtie_namespace
-
@railtie_namespace ||= self.class.parents.detect { |n| n.respond_to?(:railtie_namespace) }
-
end
-
-
1
protected
-
-
1
def run_console_blocks(app) #:nodoc:
-
each_registered_block(:console) { |block| block.call(app) }
-
end
-
-
1
def run_generators_blocks(app) #:nodoc:
-
each_registered_block(:generators) { |block| block.call(app) }
-
end
-
-
1
def run_runner_blocks(app) #:nodoc:
-
each_registered_block(:runner) { |block| block.call(app) }
-
end
-
-
1
def run_tasks_blocks(app) #:nodoc:
-
extend Rake::DSL
-
each_registered_block(:rake_tasks) { |block| instance_exec(app, &block) }
-
end
-
-
1
private
-
-
1
def each_registered_block(type, &block)
-
klass = self.class
-
while klass.respond_to?(type)
-
klass.public_send(type).each(&block)
-
klass = klass.superclass
-
end
-
end
-
end
-
end
-
1
require 'rails/configuration'
-
-
1
module Rails
-
1
class Railtie
-
1
class Configuration
-
1
def initialize
-
32
@@options ||= {}
-
end
-
-
# Expose the eager_load_namespaces at "module" level for convenience.
-
1
def self.eager_load_namespaces #:nodoc:
-
14
@@eager_load_namespaces ||= []
-
end
-
-
# All namespaces that are eager loaded
-
1
def eager_load_namespaces
-
7
@@eager_load_namespaces ||= []
-
end
-
-
# Add files that should be watched for change.
-
1
def watchable_files
-
2
@@watchable_files ||= []
-
end
-
-
# Add directories that should be watched for change.
-
# The key of the hashes should be directories and the values should
-
# be an array of extensions to match in each directory.
-
1
def watchable_dirs
-
1
@@watchable_dirs ||= {}
-
end
-
-
# This allows you to modify the application's middlewares from Engines.
-
#
-
# All operations you run on the app_middleware will be replayed on the
-
# application once it is defined and the default_middlewares are
-
# created
-
1
def app_middleware
-
4
@@app_middleware ||= Rails::Configuration::MiddlewareStackProxy.new
-
end
-
-
# This allows you to modify application's generators from Railties.
-
#
-
# Values set on app_generators will become defaults for application, unless
-
# application overwrites them.
-
1
def app_generators
-
23
@@app_generators ||= Rails::Configuration::Generators.new
-
23
yield(@@app_generators) if block_given?
-
23
@@app_generators
-
end
-
-
# First configurable block to run. Called before any initializers are run.
-
1
def before_configuration(&block)
-
2
ActiveSupport.on_load(:before_configuration, yield: true, &block)
-
end
-
-
# Third configurable block to run. Does not run if +config.cache_classes+
-
# set to false.
-
1
def before_eager_load(&block)
-
2
ActiveSupport.on_load(:before_eager_load, yield: true, &block)
-
end
-
-
# Second configurable block to run. Called before frameworks initialize.
-
1
def before_initialize(&block)
-
3
ActiveSupport.on_load(:before_initialize, yield: true, &block)
-
end
-
-
# Last configurable block to run. Called after frameworks initialize.
-
1
def after_initialize(&block)
-
6
ActiveSupport.on_load(:after_initialize, yield: true, &block)
-
end
-
-
# Array of callbacks defined by #to_prepare.
-
1
def to_prepare_blocks
-
1
@@to_prepare_blocks ||= []
-
end
-
-
# Defines generic callbacks to run before #after_initialize. Useful for
-
# Rails::Railtie subclasses.
-
1
def to_prepare(&blk)
-
to_prepare_blocks << blk if blk
-
end
-
-
1
def respond_to?(name, include_private = false)
-
2
super || @@options.key?(name.to_sym)
-
end
-
-
1
private
-
-
1
def method_missing(name, *args, &blk)
-
180
if name.to_s =~ /=$/
-
12
@@options[$`.to_sym] = args.first
-
168
elsif @@options.key?(name)
-
168
@@options[name]
-
else
-
super
-
end
-
end
-
end
-
end
-
end
-
1
if RUBY_VERSION < '1.9.3'
-
desc = defined?(RUBY_DESCRIPTION) ? RUBY_DESCRIPTION : "ruby #{RUBY_VERSION} (#{RUBY_RELEASE_DATE})"
-
abort <<-end_message
-
-
Rails 4 prefers to run on Ruby 2.0.
-
-
You're running
-
#{desc}
-
-
Please upgrade to Ruby 1.9.3 or newer to continue.
-
-
end_message
-
end
-
1
if defined?(Rake.application) && Rake.application.top_level_tasks.grep(/^(default$|test(:|$))/).any?
-
ENV['RAILS_ENV'] ||= 'test'
-
end
-
-
1
module Rails
-
1
class TestUnitRailtie < Rails::Railtie
-
1
config.app_generators do |c|
-
1
c.test_framework :test_unit, fixture: true,
-
fixture_replacement: nil
-
-
1
c.integration_tool :test_unit
-
end
-
-
1
rake_tasks do
-
load "rails/test_unit/testing.rake"
-
end
-
end
-
end
-
1
require_relative 'gem_version'
-
-
1
module Rails
-
# Returns the version of the currently loaded Rails as a string.
-
1
def self.version
-
1
VERSION::STRING
-
end
-
end
-
1
require 'redcarpet.so'
-
-
1
module Redcarpet
-
1
VERSION = '3.1.2'
-
-
1
class Markdown
-
1
attr_reader :renderer
-
end
-
-
1
module Render
-
-
# XHTML Renderer
-
1
class XHTML < HTML
-
1
def initialize(extensions={})
-
super(extensions.merge(:xhtml => true))
-
end
-
end
-
-
# HTML + SmartyPants renderer
-
1
class SmartyHTML < HTML
-
1
include SmartyPants
-
end
-
-
# SmartyPants Mixin module
-
#
-
# Implements SmartyPants.postprocess, which
-
# performs smartypants replacements on the HTML file,
-
# once it has been fully rendered.
-
#
-
# To add SmartyPants postprocessing to your custom
-
# renderers, just mixin the module `include SmartyPants`
-
#
-
# You can also use this as a standalone SmartyPants
-
# implementation.
-
#
-
# Example:
-
#
-
# # Mixin
-
# class CoolRenderer < HTML
-
# include SmartyPants
-
# # more code here
-
# end
-
#
-
# # Standalone
-
# Redcarpet::Render::SmartyPants.render("you're")
-
#
-
1
module SmartyPants
-
1
extend self
-
1
def self.render(text)
-
postprocess text
-
end
-
end
-
end
-
end
-
-
# Compatibility class;
-
# Creates an instance of Redcarpet with the RedCloth API.
-
1
class RedcarpetCompat
-
1
attr_accessor :text
-
-
1
def initialize(text, *exts)
-
exts_hash, render_hash = *parse_extensions_and_renderer_options(exts)
-
@text = text
-
renderer = Redcarpet::Render::HTML.new(render_hash)
-
@markdown = Redcarpet::Markdown.new(renderer, exts_hash)
-
end
-
-
1
def to_html(*_dummy)
-
@markdown.render(@text)
-
end
-
-
1
private
-
-
1
EXTENSION_MAP = {
-
# old name => new name
-
:autolink => :autolink,
-
:fenced_code => :fenced_code_blocks,
-
:filter_html => :filter_html,
-
:hard_wrap => :hard_wrap,
-
:prettify => :prettify,
-
:lax_htmlblock => :lax_spacing,
-
:no_image => :no_images,
-
:no_intraemphasis => :no_intra_emphasis,
-
:no_links => :no_links,
-
:filter_styles => :no_styles,
-
:safelink => :safe_links_only,
-
:space_header => :space_after_headers,
-
:strikethrough => :strikethrough,
-
:tables => :tables,
-
:generate_toc => :with_toc_data,
-
:xhtml => :xhtml,
-
# old names with no new mapping
-
:gh_blockcode => nil,
-
:no_tables => nil,
-
:smart => nil,
-
:strict => nil
-
}
-
-
1
RENDERER_OPTIONS = [:filter_html, :no_images, :no_links, :no_styles,
-
:safe_links_only, :with_toc_data, :hard_wrap, :prettify, :xhtml]
-
-
1
def rename_extensions(exts)
-
exts.map do |old_name|
-
if new_name = EXTENSION_MAP[old_name]
-
new_name
-
else
-
old_name
-
end
-
end.compact
-
end
-
-
# Returns two hashes, the extensions and renderer options
-
# given the extension list
-
1
def parse_extensions_and_renderer_options(exts)
-
exts = rename_extensions(exts)
-
exts.partition {|ext| !RENDERER_OPTIONS.include?(ext) }.
-
map {|list| list_to_truthy_hash(list) }
-
end
-
-
# Turns a list of symbols into a hash of <tt>symbol => true</tt>.
-
1
def list_to_truthy_hash(list)
-
list.inject({}) {|h, k| h[k] = true; h }
-
end
-
end
-
-
1
module Ref
-
1
require File.join(File.dirname(__FILE__), "ref", "abstract_reference_value_map.rb")
-
1
require File.join(File.dirname(__FILE__), "ref", "abstract_reference_key_map.rb")
-
1
require File.join(File.dirname(__FILE__), "ref", "reference.rb")
-
1
require File.join(File.dirname(__FILE__), "ref", "reference_queue.rb")
-
1
require File.join(File.dirname(__FILE__), "ref", "safe_monitor.rb")
-
-
# Set the best implementation for weak references based on the runtime.
-
1
if defined?(RUBY_PLATFORM) && RUBY_PLATFORM == 'java'
-
# Use native Java references
-
begin
-
$LOAD_PATH.unshift(File.dirname(__FILE__))
-
require 'org/jruby/ext/ref/references'
-
ensure
-
$LOAD_PATH.shift if $LOAD_PATH.first == File.dirname(__FILE__)
-
end
-
else
-
1
require File.join(File.dirname(__FILE__), "ref", "soft_reference.rb")
-
1
if defined?(RUBY_ENGINE) && RUBY_ENGINE == 'ironruby'
-
# IronRuby has it's own implementation of weak references.
-
require File.join(File.dirname(__FILE__), "ref", "weak_reference", "iron_ruby.rb")
-
elsif defined?(RUBY_ENGINE) && RUBY_ENGINE == 'rbx'
-
# If using Rubinius set the implementation to use WeakRef since it is very efficient and using finalizers is not.
-
require File.join(File.dirname(__FILE__), "ref", "weak_reference", "weak_ref.rb")
-
elsif defined?(::ObjectSpace::WeakMap)
-
# Ruby 2.0 has a working implementation of weakref.rb backed by the new ObjectSpace::WeakMap
-
1
require File.join(File.dirname(__FILE__), "ref", "weak_reference", "weak_ref.rb")
-
elsif defined?(::ObjectSpace._id2ref)
-
# If ObjectSpace can lookup objects from their object_id, then use the pure ruby implementation.
-
require File.join(File.dirname(__FILE__), "ref", "weak_reference", "pure_ruby.rb")
-
else
-
# Otherwise, wrap the standard library WeakRef class
-
require File.join(File.dirname(__FILE__), "ref", "weak_reference", "weak_ref.rb")
-
end
-
end
-
-
1
require File.join(File.dirname(__FILE__), "ref", "soft_key_map.rb")
-
1
require File.join(File.dirname(__FILE__), "ref", "soft_value_map.rb")
-
1
require File.join(File.dirname(__FILE__), "ref", "strong_reference.rb")
-
1
require File.join(File.dirname(__FILE__), "ref", "weak_key_map.rb")
-
1
require File.join(File.dirname(__FILE__), "ref", "weak_value_map.rb")
-
-
# Used for testing
-
1
autoload :Mock, File.join(File.dirname(__FILE__), "ref", "mock.rb")
-
end
-
1
module Ref
-
# Abstract base class for WeakKeyMap and SoftKeyMap.
-
#
-
# The classes behave similar to Hashes, but the keys in the map are not strong references
-
# and can be reclaimed by the garbage collector at any time. When a key is reclaimed, the
-
# map entry will be removed.
-
1
class AbstractReferenceKeyMap
-
1
class << self
-
1
def reference_class=(klass) #:nodoc:
-
2
@reference_class = klass
-
end
-
-
1
def reference_class #:nodoc:
-
raise NotImplementedError.new("#{name} is an abstract class and cannot be instantiated") unless @reference_class
-
@reference_class
-
end
-
end
-
-
# Create a new map. Values added to the hash will be cleaned up by the garbage
-
# collector if there are no other reference except in the map.
-
1
def initialize
-
@values = {}
-
@references_to_keys_map = {}
-
@lock = SafeMonitor.new
-
@reference_cleanup = lambda{|object_id| remove_reference_to(object_id)}
-
end
-
-
# Get a value from the map by key. If the value has been reclaimed by the garbage
-
# collector, this will return nil.
-
1
def [](key)
-
rkey = ref_key(key)
-
@values[rkey] if rkey
-
end
-
-
# Add a key/value to the map.
-
1
def []=(key, value)
-
ObjectSpace.define_finalizer(key, @reference_cleanup)
-
@lock.synchronize do
-
@references_to_keys_map[key.__id__] = self.class.reference_class.new(key)
-
@values[key.__id__] = value
-
end
-
end
-
-
# Remove the value associated with the key from the map.
-
1
def delete(key)
-
rkey = ref_key(key)
-
if rkey
-
@references_to_keys_map.delete(rkey)
-
@values.delete(rkey)
-
else
-
nil
-
end
-
end
-
-
# Get an array of keys that have not yet been garbage collected.
-
1
def keys
-
@values.keys.collect{|rkey| @references_to_keys_map[rkey].object}.compact
-
end
-
-
# Turn the map into an arry of [key, value] entries.
-
1
def to_a
-
array = []
-
each{|k,v| array << [k, v]}
-
array
-
end
-
-
# Iterate through all the key/value pairs in the map that have not been reclaimed
-
# by the garbage collector.
-
1
def each
-
@references_to_keys_map.each do |rkey, ref|
-
key = ref.object
-
yield(key, @values[rkey]) if key
-
end
-
end
-
-
# Clear the map of all key/value pairs.
-
1
def clear
-
@lock.synchronize do
-
@values.clear
-
@references_to_keys_map.clear
-
end
-
end
-
-
# Merge the values from another hash into this map.
-
1
def merge!(other_hash)
-
other_hash.each do |key, value|
-
self[key] = value
-
end
-
end
-
-
1
def inspect
-
live_entries = {}
-
each do |key, value|
-
live_entries[key] = value
-
end
-
live_entries.inspect
-
end
-
-
1
private
-
-
1
def ref_key (key)
-
ref = @references_to_keys_map[key.__id__]
-
if ref && ref.object
-
ref.referenced_object_id
-
else
-
nil
-
end
-
end
-
-
1
def remove_reference_to(object_id)
-
@lock.synchronize do
-
@references_to_keys_map.delete(object_id)
-
@values.delete(object_id)
-
end
-
end
-
end
-
end
-
1
module Ref
-
# Abstract base class for WeakValueMap and SoftValueMap.
-
#
-
# The classes behave similar to Hashes, but the values in the map are not strong references
-
# and can be reclaimed by the garbage collector at any time. When a value is reclaimed, the
-
# map entry will be removed.
-
1
class AbstractReferenceValueMap
-
1
class << self
-
1
def reference_class=(klass) #:nodoc:
-
2
@reference_class = klass
-
end
-
-
1
def reference_class #:nodoc:
-
raise NotImplementedError.new("#{name} is an abstract class and cannot be instantiated") unless @reference_class
-
@reference_class
-
end
-
end
-
-
# Create a new map. Values added to the map will be cleaned up by the garbage
-
# collector if there are no other reference except in the map.
-
1
def initialize
-
@references = {}
-
@references_to_keys_map = {}
-
@lock = SafeMonitor.new
-
@reference_cleanup = lambda{|object_id| remove_reference_to(object_id)}
-
end
-
-
# Get a value from the map by key. If the value has been reclaimed by the garbage
-
# collector, this will return nil.
-
1
def [](key)
-
ref = @references[key]
-
value = ref.object if ref
-
value
-
end
-
-
# Add a key/value to the map.
-
1
def []=(key, value)
-
ObjectSpace.define_finalizer(value, @reference_cleanup)
-
key = key.dup if key.is_a?(String)
-
@lock.synchronize do
-
@references[key] = self.class.reference_class.new(value)
-
keys_for_id = @references_to_keys_map[value.__id__]
-
unless keys_for_id
-
keys_for_id = []
-
@references_to_keys_map[value.__id__] = keys_for_id
-
end
-
keys_for_id << key
-
end
-
value
-
end
-
-
# Remove the entry associated with the key from the map.
-
1
def delete(key)
-
ref = @references.delete(key)
-
if ref
-
keys_to_id = @references_to_keys_map[ref.referenced_object_id]
-
if keys_to_id
-
keys_to_id.delete(key)
-
@references_to_keys_map.delete(ref.referenced_object_id) if keys_to_id.empty?
-
end
-
ref.object
-
else
-
nil
-
end
-
end
-
-
# Get the list of all values that have not yet been garbage collected.
-
1
def values
-
vals = []
-
each{|k,v| vals << v}
-
vals
-
end
-
-
# Turn the map into an arry of [key, value] entries
-
1
def to_a
-
array = []
-
each{|k,v| array << [k, v]}
-
array
-
end
-
-
# Iterate through all the key/value pairs in the map that have not been reclaimed
-
# by the garbage collector.
-
1
def each
-
@references.each do |key, ref|
-
value = ref.object
-
yield(key, value) if value
-
end
-
end
-
-
# Clear the map of all key/value pairs.
-
1
def clear
-
@lock.synchronize do
-
@references.clear
-
@references_to_keys_map.clear
-
end
-
end
-
-
# Merge the values from another hash into this map.
-
1
def merge!(other_hash)
-
other_hash.each do |key, value|
-
self[key] = value
-
end
-
end
-
-
1
def inspect
-
live_entries = {}
-
each do |key, value|
-
live_entries[key] = value
-
end
-
live_entries.inspect
-
end
-
-
1
private
-
-
1
def remove_reference_to(object_id)
-
@lock.synchronize do
-
keys = @references_to_keys_map[object_id]
-
if keys
-
keys.each do |key|
-
@references.delete(key)
-
end
-
@references_to_keys_map.delete(object_id)
-
end
-
end
-
end
-
end
-
end
-
1
module Ref
-
# This class serves as a generic reference mechanism to other objects. The
-
# actual reference can be either a WeakReference, SoftReference, or StrongReference.
-
1
class Reference
-
# The object id of the object being referenced.
-
1
attr_reader :referenced_object_id
-
-
# Create a new reference to an object.
-
1
def initialize(obj)
-
raise NotImplementedError.new("cannot instantiate a generic reference")
-
end
-
-
# Get the referenced object. This could be nil if the reference
-
# is a WeakReference or a SoftReference and the object has been reclaimed by the garbage collector.
-
1
def object
-
raise NotImplementedError
-
end
-
-
1
def inspect
-
obj = object
-
"<##{self.class.name}: #{obj ? obj.inspect : "##{referenced_object_id} (not accessible)"}>"
-
end
-
end
-
end
-
1
module Ref
-
# This class provides a simple thread safe container to hold a reference queue. Instances
-
# of WeakReference can be added to the queue and as the objects pointed to by those references
-
# are cleaned up by the garbage collector, the references will be added to the queue.
-
#
-
# The reason for using a reference queue is that it tends to be more efficient than adding
-
# individual finalizers to objects and the cleanup code can be handled by a thread outside
-
# of garbage collection.
-
#
-
# In general, you should create your own subclass of WeakReference that contains the logic
-
# needed to complete the cleanup. The object pointed to will have already been cleaned up
-
# and the reference cannot maintain a reference to the object.
-
#
-
# === Example usage:
-
#
-
# class MyRef < Ref::WeakReference
-
# def cleanup
-
# # Do something...
-
# end
-
# end
-
#
-
# queue = Ref::ReferenceQueue.new
-
# ref = MyRef.new(Object.new)
-
# queue.monitor(ref)
-
# queue.shift # = nil
-
# ObjectSpace.garbage_collect
-
# r = queue.shift # = ref
-
# r.cleanup
-
1
class ReferenceQueue
-
1
def initialize
-
@queue = []
-
@references = {}
-
@lock = SafeMonitor.new
-
@finalizer = lambda do |object_id|
-
@lock.synchronize do
-
ref = @references.delete(object_id)
-
@queue.push(ref) if ref
-
end
-
end
-
end
-
-
# Monitor a reference. When the object the reference points to is garbage collected,
-
# the reference will be added to the queue.
-
1
def monitor(reference)
-
obj = reference.object
-
if obj
-
@lock.synchronize do
-
@references[reference.referenced_object_id] = reference
-
end
-
ObjectSpace.define_finalizer(obj, @finalizer)
-
else
-
push(reference)
-
end
-
end
-
-
# Add a reference to the queue.
-
1
def push(reference)
-
if reference
-
@lock.synchronize do
-
@queue.push(reference)
-
end
-
end
-
end
-
-
# Pull the last reference off the queue. Returns +nil+ if their are no references.
-
1
def pop
-
@lock.synchronize do
-
@queue.pop
-
end
-
end
-
-
# Pull the next reference off the queue. Returns +nil+ if there are no references.
-
1
def shift
-
@lock.synchronize do
-
@queue.shift
-
end
-
end
-
-
# Return +true+ if the queue is empty.
-
1
def empty?
-
@queue.empty?
-
end
-
-
# Get the current size of the queue.
-
1
def size
-
@queue.size
-
end
-
end
-
end
-
1
begin
-
1
require 'thread'
-
rescue LoadError
-
# Threads not available. Monitor will do nothing.
-
end
-
-
1
module Ref
-
# The Monitor class in Ruby 1.8 has some bugs and also threads may not be available on all
-
# runtimes. This class provides a simple, safe re-entrant mutex as an alternative.
-
1
class SafeMonitor
-
1
def initialize
-
1
@owner = nil
-
1
@count = 0
-
1
@mutex = defined?(Mutex) ? Mutex.new : nil
-
end
-
-
# Acquire an exclusive lock.
-
1
def lock
-
if @mutex
-
if @owner != Thread.current.object_id
-
@mutex.lock
-
@owner = Thread.current.object_id
-
end
-
@count += 1
-
end
-
true
-
end
-
-
# Release the exclusive lock.
-
1
def unlock
-
if @mutex
-
if @owner == Thread.current.object_id
-
@count -= 1
-
if @count == 0
-
@owner = nil
-
@mutex.unlock
-
end
-
end
-
end
-
end
-
-
# Run a block of code with an exclusive lock.
-
1
def synchronize
-
lock
-
yield
-
ensure
-
unlock
-
end
-
end
-
end
-
1
module Ref
-
# Implementation of a map in which only softly referenced keys are kept to the map values.
-
# This allows the garbage collector to reclaim these objects if the only reference to them
-
# is the soft reference in the map.
-
#
-
# This is often useful for cache implementations since the map can be allowed to grow
-
# without bound and the garbage collector can be relied on to clean it up as necessary.
-
# One must be careful, though, when accessing entries since they can be collected at
-
# any time until there is a strong reference to the key.
-
#
-
# === Example usage:
-
#
-
# cache = Ref::SoftKeyMap.new
-
# obj = MyObject.find_by_whatever
-
# obj_info = Service.lookup_object_info(obj)
-
# cache[obj] = Service.lookup_object_info(obj)
-
# cache[obj] # The values looked up from the service
-
# obj = nil
-
# ObjectSpace.garbage_collect
-
# cache.keys # empty array since the keys and values have been reclaimed
-
#
-
# See AbstractReferenceKeyMap for details.
-
1
class SoftKeyMap < AbstractReferenceKeyMap
-
1
self.reference_class = SoftReference
-
end
-
end
-
1
module Ref
-
# A SoftReference represents a reference to an object that is not seen by
-
# the tracing phase of the garbage collector. This allows the referenced
-
# object to be garbage collected as if nothing is referring to it.
-
#
-
# A SoftReference differs from a WeakReference in that the garbage collector
-
# is not so eager to reclaim soft references so they should persist longer.
-
#
-
# === Example usage:
-
#
-
# foo = Object.new
-
# ref = Ref::SoftReference.new(foo)
-
# ref.object # should be foo
-
# ObjectSpace.garbage_collect
-
# ref.object # should be foo
-
# ObjectSpace.garbage_collect
-
# ObjectSpace.garbage_collect
-
# ref.object # should be nil
-
1
class SoftReference < Reference
-
1
@@strong_references = [{}]
-
1
@@gc_flag_set = false
-
-
# Number of garbage collection cycles after an object is used before a reference to it can be reclaimed.
-
1
MIN_GC_CYCLES = 10
-
-
1
@@lock = SafeMonitor.new
-
-
1
@@finalizer = lambda do |object_id|
-
@@lock.synchronize do
-
while @@strong_references.size >= MIN_GC_CYCLES do
-
@@strong_references.shift
-
end
-
@@strong_references.push({}) if @@strong_references.size < MIN_GC_CYCLES
-
@@gc_flag_set = false
-
end
-
end
-
-
# Create a new soft reference to an object.
-
1
def initialize(obj)
-
@referenced_object_id = obj.__id__
-
@weak_reference = WeakReference.new(obj)
-
add_strong_reference(obj)
-
end
-
-
# Get the referenced object. If the object has been reclaimed by the
-
# garbage collector, then this will return nil.
-
1
def object
-
obj = @weak_reference.object
-
# add a temporary strong reference each time the object is referenced.
-
add_strong_reference(obj) if obj
-
obj
-
end
-
-
1
private
-
# Create a strong reference to the object. This reference will live
-
# for three passes of the garbage collector.
-
1
def add_strong_reference(obj) #:nodoc:
-
@@lock.synchronize do
-
@@strong_references.last[obj] = true
-
unless @@gc_flag_set
-
@@gc_flag_set = true
-
ObjectSpace.define_finalizer(Object.new, @@finalizer)
-
end
-
end
-
end
-
end
-
end
-
1
module Ref
-
# Implementation of a map in which soft references are kept to the map values.
-
# This allows the garbage collector to reclaim these objects if the
-
# only reference to them is the soft reference in the map.
-
#
-
# This is often useful for cache implementations since the map can be allowed to grow
-
# without bound and the garbage collector can be relied on to clean it up as necessary.
-
# One must be careful, though, when accessing entries since the values can be collected
-
# at any time until there is a strong reference to them.
-
#
-
# === Example usage:
-
#
-
# cache = Ref::SoftValueMap.new
-
# foo = "foo"
-
# cache["strong"] = foo # add a value with a strong reference
-
# cache["soft"] = "bar" # add a value without a strong reference
-
# cache["strong"] # "foo"
-
# cache["soft"] # "bar"
-
# ObjectSpace.garbage_collect
-
# ObjectSpace.garbage_collect
-
# cache["strong"] # "foo"
-
# cache["soft"] # nil
-
#
-
# See AbstractReferenceValueMap for details.
-
1
class SoftValueMap < AbstractReferenceValueMap
-
1
self.reference_class = SoftReference
-
end
-
end
-
1
module Ref
-
# This implementation of Reference holds a strong reference to an object. The
-
# referenced object will not be garbage collected as long as the strong reference
-
# exists.
-
1
class StrongReference < Reference
-
# Create a new strong reference to an object.
-
1
def initialize(obj)
-
@obj = obj
-
@referenced_object_id = obj.__id__
-
end
-
-
# Get the referenced object.
-
1
def object
-
@obj
-
end
-
end
-
end
-
1
module Ref
-
# Implementation of a map in which only weakly referenced keys are kept to the map values.
-
# This allows the garbage collector to reclaim these objects if the only reference to them
-
# is the weak reference in the map.
-
#
-
# This is often useful for cache implementations since the map can be allowed to grow
-
# without bound and the garbage collector can be relied on to clean it up as necessary.
-
# One must be careful, though, when accessing entries since they can be collected at
-
# any time until there is a strong reference to the key.
-
#
-
# === Example usage:
-
#
-
# cache = Ref::WeakKeyMap.new
-
# obj = MyObject.find_by_whatever
-
# obj_info = Service.lookup_object_info(obj)
-
# cache[obj] = Service.lookup_object_info(obj)
-
# cache[obj] # The values looked up from the service
-
# obj = nil
-
# ObjectSpace.garbage_collect
-
# cache.keys # empty array since the keys and values have been reclaimed
-
#
-
# See AbstractReferenceKeyMap for details.
-
1
class WeakKeyMap < AbstractReferenceKeyMap
-
1
self.reference_class = WeakReference
-
end
-
end
-
1
require 'weakref'
-
-
1
module Ref
-
1
class WeakReference < Reference
-
# This implementation of a weak reference simply wraps the standard WeakRef implementation
-
# that comes with the Ruby standard library.
-
1
def initialize(obj) #:nodoc:
-
@referenced_object_id = obj.__id__
-
@ref = ::WeakRef.new(obj)
-
end
-
-
1
def object #:nodoc:
-
@ref.__getobj__
-
rescue => e
-
# Jruby implementation uses RefError while MRI uses WeakRef::RefError
-
if (defined?(RefError) && e.is_a?(RefError)) || (defined?(::WeakRef::RefError) && e.is_a?(::WeakRef::RefError))
-
nil
-
else
-
raise e
-
end
-
end
-
end
-
end
-
1
module Ref
-
# Implementation of a map in which weak references are kept to the map values.
-
# This allows the garbage collector to reclaim these objects if the
-
# only reference to them is the weak reference in the map.
-
#
-
# This is often useful for cache implementations since the map can be allowed to grow
-
# without bound and the garbage collector can be relied on to clean it up as necessary.
-
# One must be careful, though, when accessing entries since the values can be collected
-
# at any time until there is a strong reference to them.
-
#
-
# === Example usage:
-
#
-
# cache = Ref::WeakValueMap.new
-
# foo = "foo"
-
# cache["strong"] = foo # add a value with a strong reference
-
# cache["weak"] = "bar" # add a value without a strong reference
-
# cache["strong"] # "foo"
-
# cache["weak"] # "bar"
-
# ObjectSpace.garbage_collect
-
# cache["strong"] # "foo"
-
# cache["weak"] # nil
-
#
-
# See AbstractReferenceValueMap for details.
-
1
class WeakValueMap < AbstractReferenceValueMap
-
1
self.reference_class = WeakReference
-
end
-
end
-
1
require 'rspec/support'
-
1
RSpec::Support.require_rspec_support "caller_filter"
-
1
RSpec::Support.require_rspec_support "warnings"
-
-
1
require 'rspec/matchers'
-
-
7
RSpec::Support.define_optimized_require_for_rspec(:expectations) { |f| require_relative(f) }
-
-
%w[
-
expectation_target
-
configuration
-
fail_with
-
handler
-
version
-
6
].each { |file| RSpec::Support.require_rspec_expectations(file) }
-
-
1
module RSpec
-
# RSpec::Expectations provides a simple, readable API to express
-
# the expected outcomes in a code example. To express an expected
-
# outcome, wrap an object or block in `expect`, call `to` or `to_not`
-
# (aliased as `not_to`) and pass it a matcher object:
-
#
-
# expect(order.total).to eq(Money.new(5.55, :USD))
-
# expect(list).to include(user)
-
# expect(message).not_to match(/foo/)
-
# expect { do_something }.to raise_error
-
#
-
# The last form (the block form) is needed to match against ruby constructs
-
# that are not objects, but can only be observed when executing a block
-
# of code. This includes raising errors, throwing symbols, yielding,
-
# and changing values.
-
#
-
# When `expect(...).to` is invoked with a matcher, it turns around
-
# and calls `matcher.matches?(<object wrapped by expect>)`. For example,
-
# in the expression:
-
#
-
# expect(order.total).to eq(Money.new(5.55, :USD))
-
#
-
# ...`eq(Money.new(5.55, :USD))` returns a matcher object, and it results
-
# in the equivalent of `eq.matches?(order.total)`. If `matches?` returns
-
# `true`, the expectation is met and execution continues. If `false`, then
-
# the spec fails with the message returned by `eq.failure_message`.
-
#
-
# Given the expression:
-
#
-
# expect(order.entries).not_to include(entry)
-
#
-
# ...the `not_to` method (also available as `to_not`) invokes the equivalent of
-
# `include.matches?(order.entries)`, but it interprets `false` as success, and
-
# `true` as a failure, using the message generated by
-
# `include.failure_message_when_negated`.
-
#
-
# rspec-expectations ships with a standard set of useful matchers, and writing
-
# your own matchers is quite simple.
-
#
-
# See [RSpec::Matchers](../RSpec/Matchers) for more information about the
-
# built-in matchers that ship with rspec-expectations, and how to write your
-
# own custom matchers.
-
1
module Expectations
-
# Exception raised when an expectation fails.
-
#
-
# @note We subclass Exception so that in a stub implementation if
-
# the user sets an expectation, it can't be caught in their
-
# code by a bare `rescue`.
-
# @api public
-
1
ExpectationNotMetError = Class.new(::Exception)
-
end
-
end
-
1
module RSpec
-
1
module Expectations
-
# Wraps the target of an expectation.
-
#
-
# @example
-
# expect(something) # => ExpectationTarget wrapping something
-
# expect { do_something } # => ExpectationTarget wrapping the block
-
#
-
# # used with `to`
-
# expect(actual).to eq(3)
-
#
-
# # with `not_to`
-
# expect(actual).not_to eq(3)
-
#
-
# @note `ExpectationTarget` is not intended to be instantiated
-
# directly by users. Use `expect` instead.
-
1
class ExpectationTarget
-
# @private
-
# Used as a sentinel value to be able to tell when the user
-
# did not pass an argument. We can't use `nil` for that because
-
# `nil` is a valid value to pass.
-
1
UndefinedValue = Module.new
-
-
# @api private
-
1
def initialize(value)
-
@target = value
-
end
-
-
# @private
-
1
def self.for(value, block)
-
if UndefinedValue.equal?(value)
-
unless block
-
raise ArgumentError, "You must pass either an argument or a block to `expect`."
-
end
-
BlockExpectationTarget.new(block)
-
elsif block
-
raise ArgumentError, "You cannot pass both an argument and a block to `expect`."
-
else
-
new(value)
-
end
-
end
-
-
# Runs the given expectation, passing if `matcher` returns true.
-
# @example
-
# expect(value).to eq(5)
-
# expect { perform }.to raise_error
-
# @param [Matcher]
-
# matcher
-
# @param [String or Proc] message optional message to display when the expectation fails
-
# @return [Boolean] true if the expectation succeeds (else raises)
-
# @see RSpec::Matchers
-
1
def to(matcher=nil, message=nil, &block)
-
prevent_operator_matchers(:to) unless matcher
-
RSpec::Expectations::PositiveExpectationHandler.handle_matcher(@target, matcher, message, &block)
-
end
-
-
# Runs the given expectation, passing if `matcher` returns false.
-
# @example
-
# expect(value).not_to eq(5)
-
# @param [Matcher]
-
# matcher
-
# @param [String or Proc] message optional message to display when the expectation fails
-
# @return [Boolean] false if the negative expectation succeeds (else raises)
-
# @see RSpec::Matchers
-
1
def not_to(matcher=nil, message=nil, &block)
-
prevent_operator_matchers(:not_to) unless matcher
-
RSpec::Expectations::NegativeExpectationHandler.handle_matcher(@target, matcher, message, &block)
-
end
-
1
alias to_not not_to
-
-
1
private
-
-
1
def prevent_operator_matchers(verb)
-
raise ArgumentError, "The expect syntax does not support operator matchers, " \
-
"so you must pass a matcher to `##{verb}`."
-
end
-
end
-
-
# @private
-
# Validates the provided matcher to ensure it supports block
-
# expectations, in order to avoid user confusion when they
-
# use a block thinking the expectation will be on the return
-
# value of the block rather than the block itself.
-
1
class BlockExpectationTarget < ExpectationTarget
-
1
def to(matcher, message=nil, &block)
-
enforce_block_expectation(matcher)
-
super
-
end
-
-
1
def not_to(matcher, message=nil, &block)
-
enforce_block_expectation(matcher)
-
super
-
end
-
1
alias to_not not_to
-
-
1
private
-
-
1
def enforce_block_expectation(matcher)
-
return if supports_block_expectations?(matcher)
-
-
raise ExpectationNotMetError, "You must pass an argument rather than " \
-
"a block to use the provided matcher (#{description_of matcher}), or " \
-
"the matcher must implement `supports_block_expectations?`."
-
end
-
-
1
def supports_block_expectations?(matcher)
-
matcher.supports_block_expectations?
-
rescue NoMethodError
-
false
-
end
-
-
1
def description_of(matcher)
-
matcher.description
-
rescue NoMethodError
-
matcher.inspect
-
end
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_support 'differ'
-
-
1
module RSpec
-
1
module Expectations
-
1
class << self
-
# @private
-
1
def differ
-
RSpec::Support::Differ.new(
-
:object_preparer => lambda { |object| RSpec::Matchers::Composable.surface_descriptions_in(object) },
-
:color => RSpec::Matchers.configuration.color?
-
)
-
end
-
-
# Raises an RSpec::Expectations::ExpectationNotMetError with message.
-
# @param [String] message
-
# @param [Object] expected
-
# @param [Object] actual
-
#
-
# Adds a diff to the failure message when `expected` and `actual` are
-
# both present.
-
1
def fail_with(message, expected=nil, actual=nil)
-
unless message
-
raise ArgumentError, "Failure message is nil. Does your matcher define the " \
-
"appropriate failure_message[_when_negated] method to return a string?"
-
end
-
-
diff = differ.diff(actual, expected)
-
message = "#{message}\nDiff:#{diff}" unless diff.empty?
-
-
raise RSpec::Expectations::ExpectationNotMetError, message
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Expectations
-
# @private
-
1
module ExpectationHelper
-
1
def self.check_message(msg)
-
unless msg.nil? || msg.respond_to?(:to_str) || msg.respond_to?(:call)
-
::Kernel.warn [
-
"WARNING: ignoring the provided expectation message argument (",
-
msg.inspect,
-
") since it is not a string or a proc."
-
].join
-
end
-
end
-
-
# Returns an RSpec-3+ compatible matcher, wrapping a legacy one
-
# in an adapter if necessary.
-
#
-
# @private
-
1
def self.modern_matcher_from(matcher)
-
LegacyMacherAdapter::RSpec2.wrap(matcher) ||
-
LegacyMacherAdapter::RSpec1.wrap(matcher) || matcher
-
end
-
-
1
def self.setup(handler, matcher, message)
-
check_message(message)
-
::RSpec::Matchers.last_expectation_handler = handler
-
::RSpec::Matchers.last_matcher = modern_matcher_from(matcher)
-
end
-
-
1
def self.handle_failure(matcher, message, failure_message_method)
-
message = message.call if message.respond_to?(:call)
-
message ||= matcher.__send__(failure_message_method)
-
-
if matcher.respond_to?(:diffable?) && matcher.diffable?
-
::RSpec::Expectations.fail_with message, matcher.expected, matcher.actual
-
else
-
::RSpec::Expectations.fail_with message
-
end
-
end
-
end
-
-
# @private
-
1
class PositiveExpectationHandler
-
1
def self.handle_matcher(actual, initial_matcher, message=nil, &block)
-
matcher = ExpectationHelper.setup(self, initial_matcher, message)
-
-
return ::RSpec::Matchers::BuiltIn::PositiveOperatorMatcher.new(actual) unless initial_matcher
-
matcher.matches?(actual, &block) || ExpectationHelper.handle_failure(matcher, message, :failure_message)
-
end
-
-
1
def self.verb
-
"should"
-
end
-
-
1
def self.should_method
-
:should
-
end
-
-
1
def self.opposite_should_method
-
:should_not
-
end
-
end
-
-
# @private
-
1
class NegativeExpectationHandler
-
1
def self.handle_matcher(actual, initial_matcher, message=nil, &block)
-
matcher = ExpectationHelper.setup(self, initial_matcher, message)
-
-
return ::RSpec::Matchers::BuiltIn::NegativeOperatorMatcher.new(actual) unless initial_matcher
-
!(does_not_match?(matcher, actual, &block) || ExpectationHelper.handle_failure(matcher, message, :failure_message_when_negated))
-
end
-
-
1
def self.does_not_match?(matcher, actual, &block)
-
if matcher.respond_to?(:does_not_match?)
-
matcher.does_not_match?(actual, &block)
-
else
-
!matcher.matches?(actual, &block)
-
end
-
end
-
-
1
def self.verb
-
"should not"
-
end
-
-
1
def self.should_method
-
:should_not
-
end
-
-
1
def self.opposite_should_method
-
:should
-
end
-
end
-
-
# Wraps a matcher written against one of the legacy protocols in
-
# order to present the current protocol.
-
#
-
# @private
-
1
class LegacyMacherAdapter < Matchers::MatcherDelegator
-
1
def initialize(matcher)
-
super
-
::RSpec.warn_deprecation(<<-EOS.gsub(/^\s+\|/, ''), :type => "legacy_matcher")
-
|#{matcher.class.name || matcher.inspect} implements a legacy RSpec matcher
-
|protocol. For the current protocol you should expose the failure messages
-
|via the `failure_message` and `failure_message_when_negated` methods.
-
|(Used from #{CallerFilter.first_non_rspec_line})
-
EOS
-
end
-
-
1
def self.wrap(matcher)
-
new(matcher) if interface_matches?(matcher)
-
end
-
-
# Starting in RSpec 1.2 (and continuing through all 2.x releases),
-
# the failure message protocol was:
-
# * `failure_message_for_should`
-
# * `failure_message_for_should_not`
-
# @private
-
1
class RSpec2 < self
-
1
def failure_message
-
base_matcher.failure_message_for_should
-
end
-
-
1
def failure_message_when_negated
-
base_matcher.failure_message_for_should_not
-
end
-
-
1
def self.interface_matches?(matcher)
-
(
-
!matcher.respond_to?(:failure_message) &&
-
matcher.respond_to?(:failure_message_for_should)
-
) || (
-
!matcher.respond_to?(:failure_message_when_negated) &&
-
matcher.respond_to?(:failure_message_for_should_not)
-
)
-
end
-
end
-
-
# Before RSpec 1.2, the failure message protocol was:
-
# * `failure_message`
-
# * `negative_failure_message`
-
# @private
-
1
class RSpec1 < self
-
1
def failure_message
-
base_matcher.failure_message
-
end
-
-
1
def failure_message_when_negated
-
base_matcher.negative_failure_message
-
end
-
-
# Note: `failure_message` is part of the RSpec 3 protocol
-
# (paired with `failure_message_when_negated`), so we don't check
-
# for `failure_message` here.
-
1
def self.interface_matches?(matcher)
-
!matcher.respond_to?(:failure_message_when_negated) &&
-
matcher.respond_to?(:negative_failure_message)
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Expectations
-
# @api private
-
# Provides methods for enabling and disabling the available
-
# syntaxes provided by rspec-expectations.
-
1
module Syntax
-
1
module_function
-
-
# @api private
-
# Determines where we add `should` and `should_not`.
-
1
def default_should_host
-
2
@default_should_host ||= ::Object.ancestors.last
-
end
-
-
# @api private
-
# Instructs rspec-expectations to warn on first usage of `should` or `should_not`.
-
# Enabled by default. This is largely here to facilitate testing.
-
1
def warn_about_should!
-
1
@warn_about_should = true
-
end
-
-
# @api private
-
# Generates a deprecation warning for the given method if no warning
-
# has already been issued.
-
1
def warn_about_should_unless_configured(method_name)
-
return unless @warn_about_should
-
-
RSpec.deprecate(
-
"Using `#{method_name}` from rspec-expectations' old `:should` syntax without explicitly enabling the syntax",
-
:replacement => "the new `:expect` syntax or explicitly enable `:should`"
-
)
-
-
@warn_about_should = false
-
end
-
-
# @api private
-
# Enables the `should` syntax.
-
1
def enable_should(syntax_host=default_should_host)
-
1
@warn_about_should = false if syntax_host == default_should_host
-
1
return if should_enabled?(syntax_host)
-
-
1
syntax_host.module_exec do
-
1
def should(matcher=nil, message=nil, &block)
-
::RSpec::Expectations::Syntax.warn_about_should_unless_configured(__method__)
-
::RSpec::Expectations::PositiveExpectationHandler.handle_matcher(self, matcher, message, &block)
-
end
-
-
1
def should_not(matcher=nil, message=nil, &block)
-
::RSpec::Expectations::Syntax.warn_about_should_unless_configured(__method__)
-
::RSpec::Expectations::NegativeExpectationHandler.handle_matcher(self, matcher, message, &block)
-
end
-
end
-
end
-
-
# @api private
-
# Disables the `should` syntax.
-
1
def disable_should(syntax_host=default_should_host)
-
return unless should_enabled?(syntax_host)
-
-
syntax_host.module_exec do
-
undef should
-
undef should_not
-
end
-
end
-
-
# @api private
-
# Enables the `expect` syntax.
-
1
def enable_expect(syntax_host=::RSpec::Matchers)
-
1
return if expect_enabled?(syntax_host)
-
-
1
syntax_host.module_exec do
-
1
def expect(value=::RSpec::Expectations::ExpectationTarget::UndefinedValue, &block)
-
::RSpec::Expectations::ExpectationTarget.for(value, block)
-
end
-
end
-
end
-
-
# @api private
-
# Disables the `expect` syntax.
-
1
def disable_expect(syntax_host=::RSpec::Matchers)
-
return unless expect_enabled?(syntax_host)
-
-
syntax_host.module_exec do
-
undef expect
-
end
-
end
-
-
# @api private
-
# Indicates whether or not the `should` syntax is enabled.
-
1
def should_enabled?(syntax_host=default_should_host)
-
1
syntax_host.method_defined?(:should)
-
end
-
-
# @api private
-
# Indicates whether or not the `expect` syntax is enabled.
-
1
def expect_enabled?(syntax_host=::RSpec::Matchers)
-
1
syntax_host.method_defined?(:expect)
-
end
-
end
-
end
-
end
-
-
1
if defined?(BasicObject)
-
# The legacy `:should` syntax adds the following methods directly to
-
# `BasicObject` so that they are available off of any object. Note, however,
-
# that this syntax does not always play nice with delegate/proxy objects.
-
# We recommend you use the non-monkeypatching `:expect` syntax instead.
-
1
class BasicObject
-
# @method should
-
# Passes if `matcher` returns true. Available on every `Object`.
-
# @example
-
# actual.should eq expected
-
# actual.should match /expression/
-
# @param [Matcher]
-
# matcher
-
# @param [String] message optional message to display when the expectation fails
-
# @return [Boolean] true if the expectation succeeds (else raises)
-
# @note This is only available when you have enabled the `:should` syntax.
-
# @see RSpec::Matchers
-
-
# @method should_not
-
# Passes if `matcher` returns false. Available on every `Object`.
-
# @example
-
# actual.should_not eq expected
-
# @param [Matcher]
-
# matcher
-
# @param [String] message optional message to display when the expectation fails
-
# @return [Boolean] false if the negative expectation succeeds (else raises)
-
# @note This is only available when you have enabled the `:should` syntax.
-
# @see RSpec::Matchers
-
end
-
end
-
1
module RSpec
-
1
module Expectations
-
# @private
-
1
module Version
-
1
STRING = '3.0.4'
-
end
-
end
-
end
-
1
require 'rspec/support'
-
9
RSpec::Support.define_optimized_require_for_rspec(:matchers) { |f| require_relative(f) }
-
-
%w[
-
pretty
-
composable
-
built_in
-
generated_descriptions
-
dsl
-
matcher_delegator
-
aliased_matcher
-
8
].each { |file| RSpec::Support.require_rspec_matchers(file) }
-
-
# RSpec's top level namespace. All of rspec-expectations is contained
-
# in the `RSpec::Expectations` and `RSpec::Matchers` namespaces.
-
1
module RSpec
-
# RSpec::Matchers provides a number of useful matchers we use to define
-
# expectations. A matcher is any object that responds to the following:
-
#
-
# matches?(actual)
-
# failure_message
-
#
-
# These methods are also part of the matcher protocol, but are optional:
-
#
-
# does_not_match?(actual)
-
# failure_message_when_negated
-
# description
-
# supports_block_expectations?
-
#
-
# ## Predicates
-
#
-
# In addition to matchers that are defined explicitly, RSpec will create
-
# custom matchers on the fly for any arbitrary predicate, giving your specs a
-
# much more natural language feel.
-
#
-
# A Ruby predicate is a method that ends with a "?" and returns true or false.
-
# Common examples are `empty?`, `nil?`, and `instance_of?`.
-
#
-
# All you need to do is write `expect(..).to be_` followed by the predicate
-
# without the question mark, and RSpec will figure it out from there.
-
# For example:
-
#
-
# expect([]).to be_empty # => [].empty?() | passes
-
# expect([]).not_to be_empty # => [].empty?() | fails
-
#
-
# In addtion to prefixing the predicate matchers with "be_", you can also use "be_a_"
-
# and "be_an_", making your specs read much more naturally:
-
#
-
# expect("a string").to be_an_instance_of(String) # =>"a string".instance_of?(String) # passes
-
#
-
# expect(3).to be_a_kind_of(Fixnum) # => 3.kind_of?(Numeric) | passes
-
# expect(3).to be_a_kind_of(Numeric) # => 3.kind_of?(Numeric) | passes
-
# expect(3).to be_an_instance_of(Fixnum) # => 3.instance_of?(Fixnum) | passes
-
# expect(3).not_to be_an_instance_of(Numeric) # => 3.instance_of?(Numeric) | fails
-
#
-
# RSpec will also create custom matchers for predicates like `has_key?`. To
-
# use this feature, just state that the object should have_key(:key) and RSpec will
-
# call has_key?(:key) on the target. For example:
-
#
-
# expect(:a => "A").to have_key(:a)
-
# expect(:a => "A").to have_key(:b) # fails
-
#
-
# You can use this feature to invoke any predicate that begins with "has_", whether it is
-
# part of the Ruby libraries (like `Hash#has_key?`) or a method you wrote on your own class.
-
#
-
# Note that RSpec does not provide composable aliases for these dynamic predicate
-
# matchers. You can easily define your own aliases, though:
-
#
-
# RSpec::Matchers.alias_matcher :a_user_who_is_an_admin, :be_an_admin
-
# expect(user_list).to include(a_user_who_is_an_admin)
-
#
-
# ## Custom Matchers
-
#
-
# When you find that none of the stock matchers provide a natural feeling
-
# expectation, you can very easily write your own using RSpec's matcher DSL
-
# or writing one from scratch.
-
#
-
# ### Matcher DSL
-
#
-
# Imagine that you are writing a game in which players can be in various
-
# zones on a virtual board. To specify that bob should be in zone 4, you
-
# could say:
-
#
-
# expect(bob.current_zone).to eql(Zone.new("4"))
-
#
-
# But you might find it more expressive to say:
-
#
-
# expect(bob).to be_in_zone("4")
-
#
-
# and/or
-
#
-
# expect(bob).not_to be_in_zone("3")
-
#
-
# You can create such a matcher like so:
-
#
-
# RSpec::Matchers.define :be_in_zone do |zone|
-
# match do |player|
-
# player.in_zone?(zone)
-
# end
-
# end
-
#
-
# This will generate a <tt>be_in_zone</tt> method that returns a matcher
-
# with logical default messages for failures. You can override the failure
-
# messages and the generated description as follows:
-
#
-
# RSpec::Matchers.define :be_in_zone do |zone|
-
# match do |player|
-
# player.in_zone?(zone)
-
# end
-
#
-
# failure_message do |player|
-
# # generate and return the appropriate string.
-
# end
-
#
-
# failure_message_when_negated do |player|
-
# # generate and return the appropriate string.
-
# end
-
#
-
# description do
-
# # generate and return the appropriate string.
-
# end
-
# end
-
#
-
# Each of the message-generation methods has access to the block arguments
-
# passed to the <tt>create</tt> method (in this case, <tt>zone</tt>). The
-
# failure message methods (<tt>failure_message</tt> and
-
# <tt>failure_message_when_negated</tt>) are passed the actual value (the
-
# receiver of <tt>expect(..)</tt> or <tt>expect(..).not_to</tt>).
-
#
-
# ### Custom Matcher from scratch
-
#
-
# You could also write a custom matcher from scratch, as follows:
-
#
-
# class BeInZone
-
# def initialize(expected)
-
# @expected = expected
-
# end
-
#
-
# def matches?(target)
-
# @target = target
-
# @target.current_zone.eql?(Zone.new(@expected))
-
# end
-
#
-
# def failure_message
-
# "expected #{@target.inspect} to be in Zone #{@expected}"
-
# end
-
#
-
# def failure_message_when_negated
-
# "expected #{@target.inspect} not to be in Zone #{@expected}"
-
# end
-
# end
-
#
-
# ... and a method like this:
-
#
-
# def be_in_zone(expected)
-
# BeInZone.new(expected)
-
# end
-
#
-
# And then expose the method to your specs. This is normally done
-
# by including the method and the class in a module, which is then
-
# included in your spec:
-
#
-
# module CustomGameMatchers
-
# class BeInZone
-
# # ...
-
# end
-
#
-
# def be_in_zone(expected)
-
# # ...
-
# end
-
# end
-
#
-
# describe "Player behaviour" do
-
# include CustomGameMatchers
-
# # ...
-
# end
-
#
-
# or you can include in globally in a spec_helper.rb file <tt>require</tt>d
-
# from your spec file(s):
-
#
-
# RSpec::configure do |config|
-
# config.include(CustomGameMatchers)
-
# end
-
#
-
# ### Making custom matchers composable
-
#
-
# RSpec's built-in matchers are designed to be composed, in expressions like:
-
#
-
# expect(["barn", 2.45]).to contain_exactly(
-
# a_value_within(0.1).of(2.5),
-
# a_string_starting_with("bar")
-
# )
-
#
-
# Custom matchers can easily participate in composed matcher expressions like these.
-
# Include {RSpec::Matchers::Composable} in your custom matcher to make it support
-
# being composed (matchers defined using the DSL have this included automatically).
-
# Within your matcher's `matches?` method (or the `match` block, if using the DSL),
-
# use `values_match?(expected, actual)` rather than `expected == actual`.
-
# Under the covers, `values_match?` is able to match arbitrary
-
# nested data structures containing a mix of both matchers and non-matcher objects.
-
# It uses `===` and `==` to perform the matching, considering the values to
-
# match if either returns `true`. The `Composable` mixin also provides some helper
-
# methods for surfacing the matcher descriptions within your matcher's description
-
# or failure messages.
-
#
-
# RSpec's built-in matchers each have a number of aliases that rephrase the matcher
-
# from a verb phrase (such as `be_within`) to a noun phrase (such as `a_value_within`),
-
# which reads better when the matcher is passed as an argument in a composed matcher
-
# expressions, and also uses the noun-phrase wording in the matcher's `description`,
-
# for readable failure messages. You can alias your custom matchers in similar fashion
-
# using {RSpec::Matchers.alias_matcher}.
-
1
module Matchers
-
# @method expect
-
# Supports `expect(actual).to matcher` syntax by wrapping `actual` in an
-
# `ExpectationTarget`.
-
# @example
-
# expect(actual).to eq(expected)
-
# expect(actual).not_to eq(expected)
-
# @return [ExpectationTarget]
-
# @see ExpectationTarget#to
-
# @see ExpectationTarget#not_to
-
-
# Defines a matcher alias. The returned matcher's `description` will be overriden
-
# to reflect the phrasing of the new name, which will be used in failure messages
-
# when passed as an argument to another matcher in a composed matcher expression.
-
#
-
# @param new_name [Symbol] the new name for the matcher
-
# @param old_name [Symbol] the original name for the matcher
-
# @yield [String] optional block that, when given is used to define the overriden
-
# description. The yielded arg is the original description. If no block is
-
# provided, a default description override is used based on the old and
-
# new names.
-
#
-
# @example
-
#
-
# RSpec::Matchers.alias_matcher :a_list_that_sums_to, :sum_to
-
# sum_to(3).description # => "sum to 3"
-
# a_list_that_sums_to(3).description # => "a list that sums to 3"
-
#
-
# @example
-
#
-
# RSpec::Matchers.alias_matcher :a_list_sorted_by, :be_sorted_by do |description|
-
# description.sub("be sorted by", "a list sorted by")
-
# end
-
#
-
# be_sorted_by(:age).description # => "be sorted by age"
-
# a_list_sorted_by(:age).description # => "a list sorted by age"
-
#
-
# @!macro [attach] alias_matcher
-
# @!parse
-
# alias $1 $2
-
1
def self.alias_matcher(new_name, old_name, &description_override)
-
description_override ||= lambda do |old_desc|
-
old_desc.gsub(Pretty.split_words(old_name), Pretty.split_words(new_name))
-
56
end
-
-
56
define_method(new_name) do |*args, &block|
-
matcher = __send__(old_name, *args, &block)
-
AliasedMatcher.new(matcher, description_override)
-
end
-
end
-
-
# Passes if actual is truthy (anything but false or nil)
-
1
def be_truthy
-
BuiltIn::BeTruthy.new
-
end
-
1
alias_matcher :a_truthy_value, :be_truthy
-
-
# Passes if actual is falsey (false or nil)
-
1
def be_falsey
-
BuiltIn::BeFalsey.new
-
end
-
1
alias_matcher :be_falsy, :be_falsey
-
1
alias_matcher :a_falsey_value, :be_falsey
-
1
alias_matcher :a_falsy_value, :be_falsey
-
-
# Passes if actual is nil
-
1
def be_nil
-
BuiltIn::BeNil.new
-
end
-
1
alias_matcher :a_nil_value, :be_nil
-
-
# @example
-
# expect(actual).to be_truthy
-
# expect(actual).to be_falsey
-
# expect(actual).to be_nil
-
# expect(actual).to be_[arbitrary_predicate](*args)
-
# expect(actual).not_to be_nil
-
# expect(actual).not_to be_[arbitrary_predicate](*args)
-
#
-
# Given true, false, or nil, will pass if actual value is true, false or
-
# nil (respectively). Given no args means the caller should satisfy an if
-
# condition (to be or not to be).
-
#
-
# Predicates are any Ruby method that ends in a "?" and returns true or
-
# false. Given be_ followed by arbitrary_predicate (without the "?"),
-
# RSpec will match convert that into a query against the target object.
-
#
-
# The arbitrary_predicate feature will handle any predicate prefixed with
-
# "be_an_" (e.g. be_an_instance_of), "be_a_" (e.g. be_a_kind_of) or "be_"
-
# (e.g. be_empty), letting you choose the prefix that best suits the
-
# predicate.
-
1
def be(*args)
-
args.empty? ? Matchers::BuiltIn::Be.new : equal(*args)
-
end
-
1
alias_matcher :a_value, :be
-
-
# passes if target.kind_of?(klass)
-
1
def be_a(klass)
-
be_a_kind_of(klass)
-
end
-
1
alias_method :be_an, :be_a
-
-
# Passes if actual.instance_of?(expected)
-
#
-
# @example
-
#
-
# expect(5).to be_an_instance_of(Fixnum)
-
# expect(5).not_to be_an_instance_of(Numeric)
-
# expect(5).not_to be_an_instance_of(Float)
-
1
def be_an_instance_of(expected)
-
BuiltIn::BeAnInstanceOf.new(expected)
-
end
-
1
alias_method :be_instance_of, :be_an_instance_of
-
1
alias_matcher :an_instance_of, :be_an_instance_of
-
-
# Passes if actual.kind_of?(expected)
-
#
-
# @example
-
#
-
# expect(5).to be_a_kind_of(Fixnum)
-
# expect(5).to be_a_kind_of(Numeric)
-
# expect(5).not_to be_a_kind_of(Float)
-
1
def be_a_kind_of(expected)
-
BuiltIn::BeAKindOf.new(expected)
-
end
-
1
alias_method :be_kind_of, :be_a_kind_of
-
1
alias_matcher :a_kind_of, :be_a_kind_of
-
-
# Passes if actual.between?(min, max). Works with any Comparable object,
-
# including String, Symbol, Time, or Numeric (Fixnum, Bignum, Integer,
-
# Float, Complex, and Rational).
-
#
-
# By default, `be_between` is inclusive (i.e. passes when given either the max or min value),
-
# but you can make it `exclusive` by chaining that off the matcher.
-
#
-
# @example
-
#
-
# expect(5).to be_between(1, 10)
-
# expect(11).not_to be_between(1, 10)
-
# expect(10).not_to be_between(1, 10).exclusive
-
1
def be_between(min, max)
-
BuiltIn::BeBetween.new(min, max)
-
end
-
1
alias_matcher :a_value_between, :be_between
-
-
# Passes if actual == expected +/- delta
-
#
-
# @example
-
#
-
# expect(result).to be_within(0.5).of(3.0)
-
# expect(result).not_to be_within(0.5).of(3.0)
-
1
def be_within(delta)
-
BuiltIn::BeWithin.new(delta)
-
end
-
1
alias_matcher :a_value_within, :be_within
-
1
alias_matcher :within, :be_within
-
-
# Applied to a proc, specifies that its execution will cause some value to
-
# change.
-
#
-
# @param [Object] receiver
-
# @param [Symbol] message the message to send the receiver
-
#
-
# You can either pass <tt>receiver</tt> and <tt>message</tt>, or a block,
-
# but not both.
-
#
-
# When passing a block, it must use the `{ ... }` format, not
-
# do/end, as `{ ... }` binds to the `change` method, whereas do/end
-
# would errantly bind to the `expect(..).to` or `expect(...).not_to` method.
-
#
-
# You can chain any of the following off of the end to specify details
-
# about the change:
-
#
-
# * `by`
-
# * `by_at_least`
-
# * `by_at_most`
-
# * `from`
-
# * `to`
-
#
-
# @example
-
#
-
# expect {
-
# team.add_player(player)
-
# }.to change(roster, :count)
-
#
-
# expect {
-
# team.add_player(player)
-
# }.to change(roster, :count).by(1)
-
#
-
# expect {
-
# team.add_player(player)
-
# }.to change(roster, :count).by_at_least(1)
-
#
-
# expect {
-
# team.add_player(player)
-
# }.to change(roster, :count).by_at_most(1)
-
#
-
# string = "string"
-
# expect {
-
# string.reverse!
-
# }.to change { string }.from("string").to("gnirts")
-
#
-
# string = "string"
-
# expect {
-
# string
-
# }.not_to change { string }.from("string")
-
#
-
# expect {
-
# person.happy_birthday
-
# }.to change(person, :birthday).from(32).to(33)
-
#
-
# expect {
-
# employee.develop_great_new_social_networking_app
-
# }.to change(employee, :title).from("Mail Clerk").to("CEO")
-
#
-
# expect {
-
# doctor.leave_office
-
# }.to change(doctor, :sign).from(/is in/).to(/is out/)
-
#
-
# user = User.new(:type => "admin")
-
# expect {
-
# user.symbolize_type
-
# }.to change(user, :type).from(String).to(Symbol)
-
#
-
# == Notes
-
#
-
# Evaluates `receiver.message` or `block` before and after it
-
# evaluates the block passed to `expect`.
-
#
-
# `expect( ... ).not_to change` supports the form that specifies `from`
-
# (which specifies what you expect the starting, unchanged value to be)
-
# but does not support forms with subsequent calls to `by`, `by_at_least`,
-
# `by_at_most` or `to`.
-
1
def change(receiver=nil, message=nil, &block)
-
BuiltIn::Change.new(receiver, message, &block)
-
end
-
1
alias_matcher :a_block_changing, :change
-
1
alias_matcher :changing, :change
-
-
# Passes if actual contains all of the expected regardless of order.
-
# This works for collections. Pass in multiple args and it will only
-
# pass if all args are found in collection.
-
#
-
# @note This is also available using the `=~` operator with `should`,
-
# but `=~` is not supported with `expect`.
-
#
-
# @note This matcher only supports positive expectations.
-
# `expect(...).not_to contain_exactly(other_array)` is not supported.
-
#
-
# @example
-
#
-
# expect([1, 2, 3]).to contain_exactly(1, 2, 3)
-
# expect([1, 2, 3]).to contain_exactly(1, 3, 2)
-
#
-
# @see #match_array
-
1
def contain_exactly(*items)
-
BuiltIn::ContainExactly.new(items)
-
end
-
1
alias_matcher :a_collection_containing_exactly, :contain_exactly
-
1
alias_matcher :containing_exactly, :contain_exactly
-
-
# Passes if actual covers expected. This works for
-
# Ranges. You can also pass in multiple args
-
# and it will only pass if all args are found in Range.
-
#
-
# @example
-
# expect(1..10).to cover(5)
-
# expect(1..10).to cover(4, 6)
-
# expect(1..10).to cover(4, 6, 11) # fails
-
# expect(1..10).not_to cover(11)
-
# expect(1..10).not_to cover(5) # fails
-
#
-
# ### Warning:: Ruby >= 1.9 only
-
1
def cover(*values)
-
BuiltIn::Cover.new(*values)
-
end
-
1
alias_matcher :a_range_covering, :cover
-
1
alias_matcher :covering, :cover
-
-
# Matches if the actual value ends with the expected value(s). In the case
-
# of a string, matches against the last `expected.length` characters of the
-
# actual string. In the case of an array, matches against the last
-
# `expected.length` elements of the actual array.
-
#
-
# @example
-
#
-
# expect("this string").to end_with "string"
-
# expect([0, 1, 2, 3, 4]).to end_with 4
-
# expect([0, 2, 3, 4, 4]).to end_with 3, 4
-
1
def end_with(*expected)
-
BuiltIn::EndWith.new(*expected)
-
end
-
1
alias_matcher :a_collection_ending_with, :end_with
-
1
alias_matcher :a_string_ending_with, :end_with
-
1
alias_matcher :ending_with, :end_with
-
-
# Passes if <tt>actual == expected</tt>.
-
#
-
# See http://www.ruby-doc.org/core/classes/Object.html#M001057 for more
-
# information about equality in Ruby.
-
#
-
# @example
-
#
-
# expect(5).to eq(5)
-
# expect(5).not_to eq(3)
-
1
def eq(expected)
-
BuiltIn::Eq.new(expected)
-
end
-
1
alias_matcher :an_object_eq_to, :eq
-
1
alias_matcher :eq_to, :eq
-
-
# Passes if `actual.eql?(expected)`
-
#
-
# See http://www.ruby-doc.org/core/classes/Object.html#M001057 for more
-
# information about equality in Ruby.
-
#
-
# @example
-
#
-
# expect(5).to eql(5)
-
# expect(5).not_to eql(3)
-
1
def eql(expected)
-
BuiltIn::Eql.new(expected)
-
end
-
1
alias_matcher :an_object_eql_to, :eql
-
1
alias_matcher :eql_to, :eql
-
-
# Passes if <tt>actual.equal?(expected)</tt> (object identity).
-
#
-
# See http://www.ruby-doc.org/core/classes/Object.html#M001057 for more
-
# information about equality in Ruby.
-
#
-
# @example
-
#
-
# expect(5).to equal(5) # Fixnums are equal
-
# expect("5").not_to equal("5") # Strings that look the same are not the same object
-
1
def equal(expected)
-
BuiltIn::Equal.new(expected)
-
end
-
1
alias_matcher :an_object_equal_to, :equal
-
1
alias_matcher :equal_to, :equal
-
-
# Passes if `actual.exist?` or `actual.exists?`
-
#
-
# @example
-
# expect(File).to exist("path/to/file")
-
1
def exist(*args)
-
BuiltIn::Exist.new(*args)
-
end
-
1
alias_matcher :an_object_existing, :exist
-
1
alias_matcher :existing, :exist
-
-
# Passes if actual includes expected. This works for
-
# collections and Strings. You can also pass in multiple args
-
# and it will only pass if all args are found in collection.
-
#
-
# @example
-
#
-
# expect([1,2,3]).to include(3)
-
# expect([1,2,3]).to include(2,3)
-
# expect([1,2,3]).to include(2,3,4) # fails
-
# expect([1,2,3]).not_to include(4)
-
# expect("spread").to include("read")
-
# expect("spread").not_to include("red")
-
1
def include(*expected)
-
BuiltIn::Include.new(*expected)
-
end
-
1
alias_matcher :a_collection_including, :include
-
1
alias_matcher :a_string_including, :include
-
1
alias_matcher :a_hash_including, :include
-
1
alias_matcher :including, :include
-
-
# Passes if actual all expected objects pass. This works for
-
# any enumerable object.
-
#
-
# @example
-
#
-
# expect([1, 3, 5]).to all be_odd
-
# expect([1, 3, 6]).to all be_odd # fails
-
#
-
# @note The negative form `not_to all` is not supported. Instead
-
# use `not_to include` or pass a negative form of a matcher
-
# as the argument (e.g. `all exclude(:foo)`).
-
#
-
# @note You can also use this with compound matchers as well.
-
#
-
# @example
-
# expect([1, 3, 5]).to all( be_odd.and be_an(Integer) )
-
1
def all(expected)
-
BuiltIn::All.new(expected)
-
end
-
-
# Given a `Regexp` or `String`, passes if `actual.match(pattern)`
-
# Given an arbitrary nested data structure (e.g. arrays and hashes),
-
# matches if `expected === actual` || `actual == expected` for each
-
# pair of elements.
-
#
-
# @example
-
#
-
# expect(email).to match(/^([^\s]+)((?:[-a-z0-9]+\.)+[a-z]{2,})$/i)
-
# expect(email).to match("@example.com")
-
#
-
# @example
-
#
-
# hash = {
-
# :a => {
-
# :b => ["foo", 5],
-
# :c => { :d => 2.05 }
-
# }
-
# }
-
#
-
# expect(hash).to match(
-
# :a => {
-
# :b => a_collection_containing_exactly(
-
# a_string_starting_with("f"),
-
# an_instance_of(Fixnum)
-
# ),
-
# :c => { :d => (a_value < 3) }
-
# }
-
# )
-
#
-
# @note The `match_regex` alias is deprecated and is not recommended for use.
-
# It was added in 2.12.1 to facilitate its use from within custom
-
# matchers (due to how the custom matcher DSL was evaluated in 2.x,
-
# `match` could not be used there), but is no longer needed in 3.x.
-
1
def match(expected)
-
BuiltIn::Match.new(expected)
-
end
-
1
alias_matcher :match_regex, :match
-
1
alias_matcher :an_object_matching, :match
-
1
alias_matcher :a_string_matching, :match
-
1
alias_matcher :matching, :match
-
-
# An alternate form of `contain_exactly` that accepts
-
# the expected contents as a single array arg rather
-
# that splatted out as individual items.
-
#
-
# @example
-
#
-
# expect(results).to contain_exactly(1, 2)
-
# # is identical to:
-
# expect(results).to match_array([1, 2])
-
#
-
# @see #contain_exactly
-
1
def match_array(items)
-
contain_exactly(*items)
-
end
-
-
# With no arg, passes if the block outputs `to_stdout` or `to_stderr`.
-
# With a string, passes if the blocks outputs that specific string `to_stdout` or `to_stderr`.
-
# With a regexp or matcher, passes if the blocks outputs a string `to_stdout` or `to_stderr` that matches.
-
#
-
# @example
-
#
-
# expect { print 'foo' }.to output.to_stdout
-
# expect { print 'foo' }.to output('foo').to_stdout
-
# expect { print 'foo' }.to output(/foo/).to_stdout
-
#
-
# expect { do_something }.to_not output.to_stdout
-
#
-
# expect { warn('foo') }.to output.to_stderr
-
# expect { warn('foo') }.to output('foo').to_stderr
-
# expect { warn('foo') }.to output(/foo/).to_stderr
-
#
-
# expect { do_something }.to_not output.to_stderr
-
#
-
# @note This matcher works by temporarily replacing `$stdout` or `$stderr`,
-
# so it's not able to intercept stream output that explicitly uses `STDOUT`/`STDERR`
-
# or that uses a reference to `$stdout`/`$stderr` that was stored before the
-
# matcher is used.
-
1
def output(expected=nil)
-
BuiltIn::Output.new(expected)
-
end
-
1
alias_matcher :a_block_outputting, :output
-
-
# With no args, matches if any error is raised.
-
# With a named error, matches only if that specific error is raised.
-
# With a named error and messsage specified as a String, matches only if both match.
-
# With a named error and messsage specified as a Regexp, matches only if both match.
-
# Pass an optional block to perform extra verifications on the exception matched
-
#
-
# @example
-
#
-
# expect { do_something_risky }.to raise_error
-
# expect { do_something_risky }.to raise_error(PoorRiskDecisionError)
-
# expect { do_something_risky }.to raise_error(PoorRiskDecisionError) { |error| expect(error.data).to eq 42 }
-
# expect { do_something_risky }.to raise_error(PoorRiskDecisionError, "that was too risky")
-
# expect { do_something_risky }.to raise_error(PoorRiskDecisionError, /oo ri/)
-
#
-
# expect { do_something_risky }.not_to raise_error
-
1
def raise_error(error=Exception, message=nil, &block)
-
BuiltIn::RaiseError.new(error, message, &block)
-
end
-
1
alias_method :raise_exception, :raise_error
-
-
1
alias_matcher :a_block_raising, :raise_error do |desc|
-
desc.sub("raise", "a block raising")
-
end
-
-
1
alias_matcher :raising, :raise_error do |desc|
-
desc.sub("raise", "raising")
-
end
-
-
# Matches if the target object responds to all of the names
-
# provided. Names can be Strings or Symbols.
-
#
-
# @example
-
#
-
# expect("string").to respond_to(:length)
-
#
-
1
def respond_to(*names)
-
BuiltIn::RespondTo.new(*names)
-
end
-
1
alias_matcher :an_object_responding_to, :respond_to
-
1
alias_matcher :responding_to, :respond_to
-
-
# Passes if the submitted block returns true. Yields target to the
-
# block.
-
#
-
# Generally speaking, this should be thought of as a last resort when
-
# you can't find any other way to specify the behaviour you wish to
-
# specify.
-
#
-
# If you do find yourself in such a situation, you could always write
-
# a custom matcher, which would likely make your specs more expressive.
-
#
-
# @example
-
#
-
# expect(5).to satisfy { |n| n > 3 }
-
1
def satisfy(&block)
-
BuiltIn::Satisfy.new(&block)
-
end
-
1
alias_matcher :an_object_satisfying, :satisfy
-
1
alias_matcher :satisfying, :satisfy
-
-
# Matches if the actual value starts with the expected value(s). In the
-
# case of a string, matches against the first `expected.length` characters
-
# of the actual string. In the case of an array, matches against the first
-
# `expected.length` elements of the actual array.
-
#
-
# @example
-
#
-
# expect("this string").to start_with "this s"
-
# expect([0, 1, 2, 3, 4]).to start_with 0
-
# expect([0, 2, 3, 4, 4]).to start_with 0, 1
-
1
def start_with(*expected)
-
BuiltIn::StartWith.new(*expected)
-
end
-
1
alias_matcher :a_collection_starting_with, :start_with
-
1
alias_matcher :a_string_starting_with, :start_with
-
1
alias_matcher :starting_with, :start_with
-
-
# Given no argument, matches if a proc throws any Symbol.
-
#
-
# Given a Symbol, matches if the given proc throws the specified Symbol.
-
#
-
# Given a Symbol and an arg, matches if the given proc throws the
-
# specified Symbol with the specified arg.
-
#
-
# @example
-
#
-
# expect { do_something_risky }.to throw_symbol
-
# expect { do_something_risky }.to throw_symbol(:that_was_risky)
-
# expect { do_something_risky }.to throw_symbol(:that_was_risky, 'culprit')
-
#
-
# expect { do_something_risky }.not_to throw_symbol
-
# expect { do_something_risky }.not_to throw_symbol(:that_was_risky)
-
# expect { do_something_risky }.not_to throw_symbol(:that_was_risky, 'culprit')
-
1
def throw_symbol(expected_symbol=nil, expected_arg=nil)
-
BuiltIn::ThrowSymbol.new(expected_symbol, expected_arg)
-
end
-
-
1
alias_matcher :a_block_throwing, :throw_symbol do |desc|
-
desc.sub("throw", "a block throwing")
-
end
-
-
1
alias_matcher :throwing, :throw_symbol do |desc|
-
desc.sub("throw", "throwing")
-
end
-
-
# Passes if the method called in the expect block yields, regardless
-
# of whether or not arguments are yielded.
-
#
-
# @example
-
#
-
# expect { |b| 5.tap(&b) }.to yield_control
-
# expect { |b| "a".to_sym(&b) }.not_to yield_control
-
#
-
# @note Your expect block must accept a parameter and pass it on to
-
# the method-under-test as a block.
-
# @note This matcher is not designed for use with methods that yield
-
# multiple times.
-
1
def yield_control
-
BuiltIn::YieldControl.new
-
end
-
1
alias_matcher :a_block_yielding_control, :yield_control
-
1
alias_matcher :yielding_control, :yield_control
-
-
# Passes if the method called in the expect block yields with
-
# no arguments. Fails if it does not yield, or yields with arguments.
-
#
-
# @example
-
#
-
# expect { |b| User.transaction(&b) }.to yield_with_no_args
-
# expect { |b| 5.tap(&b) }.not_to yield_with_no_args # because it yields with `5`
-
# expect { |b| "a".to_sym(&b) }.not_to yield_with_no_args # because it does not yield
-
#
-
# @note Your expect block must accept a parameter and pass it on to
-
# the method-under-test as a block.
-
# @note This matcher is not designed for use with methods that yield
-
# multiple times.
-
1
def yield_with_no_args
-
BuiltIn::YieldWithNoArgs.new
-
end
-
1
alias_matcher :a_block_yielding_with_no_args, :yield_with_no_args
-
1
alias_matcher :yielding_with_no_args, :yield_with_no_args
-
-
# Given no arguments, matches if the method called in the expect
-
# block yields with arguments (regardless of what they are or how
-
# many there are).
-
#
-
# Given arguments, matches if the method called in the expect block
-
# yields with arguments that match the given arguments.
-
#
-
# Argument matching is done using `===` (the case match operator)
-
# and `==`. If the expected and actual arguments match with either
-
# operator, the matcher will pass.
-
#
-
# @example
-
#
-
# expect { |b| 5.tap(&b) }.to yield_with_args # because #tap yields an arg
-
# expect { |b| 5.tap(&b) }.to yield_with_args(5) # because 5 == 5
-
# expect { |b| 5.tap(&b) }.to yield_with_args(Fixnum) # because Fixnum === 5
-
# expect { |b| File.open("f.txt", &b) }.to yield_with_args(/txt/) # because /txt/ === "f.txt"
-
#
-
# expect { |b| User.transaction(&b) }.not_to yield_with_args # because it yields no args
-
# expect { |b| 5.tap(&b) }.not_to yield_with_args(1, 2, 3)
-
#
-
# @note Your expect block must accept a parameter and pass it on to
-
# the method-under-test as a block.
-
# @note This matcher is not designed for use with methods that yield
-
# multiple times.
-
1
def yield_with_args(*args)
-
BuiltIn::YieldWithArgs.new(*args)
-
end
-
1
alias_matcher :a_block_yielding_with_args, :yield_with_args
-
1
alias_matcher :yielding_with_args, :yield_with_args
-
-
# Designed for use with methods that repeatedly yield (such as
-
# iterators). Passes if the method called in the expect block yields
-
# multiple times with arguments matching those given.
-
#
-
# Argument matching is done using `===` (the case match operator)
-
# and `==`. If the expected and actual arguments match with either
-
# operator, the matcher will pass.
-
#
-
# @example
-
#
-
# expect { |b| [1, 2, 3].each(&b) }.to yield_successive_args(1, 2, 3)
-
# expect { |b| { :a => 1, :b => 2 }.each(&b) }.to yield_successive_args([:a, 1], [:b, 2])
-
# expect { |b| [1, 2, 3].each(&b) }.not_to yield_successive_args(1, 2)
-
#
-
# @note Your expect block must accept a parameter and pass it on to
-
# the method-under-test as a block.
-
1
def yield_successive_args(*args)
-
BuiltIn::YieldSuccessiveArgs.new(*args)
-
end
-
1
alias_matcher :a_block_yielding_successive_args, :yield_successive_args
-
1
alias_matcher :yielding_successive_args, :yield_successive_args
-
-
# Delegates to {RSpec::Expectations.configuration}.
-
# This is here because rspec-core's `expect_with` option
-
# looks for a `configuration` method on the mixin
-
# (`RSpec::Matchers`) to yield to a block.
-
# @return [RSpec::Expectations::Configuration] the configuration object
-
1
def self.configuration
-
Expectations.configuration
-
end
-
-
1
private
-
-
1
BE_PREDICATE_REGEX = /^(be_(?:an?_)?)(.*)/
-
1
HAS_REGEX = /^(?:have_)(.*)/
-
-
1
def method_missing(method, *args, &block)
-
case method.to_s
-
when BE_PREDICATE_REGEX
-
BuiltIn::BePredicate.new(method, *args, &block)
-
when HAS_REGEX
-
BuiltIn::Has.new(method, *args, &block)
-
else
-
super
-
end
-
end
-
-
# @api private
-
1
def self.is_a_matcher?(obj)
-
return true if ::RSpec::Matchers::BuiltIn::BaseMatcher === obj
-
return false if obj.respond_to?(:i_respond_to_everything_so_im_not_really_a_matcher)
-
return false unless obj.respond_to?(:matches?)
-
-
obj.respond_to?(:failure_message) ||
-
obj.respond_to?(:failure_message_for_should) # support legacy matchers
-
end
-
-
# @api private
-
1
def self.is_a_describable_matcher?(obj)
-
is_a_matcher?(obj) && obj.respond_to?(:description)
-
end
-
end
-
end
-
1
module RSpec
-
1
module Matchers
-
# Decorator that wraps a matcher and overrides `description`
-
# using the provided block in order to support an alias
-
# of a matcher. This is intended for use when composing
-
# matchers, so that you can use an expression like
-
# `include( a_value_within(0.1).of(3) )` rather than
-
# `include( be_within(0.1).of(3) )`, and have the corresponding
-
# description read naturally.
-
#
-
# @api private
-
1
class AliasedMatcher < MatcherDelegator
-
1
def initialize(base_matcher, description_block)
-
@description_block = description_block
-
super(base_matcher)
-
end
-
-
# Forward messages on to the wrapped matcher.
-
# Since many matchers provide a fluent interface
-
# (e.g. `a_value_within(0.1).of(3)`), we need to wrap
-
# the returned value if it responds to `description`,
-
# so that our override can be applied when it is eventually
-
# used.
-
1
def method_missing(*)
-
return_val = super
-
return return_val unless return_val.respond_to?(:description)
-
AliasedMatcher.new(return_val, @description_block)
-
end
-
-
# Provides the description of the aliased matcher. Aliased matchers
-
# are designed to behave identically to the original matcher except
-
# for this method. The description is different to reflect the aliased
-
# name.
-
#
-
# @api private
-
1
def description
-
@description_block.call(super)
-
end
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_matchers "built_in/base_matcher"
-
-
1
module RSpec
-
1
module Matchers
-
# Container module for all built-in matchers. The matcher classes are here
-
# (rather than directly under `RSpec::Matchers`) in order to prevent name
-
# collisions, since `RSpec::Matchers` gets included into the user's namespace.
-
#
-
# Autoloading is used to delay when the matcher classes get loaded, allowing
-
# rspec-matchers to boot faster, and avoiding loading matchers the user is
-
# not using.
-
1
module BuiltIn
-
1
autoload :BeAKindOf, 'rspec/matchers/built_in/be_kind_of'
-
1
autoload :BeAnInstanceOf, 'rspec/matchers/built_in/be_instance_of'
-
1
autoload :BeBetween, 'rspec/matchers/built_in/be_between'
-
1
autoload :Be, 'rspec/matchers/built_in/be'
-
1
autoload :BeComparedTo, 'rspec/matchers/built_in/be'
-
1
autoload :BeFalsey, 'rspec/matchers/built_in/be'
-
1
autoload :BeNil, 'rspec/matchers/built_in/be'
-
1
autoload :BePredicate, 'rspec/matchers/built_in/be'
-
1
autoload :BeTruthy, 'rspec/matchers/built_in/be'
-
1
autoload :BeWithin, 'rspec/matchers/built_in/be_within'
-
1
autoload :Change, 'rspec/matchers/built_in/change'
-
1
autoload :Compound, 'rspec/matchers/built_in/compound'
-
1
autoload :ContainExactly, 'rspec/matchers/built_in/contain_exactly'
-
1
autoload :Cover, 'rspec/matchers/built_in/cover'
-
1
autoload :EndWith, 'rspec/matchers/built_in/start_and_end_with'
-
1
autoload :Eq, 'rspec/matchers/built_in/eq'
-
1
autoload :Eql, 'rspec/matchers/built_in/eql'
-
1
autoload :Equal, 'rspec/matchers/built_in/equal'
-
1
autoload :Exist, 'rspec/matchers/built_in/exist'
-
1
autoload :Has, 'rspec/matchers/built_in/has'
-
1
autoload :Include, 'rspec/matchers/built_in/include'
-
1
autoload :All, 'rspec/matchers/built_in/all'
-
1
autoload :Match, 'rspec/matchers/built_in/match'
-
1
autoload :NegativeOperatorMatcher, 'rspec/matchers/built_in/operators'
-
1
autoload :OperatorMatcher, 'rspec/matchers/built_in/operators'
-
1
autoload :Output, 'rspec/matchers/built_in/output'
-
1
autoload :PositiveOperatorMatcher, 'rspec/matchers/built_in/operators'
-
1
autoload :RaiseError, 'rspec/matchers/built_in/raise_error'
-
1
autoload :RespondTo, 'rspec/matchers/built_in/respond_to'
-
1
autoload :Satisfy, 'rspec/matchers/built_in/satisfy'
-
1
autoload :StartWith, 'rspec/matchers/built_in/start_and_end_with'
-
1
autoload :ThrowSymbol, 'rspec/matchers/built_in/throw_symbol'
-
1
autoload :YieldControl, 'rspec/matchers/built_in/yield'
-
1
autoload :YieldSuccessiveArgs, 'rspec/matchers/built_in/yield'
-
1
autoload :YieldWithArgs, 'rspec/matchers/built_in/yield'
-
1
autoload :YieldWithNoArgs, 'rspec/matchers/built_in/yield'
-
end
-
end
-
end
-
1
module RSpec
-
1
module Matchers
-
1
module BuiltIn
-
# @api private
-
# Provides the implementation for `be_truthy`.
-
# Not intended to be instantiated directly.
-
1
class BeTruthy < BaseMatcher
-
# @api private
-
# @return [String]
-
1
def failure_message
-
"expected: truthy value\n got: #{actual.inspect}"
-
end
-
-
# @api private
-
# @return [String]
-
1
def failure_message_when_negated
-
"expected: falsey value\n got: #{actual.inspect}"
-
end
-
-
1
private
-
-
1
def match(_, actual)
-
!!actual
-
end
-
end
-
-
# @api private
-
# Provides the implementation for `be_falsey`.
-
# Not intended to be instantiated directly.
-
1
class BeFalsey < BaseMatcher
-
# @api private
-
# @return [String]
-
1
def failure_message
-
"expected: falsey value\n got: #{actual.inspect}"
-
end
-
-
# @api private
-
# @return [String]
-
1
def failure_message_when_negated
-
"expected: truthy value\n got: #{actual.inspect}"
-
end
-
-
1
private
-
-
1
def match(_, actual)
-
!actual
-
end
-
end
-
-
# @api private
-
# Provides the implementation for `be_nil`.
-
# Not intended to be instantiated directly.
-
1
class BeNil < BaseMatcher
-
# @api private
-
# @return [String]
-
1
def failure_message
-
"expected: nil\n got: #{actual.inspect}"
-
end
-
-
# @api private
-
# @return [String]
-
1
def failure_message_when_negated
-
"expected: not nil\n got: nil"
-
end
-
-
1
private
-
-
1
def match(_, actual)
-
actual.nil?
-
end
-
end
-
-
# @private
-
1
module BeHelpers
-
1
private
-
-
1
def args_to_s
-
@args.empty? ? "" : parenthesize(inspected_args.join(', '))
-
end
-
-
1
def parenthesize(string)
-
"(#{string})"
-
end
-
-
1
def inspected_args
-
@args.map { |a| a.inspect }
-
end
-
-
1
def expected_to_sentence
-
split_words(@expected)
-
end
-
-
1
def args_to_sentence
-
to_sentence(@args)
-
end
-
end
-
-
# @api private
-
# Provides the implementation for `be`.
-
# Not intended to be instantiated directly.
-
1
class Be < BaseMatcher
-
1
include BeHelpers
-
-
1
def initialize(*args)
-
@args = args
-
end
-
-
# @api private
-
# @return [String]
-
1
def failure_message
-
"expected #{@actual.inspect} to evaluate to true"
-
end
-
-
# @api private
-
# @return [String]
-
1
def failure_message_when_negated
-
"expected #{@actual.inspect} to evaluate to false"
-
end
-
-
1
[:==, :<, :<=, :>=, :>, :===, :=~].each do |operator|
-
7
define_method operator do |operand|
-
BeComparedTo.new(operand, operator)
-
end
-
end
-
-
1
private
-
-
1
def match(_, actual)
-
!!actual
-
end
-
end
-
-
# @api private
-
# Provides the implementation of `be <operator> value`.
-
# Not intended to be instantiated directly.
-
1
class BeComparedTo < BaseMatcher
-
1
include BeHelpers
-
-
1
def initialize(operand, operator)
-
@expected, @operator = operand, operator
-
@args = []
-
end
-
-
1
def matches?(actual)
-
@actual = actual
-
@actual.__send__ @operator, @expected
-
end
-
-
# @api private
-
# @return [String]
-
1
def failure_message
-
"expected: #{@operator} #{@expected.inspect}\n got: #{@operator.to_s.gsub(/./, ' ')} #{@actual.inspect}"
-
end
-
-
# @api private
-
# @return [String]
-
1
def failure_message_when_negated
-
message = "`expect(#{@actual.inspect}).not_to be #{@operator} #{@expected.inspect}`"
-
if [:<, :>, :<=, :>=].include?(@operator)
-
message + " not only FAILED, it is a bit confusing."
-
else
-
message
-
end
-
end
-
-
# @api private
-
# @return [String]
-
1
def description
-
"be #{@operator} #{expected_to_sentence}#{args_to_sentence}"
-
end
-
end
-
-
# @api private
-
# Provides the implementation of `be_<predicate>`.
-
# Not intended to be instantiated directly.
-
1
class BePredicate < BaseMatcher
-
1
include BeHelpers
-
-
1
def initialize(*args, &block)
-
@expected = parse_expected(args.shift)
-
@args = args
-
@block = block
-
end
-
-
1
def matches?(actual, &block)
-
@actual = actual
-
@block ||= block
-
predicate_accessible? && predicate_matches?
-
end
-
-
1
def does_not_match?(actual, &block)
-
@actual = actual
-
@block ||= block
-
predicate_accessible? && !predicate_matches?
-
end
-
-
# @api private
-
# @return [String]
-
1
def failure_message
-
failure_message_expecting(true)
-
end
-
-
# @api private
-
# @return [String]
-
1
def failure_message_when_negated
-
failure_message_expecting(false)
-
end
-
-
# @api private
-
# @return [String]
-
1
def description
-
"#{prefix_to_sentence}#{expected_to_sentence}#{args_to_sentence}"
-
end
-
-
1
private
-
-
1
def predicate_accessible?
-
!private_predicate? && predicate_exists?
-
end
-
-
# support 1.8.7, evaluate once at load time for performance
-
1
if String === methods.first
-
def private_predicate?
-
@actual.private_methods.include? predicate.to_s
-
end
-
else
-
1
def private_predicate?
-
@actual.private_methods.include? predicate
-
end
-
end
-
-
1
def predicate_exists?
-
actual.respond_to?(predicate) || actual.respond_to?(present_tense_predicate)
-
end
-
-
1
def predicate_matches?
-
method_name = actual.respond_to?(predicate) ? predicate : present_tense_predicate
-
@predicate_matches = actual.__send__(method_name, *@args, &@block)
-
end
-
-
1
def predicate
-
:"#{@expected}?"
-
end
-
-
1
def present_tense_predicate
-
:"#{@expected}s?"
-
end
-
-
1
def parse_expected(expected)
-
@prefix, expected = prefix_and_expected(expected)
-
expected
-
end
-
-
1
def prefix_and_expected(symbol)
-
Matchers::BE_PREDICATE_REGEX.match(symbol.to_s).captures.compact
-
end
-
-
1
def prefix_to_sentence
-
split_words(@prefix)
-
end
-
-
1
def failure_message_expecting(value)
-
validity_message ||
-
"expected `#{@actual.inspect}.#{predicate}#{args_to_s}` to return #{value}, got #{@predicate_matches.inspect}"
-
end
-
-
1
def validity_message
-
if private_predicate?
-
"expected #{@actual} to respond to `#{predicate}` but `#{predicate}` is a private method"
-
elsif !predicate_exists?
-
"expected #{@actual} to respond to `#{predicate}`"
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Matchers
-
1
module BuiltIn
-
# @api private
-
# Provides the implementation for `contain_exactly` and `match_array`.
-
# Not intended to be instantiated directly.
-
1
class ContainExactly < BaseMatcher
-
# @api private
-
# @return [String]
-
1
def failure_message
-
if Array === actual
-
message = "expected collection contained: #{safe_sort(surface_descriptions_in expected).inspect}\n"
-
message += "actual collection contained: #{safe_sort(actual).inspect}\n"
-
message += "the missing elements were: #{safe_sort(surface_descriptions_in missing_items).inspect}\n" unless missing_items.empty?
-
message += "the extra elements were: #{safe_sort(extra_items).inspect}\n" unless extra_items.empty?
-
message
-
else
-
"expected a collection that can be converted to an array with " \
-
"`#to_ary` or `#to_a`, but got #{actual.inspect}"
-
end
-
end
-
-
# @api private
-
# @return [String]
-
1
def failure_message_when_negated
-
"`contain_exactly` does not support negation"
-
end
-
-
# @api private
-
# @return [String]
-
1
def description
-
"contain exactly#{to_sentence(surface_descriptions_in expected)}"
-
end
-
-
1
private
-
-
1
def match(_expected, _actual)
-
return false unless convert_actual_to_an_array
-
match_when_sorted? || (extra_items.empty? && missing_items.empty?)
-
end
-
-
# This cannot always work (e.g. when dealing with unsortable items,
-
# or matchers as expected items), but it's practically free compared to
-
# the slowness of the full matching algorithm, and in common cases this
-
# works, so it's worth a try.
-
1
def match_when_sorted?
-
values_match?(safe_sort(expected), safe_sort(actual))
-
end
-
-
1
def convert_actual_to_an_array
-
if actual.respond_to?(:to_ary)
-
@actual = actual.to_ary
-
elsif enumerable?(actual) && actual.respond_to?(:to_a)
-
@actual = actual.to_a
-
else
-
return false
-
end
-
end
-
-
1
def safe_sort(array)
-
array.sort rescue array
-
end
-
-
1
def missing_items
-
@missing_items ||= best_solution.unmatched_expected_indexes.map do |index|
-
expected[index]
-
end
-
end
-
-
1
def extra_items
-
@extra_items ||= best_solution.unmatched_actual_indexes.map do |index|
-
actual[index]
-
end
-
end
-
-
1
def best_solution
-
@best_solution ||= pairings_maximizer.find_best_solution
-
end
-
-
1
def pairings_maximizer
-
@pairings_maximizer ||= begin
-
expected_matches = Hash[Array.new(expected.size) { |i| [i, []] }]
-
actual_matches = Hash[Array.new(actual.size) { |i| [i, []] }]
-
-
expected.each_with_index do |e, ei|
-
actual.each_with_index do |a, ai|
-
next unless values_match?(e, a)
-
-
expected_matches[ei] << ai
-
actual_matches[ai] << ei
-
end
-
end
-
-
PairingsMaximizer.new(expected_matches, actual_matches)
-
end
-
end
-
-
# Once we started supporting composing matchers, the algorithm for this matcher got
-
# much more complicated. Consider this expression:
-
#
-
# expect(["fool", "food"]).to contain_exactly(/foo/, /fool/)
-
#
-
# This should pass (because we can pair /fool/ with "fool" and /foo/ with "food"), but
-
# the original algorithm used by this matcher would pair the first elements it could
-
# (/foo/ with "fool"), which would leave /fool/ and "food" unmatched. When we have
-
# an expected element which is a matcher that matches a superset of actual items
-
# compared to another expected element matcher, we need to consider every possible pairing.
-
#
-
# This class is designed to maximize the number of actual/expected pairings -- or,
-
# conversely, to minimize the number of unpaired items. It's essentially a brute
-
# force solution, but with a few heuristics applied to reduce the size of the
-
# problem space:
-
#
-
# * Any items which match none of the items in the other list are immediately
-
# placed into the `unmatched_expected_indexes` or `unmatched_actual_indexes` array.
-
# The extra items and missing items in the matcher failure message are derived
-
# from these arrays.
-
# * Any items which reciprocally match only each other are paired up and not
-
# considered further.
-
#
-
# What's left is only the items which match multiple items from the other list
-
# (or vice versa). From here, it performs a brute-force depth-first search,
-
# looking for a solution which pairs all elements in both lists, or, barring that,
-
# that produces the fewest unmatched items.
-
#
-
# @private
-
1
class PairingsMaximizer
-
1
Solution = Struct.new(:unmatched_expected_indexes, :unmatched_actual_indexes,
-
:indeterminate_expected_indexes, :indeterminate_actual_indexes) do
-
1
def worse_than?(other)
-
unmatched_item_count > other.unmatched_item_count
-
end
-
-
1
def candidate?
-
indeterminate_expected_indexes.empty? &&
-
indeterminate_actual_indexes.empty?
-
end
-
-
1
def ideal?
-
candidate? && (
-
unmatched_expected_indexes.empty? ||
-
unmatched_actual_indexes.empty?
-
)
-
end
-
-
1
def unmatched_item_count
-
unmatched_expected_indexes.count + unmatched_actual_indexes.count
-
end
-
-
1
def +(derived_candidate_solution)
-
self.class.new(
-
unmatched_expected_indexes + derived_candidate_solution.unmatched_expected_indexes,
-
unmatched_actual_indexes + derived_candidate_solution.unmatched_actual_indexes,
-
# Ignore the indeterminate indexes: by the time we get here,
-
# we've dealt with all indeterminates.
-
[], []
-
)
-
end
-
end
-
-
1
attr_reader :expected_to_actual_matched_indexes, :actual_to_expected_matched_indexes, :solution
-
-
1
def initialize(expected_to_actual_matched_indexes, actual_to_expected_matched_indexes)
-
@expected_to_actual_matched_indexes = expected_to_actual_matched_indexes
-
@actual_to_expected_matched_indexes = actual_to_expected_matched_indexes
-
-
unmatched_expected_indexes, indeterminate_expected_indexes =
-
categorize_indexes(expected_to_actual_matched_indexes, actual_to_expected_matched_indexes)
-
-
unmatched_actual_indexes, indeterminate_actual_indexes =
-
categorize_indexes(actual_to_expected_matched_indexes, expected_to_actual_matched_indexes)
-
-
@solution = Solution.new(unmatched_expected_indexes, unmatched_actual_indexes,
-
indeterminate_expected_indexes, indeterminate_actual_indexes)
-
end
-
-
1
def find_best_solution
-
return solution if solution.candidate?
-
best_solution_so_far = NullSolution
-
-
expected_index = solution.indeterminate_expected_indexes.first
-
actuals = expected_to_actual_matched_indexes[expected_index]
-
-
actuals.each do |actual_index|
-
solution = best_solution_for_pairing(expected_index, actual_index)
-
return solution if solution.ideal?
-
best_solution_so_far = solution if best_solution_so_far.worse_than?(solution)
-
end
-
-
best_solution_so_far
-
end
-
-
1
private
-
-
# @private
-
# Starting solution that is worse than any other real solution.
-
1
NullSolution = Class.new do
-
1
def self.worse_than?(_other)
-
true
-
end
-
end
-
-
1
def categorize_indexes(indexes_to_categorize, other_indexes)
-
unmatched = []
-
indeterminate = []
-
-
indexes_to_categorize.each_pair do |index, matches|
-
if matches.empty?
-
unmatched << index
-
elsif !reciprocal_single_match?(matches, index, other_indexes)
-
indeterminate << index
-
end
-
end
-
-
return unmatched, indeterminate
-
end
-
-
1
def reciprocal_single_match?(matches, index, other_list)
-
return false unless matches.one?
-
other_list[matches.first] == [index]
-
end
-
-
1
def best_solution_for_pairing(expected_index, actual_index)
-
modified_expecteds = apply_pairing_to(
-
solution.indeterminate_expected_indexes,
-
expected_to_actual_matched_indexes, actual_index)
-
-
modified_expecteds.delete(expected_index)
-
-
modified_actuals = apply_pairing_to(
-
solution.indeterminate_actual_indexes,
-
actual_to_expected_matched_indexes, expected_index)
-
-
modified_actuals.delete(actual_index)
-
-
solution + self.class.new(modified_expecteds, modified_actuals).find_best_solution
-
end
-
-
1
def apply_pairing_to(indeterminates, original_matches, other_list_index)
-
indeterminates.inject({}) do |accum, index|
-
accum[index] = original_matches[index] - [other_list_index]
-
accum
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'rspec/support'
-
-
1
module RSpec
-
1
module Matchers
-
1
module BuiltIn
-
# @api private
-
# Provides the implementation for operator matchers.
-
# Not intended to be instantiated directly.
-
# Only available for use with `should`.
-
1
class OperatorMatcher
-
1
class << self
-
# @private
-
1
def registry
-
4
@registry ||= {}
-
end
-
-
# @private
-
1
def register(klass, operator, matcher)
-
2
registry[klass] ||= {}
-
2
registry[klass][operator] = matcher
-
end
-
-
# @private
-
1
def unregister(klass, operator)
-
registry[klass] && registry[klass].delete(operator)
-
end
-
-
# @private
-
1
def get(klass, operator)
-
klass.ancestors.each do |ancestor|
-
matcher = registry[ancestor] && registry[ancestor][operator]
-
return matcher if matcher
-
end
-
-
nil
-
end
-
end
-
-
1
register Enumerable, '=~', BuiltIn::ContainExactly
-
-
1
def initialize(actual)
-
@actual = actual
-
end
-
-
# @private
-
1
def self.use_custom_matcher_or_delegate(operator)
-
7
define_method(operator) do |expected|
-
if !has_non_generic_implementation_of?(operator) && (matcher = OperatorMatcher.get(@actual.class, operator))
-
@actual.__send__(::RSpec::Matchers.last_expectation_handler.should_method, matcher.new(expected))
-
else
-
eval_match(@actual, operator, expected)
-
end
-
end
-
-
7
negative_operator = operator.sub(/^=/, '!')
-
7
if negative_operator != operator && respond_to?(negative_operator)
-
2
define_method(negative_operator) do |_expected|
-
opposite_should = ::RSpec::Matchers.last_expectation_handler.opposite_should_method
-
raise "RSpec does not support `#{::RSpec::Matchers.last_expectation_handler.should_method} #{negative_operator} expected`. " \
-
"Use `#{opposite_should} #{operator} expected` instead."
-
end
-
end
-
end
-
-
1
['==', '===', '=~', '>', '>=', '<', '<='].each do |operator|
-
7
use_custom_matcher_or_delegate operator
-
end
-
-
# @private
-
1
def fail_with_message(message)
-
RSpec::Expectations.fail_with(message, @expected, @actual)
-
end
-
-
# @api private
-
# @return [String]
-
1
def description
-
"#{@operator} #{@expected.inspect}"
-
end
-
-
1
private
-
-
1
def has_non_generic_implementation_of?(op)
-
Support.method_handle_for(@actual, op).owner != ::Kernel
-
rescue NameError
-
false
-
end
-
-
1
def eval_match(actual, operator, expected)
-
::RSpec::Matchers.last_matcher = self
-
@operator, @expected = operator, expected
-
__delegate_operator(actual, operator, expected)
-
end
-
end
-
-
# @private
-
# Handles operator matcher for `should`.
-
1
class PositiveOperatorMatcher < OperatorMatcher
-
1
def __delegate_operator(actual, operator, expected)
-
if actual.__send__(operator, expected)
-
true
-
elsif ['==', '===', '=~'].include?(operator)
-
fail_with_message("expected: #{expected.inspect}\n got: #{actual.inspect} (using #{operator})")
-
else
-
fail_with_message("expected: #{operator} #{expected.inspect}\n got: #{operator.gsub(/./, ' ')} #{actual.inspect}")
-
end
-
end
-
end
-
-
# @private
-
# Handles operator matcher for `should_not`.
-
1
class NegativeOperatorMatcher < OperatorMatcher
-
1
def __delegate_operator(actual, operator, expected)
-
return false unless actual.__send__(operator, expected)
-
fail_with_message("expected not: #{operator} #{expected.inspect}\n got: #{operator.gsub(/./, ' ')} #{actual.inspect}")
-
end
-
end
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_support "fuzzy_matcher"
-
-
1
module RSpec
-
1
module Matchers
-
# Mixin designed to support the composable matcher features
-
# of RSpec 3+. Mix it into your custom matcher classes to
-
# allow them to be used in a composable fashion.
-
#
-
# @api public
-
1
module Composable
-
# Creates a compound `and` expectation. The matcher will
-
# only pass if both sub-matchers pass.
-
# This can be chained together to form an arbitrarily long
-
# chain of matchers.
-
#
-
# @example
-
# expect(alphabet).to start_with("a").and end_with("z")
-
# expect(alphabet).to start_with("a") & end_with("z")
-
#
-
# @note The negative form (`expect(...).not_to matcher.and other`)
-
# is not supported at this time.
-
1
def and(matcher)
-
BuiltIn::Compound::And.new self, matcher
-
end
-
1
alias & and
-
-
# Creates a compound `or` expectation. The matcher will
-
# pass if either sub-matcher passes.
-
# This can be chained together to form an arbitrarily long
-
# chain of matchers.
-
#
-
# @example
-
# expect(stoplight.color).to eq("red").or eq("green").or eq("yellow")
-
# expect(stoplight.color).to eq("red") | eq("green") | eq("yellow")
-
#
-
# @note The negative form (`expect(...).not_to matcher.or other`)
-
# is not supported at this time.
-
1
def or(matcher)
-
BuiltIn::Compound::Or.new self, matcher
-
end
-
1
alias | or
-
-
# Delegates to `#matches?`. Allows matchers to be used in composable
-
# fashion and also supports using matchers in case statements.
-
1
def ===(value)
-
matches?(value)
-
end
-
-
1
private
-
-
# This provides a generic way to fuzzy-match an expected value against
-
# an actual value. It understands nested data structures (e.g. hashes
-
# and arrays) and is able to match against a matcher being used as
-
# the expected value or within the expected value at any level of
-
# nesting.
-
#
-
# Within a custom matcher you are encouraged to use this whenever your
-
# matcher needs to match two values, unless it needs more precise semantics.
-
# For example, the `eq` matcher _does not_ use this as it is meant to
-
# use `==` (and only `==`) for matching.
-
#
-
# @param expected [Object] what is expected
-
# @param actual [Object] the actual value
-
#
-
# @!visibility public
-
1
def values_match?(expected, actual)
-
expected = with_matchers_cloned(expected)
-
Support::FuzzyMatcher.values_match?(expected, actual)
-
end
-
-
# Returns the description of the given object in a way that is
-
# aware of composed matchers. If the object is a matcher with
-
# a `description` method, returns the description; otherwise
-
# returns `object.inspect`.
-
#
-
# You are encouraged to use this in your custom matcher's
-
# `description`, `failure_message` or
-
# `failure_message_when_negated` implementation if you are
-
# supporting matcher arguments.
-
#
-
# @!visibility public
-
1
def description_of(object)
-
return object.description if Matchers.is_a_describable_matcher?(object)
-
object.inspect
-
end
-
-
# Transforms the given data structue (typically a hash or array)
-
# into a new data structure that, when `#inspect` is called on it,
-
# will provide descriptions of any contained matchers rather than
-
# the normal `#inspect` output.
-
#
-
# You are encouraged to use this in your custom matcher's
-
# `description`, `failure_message` or
-
# `failure_message_when_negated` implementation if you are
-
# supporting any arguments which may be a data structure
-
# containing matchers.
-
#
-
# @!visibility public
-
1
def surface_descriptions_in(item)
-
if Matchers.is_a_describable_matcher?(item)
-
DescribableItem.new(item)
-
elsif Hash === item
-
Hash[surface_descriptions_in(item.to_a)]
-
elsif Struct === item
-
item.inspect
-
elsif enumerable?(item)
-
begin
-
item.map { |subitem| surface_descriptions_in(subitem) }
-
rescue IOError # STDOUT is enumerable but `map` raises an error
-
item.inspect
-
end
-
else
-
item
-
end
-
end
-
-
# @private
-
# Historically, a single matcher instance was only checked
-
# against a single value. Given that the matcher was only
-
# used once, it's been common to memoize some intermediate
-
# calculation that is derived from the `actual` value in
-
# order to reuse that intermediate result in the failure
-
# message.
-
#
-
# This can cause a problem when using such a matcher as an
-
# argument to another matcher in a composed matcher expression,
-
# since the matcher instance may be checked against multiple
-
# values and produce invalid results due to the memoization.
-
#
-
# To deal with this, we clone any matchers in `expected` via
-
# this method when using `values_match?`, so that any memoization
-
# does not "leak" between checks.
-
1
def with_matchers_cloned(object)
-
if Matchers.is_a_matcher?(object)
-
object.clone
-
elsif Hash === object
-
Hash[with_matchers_cloned(object.to_a)]
-
elsif Struct === object
-
object
-
elsif enumerable?(object)
-
begin
-
object.map { |subobject| with_matchers_cloned(subobject) }
-
rescue IOError # STDOUT is enumerable but `map` raises an error
-
object
-
end
-
else
-
object
-
end
-
end
-
-
1
if String.ancestors.include?(Enumerable) # 1.8.7
-
# Strings are not enumerable on 1.9, and on 1.8 they are an infinitely
-
# nested enumerable: since ruby lacks a character class, it yields
-
# 1-character strings, which are themselves enumerable, composed of a
-
# a single 1-character string, which is an enumerable, etc.
-
#
-
# @api private
-
def enumerable?(item)
-
return false if String === item
-
Enumerable === item
-
end
-
else
-
# @api private
-
1
def enumerable?(item)
-
Enumerable === item
-
end
-
end
-
1
module_function :surface_descriptions_in, :enumerable?
-
-
# Wraps an item in order to surface its `description` via `inspect`.
-
# @api private
-
1
DescribableItem = Struct.new(:item) do
-
1
def inspect
-
"(#{item.description})"
-
end
-
-
1
def pretty_print(pp)
-
pp.text "(#{item.description})"
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Matchers
-
# Defines the custom matcher DSL.
-
1
module DSL
-
# Defines a custom matcher.
-
# @see RSpec::Matchers
-
1
def define(name, &declarations)
-
define_method name do |*expected|
-
RSpec::Matchers::DSL::Matcher.new(name, declarations, self, *expected)
-
end
-
end
-
1
alias_method :matcher, :define
-
-
2
RSpec.configure { |c| c.extend self } if RSpec.respond_to?(:configure)
-
-
# Contains the methods that are available from within the
-
# `RSpec::Matchers.define` DSL for creating custom matchers.
-
1
module Macros
-
# Stores the block that is used to determine whether this matcher passes
-
# or fails. The block should return a boolean value. When the matcher is
-
# passed to `expect(...).to` and the block returns `true`, then the expectation
-
# passes. Similarly, when the matcher is passed to `expect(...).not_to` and the
-
# block returns `false`, then the expectation passes.
-
#
-
# @example
-
#
-
# RSpec::Matchers.define :be_even do
-
# match do |actual|
-
# actual.even?
-
# end
-
# end
-
#
-
# expect(4).to be_even # passes
-
# expect(3).not_to be_even # passes
-
# expect(3).to be_even # fails
-
# expect(4).not_to be_even # fails
-
#
-
# @yield [Object] actual the actual value (i.e. the value wrapped by `expect`)
-
1
def match(&match_block)
-
define_user_override(:matches?, match_block) do |actual|
-
begin
-
@actual = actual
-
super(*actual_arg_for(match_block))
-
rescue RSpec::Expectations::ExpectationNotMetError
-
false
-
end
-
end
-
end
-
-
# Use this to define the block for a negative expectation (`expect(...).not_to`)
-
# when the positive and negative forms require different handling. This
-
# is rarely necessary, but can be helpful, for example, when specifying
-
# asynchronous processes that require different timeouts.
-
#
-
# @yield [Object] actual the actual value (i.e. the value wrapped by `expect`)
-
1
def match_when_negated(&match_block)
-
define_user_override(:does_not_match?, match_block) do |actual|
-
@actual = actual
-
super(*actual_arg_for(match_block))
-
end
-
end
-
-
# Use this instead of `match` when the block will raise an exception
-
# rather than returning false to indicate a failure.
-
#
-
# @example
-
#
-
# RSpec::Matchers.define :accept_as_valid do |candidate_address|
-
# match_unless_raises ValidationException do |validator|
-
# validator.validate(candidate_address)
-
# end
-
# end
-
#
-
# expect(email_validator).to accept_as_valid("person@company.com")
-
#
-
# @yield [Object] actual the actual object (i.e. the value wrapped by `expect`)
-
1
def match_unless_raises(expected_exception=Exception, &match_block)
-
define_user_override(:matches?, match_block) do |actual|
-
@actual = actual
-
begin
-
super(*actual_arg_for(match_block))
-
rescue expected_exception => @rescued_exception
-
false
-
else
-
true
-
end
-
end
-
end
-
-
# Customizes the failure messsage to use when this matcher is
-
# asked to positively match. Only use this when the message
-
# generated by default doesn't suit your needs.
-
#
-
# @example
-
#
-
# RSpec::Matchers.define :have_strength do |expected|
-
# match { your_match_logic }
-
#
-
# failure_message do |actual|
-
# "Expected strength of #{expected}, but had #{actual.strength}"
-
# end
-
# end
-
#
-
# @yield [Object] actual the actual object (i.e. the value wrapped by `expect`)
-
1
def failure_message(&definition)
-
define_user_override(__method__, definition)
-
end
-
-
# Customize the failure messsage to use when this matcher is asked
-
# to negatively match. Only use this when the message generated by
-
# default doesn't suit your needs.
-
#
-
# @example
-
#
-
# RSpec::Matchers.define :have_strength do |expected|
-
# match { your_match_logic }
-
#
-
# failure_message_when_negated do |actual|
-
# "Expected not to have strength of #{expected}, but did"
-
# end
-
# end
-
#
-
# @yield [Object] actual the actual object (i.e. the value wrapped by `expect`)
-
1
def failure_message_when_negated(&definition)
-
define_user_override(__method__, definition)
-
end
-
-
# Customize the description to use for one-liners. Only use this when
-
# the description generated by default doesn't suit your needs.
-
#
-
# @example
-
#
-
# RSpec::Matchers.define :qualify_for do |expected|
-
# match { your_match_logic }
-
#
-
# description do
-
# "qualify for #{expected}"
-
# end
-
# end
-
#
-
# @yield [Object] actual the actual object (i.e. the value wrapped by `expect`)
-
1
def description(&definition)
-
define_user_override(__method__, definition)
-
end
-
-
# Tells the matcher to diff the actual and expected values in the failure
-
# message.
-
1
def diffable
-
define_method(:diffable?) { true }
-
end
-
-
# Declares that the matcher can be used in a block expectation.
-
# Users will not be able to use your matcher in a block
-
# expectation without declaring this.
-
# (e.g. `expect { do_something }.to matcher`).
-
1
def supports_block_expectations
-
define_method(:supports_block_expectations?) { true }
-
end
-
-
# Convenience for defining methods on this matcher to create a fluent
-
# interface. The trick about fluent interfaces is that each method must
-
# return self in order to chain methods together. `chain` handles that
-
# for you.
-
#
-
# @example
-
#
-
# RSpec::Matchers.define :have_errors_on do |key|
-
# chain :with do |message|
-
# @message = message
-
# end
-
#
-
# match do |actual|
-
# actual.errors[key] == @message
-
# end
-
# end
-
#
-
# expect(minor).to have_errors_on(:age).with("Not old enough to participate")
-
1
def chain(name, &definition)
-
define_user_override(name, definition) do |*args, &block|
-
super(*args, &block)
-
self
-
end
-
end
-
-
1
private
-
-
# Does the following:
-
#
-
# - Defines the named method usign a user-provided block
-
# in @user_method_defs, which is included as an ancestor
-
# in the singleton class in which we eval the `define` block.
-
# - Defines an overriden definition for the same method
-
# usign the provided `our_def` block.
-
# - Provides a default `our_def` block for the common case
-
# of needing to call the user's definition with `@actual`
-
# as an arg, but only if their block's arity can handle it.
-
#
-
# This compiles the user block into an actual method, allowing
-
# them to use normal method constructs like `return`
-
# (e.g. for a early guard statement), while allowing us to define
-
# an override that can provide the wrapped handling
-
# (e.g. assigning `@actual`, rescueing errors, etc) and
-
# can `super` to the user's definition.
-
1
def define_user_override(method_name, user_def, &our_def)
-
@user_method_defs.__send__(:define_method, method_name, &user_def)
-
our_def ||= lambda { super(*actual_arg_for(user_def)) }
-
define_method(method_name, &our_def)
-
end
-
-
# Defines deprecated macro methods from RSpec 2 for backwards compatibility.
-
# @deprecated Use the methods from {Macros} instead.
-
1
module Deprecated
-
# @deprecated Use {Macros#match} instead.
-
1
def match_for_should(&definition)
-
RSpec.deprecate("`match_for_should`", :replacement => "`match`")
-
match(&definition)
-
end
-
-
# @deprecated Use {Macros#match_when_negated} instead.
-
1
def match_for_should_not(&definition)
-
RSpec.deprecate("`match_for_should_not`", :replacement => "`match_when_negated`")
-
match_when_negated(&definition)
-
end
-
-
# @deprecated Use {Macros#failure_message} instead.
-
1
def failure_message_for_should(&definition)
-
RSpec.deprecate("`failure_message_for_should`", :replacement => "`failure_message`")
-
failure_message(&definition)
-
end
-
-
# @deprecated Use {Macros#failure_message_when_negated} instead.
-
1
def failure_message_for_should_not(&definition)
-
RSpec.deprecate("`failure_message_for_should_not`", :replacement => "`failure_message_when_negated`")
-
failure_message_when_negated(&definition)
-
end
-
end
-
end
-
-
# Defines default implementations of the matcher
-
# protocol methods for custom matchers. You can
-
# override any of these using the {RSpec::Matchers::DSL::Macros Macros} methods
-
# from within an `RSpec::Matchers.define` block.
-
1
module DefaultImplementations
-
# @api private
-
# Used internally by objects returns by `should` and `should_not`.
-
1
def diffable?
-
false
-
end
-
-
# The default description.
-
1
def description
-
"#{name_to_sentence}#{to_sentence expected}"
-
end
-
-
# The default failure message for positive expectations.
-
1
def failure_message
-
"expected #{actual.inspect} to #{name_to_sentence}#{to_sentence expected}"
-
end
-
-
# The default failure message for negative expectations.
-
1
def failure_message_when_negated
-
"expected #{actual.inspect} not to #{name_to_sentence}#{to_sentence expected}"
-
end
-
-
# Matchers do not support block expectations by default. You
-
# must opt-in.
-
1
def supports_block_expectations?
-
false
-
end
-
end
-
-
# The class used for custom matchers. The block passed to
-
# `RSpec::Matchers.define` will be evaluated in the context
-
# of the singleton class of an instance, and will have the
-
# {RSpec::Matchers::DSL::Macros Macros} methods available.
-
1
class Matcher
-
# Provides default implementations for the matcher protocol methods.
-
1
include DefaultImplementations
-
-
# Allows expectation expressions to be used in the match block.
-
1
include RSpec::Matchers
-
-
# Converts matcher name and expected args to an English expresion.
-
1
include RSpec::Matchers::Pretty
-
-
# Supports the matcher composability features of RSpec 3+.
-
1
include Composable
-
-
# Makes the macro methods available to an `RSpec::Matchers.define` block.
-
1
extend Macros
-
1
extend Macros::Deprecated
-
-
# Exposes the value being matched against -- generally the object
-
# object wrapped by `expect`.
-
1
attr_reader :actual
-
-
# Exposes the exception raised during the matching by `match_unless_raises`.
-
# Could be useful to extract details for a failure message.
-
1
attr_reader :rescued_exception
-
-
# @api private
-
1
def initialize(name, declarations, matcher_execution_context, *expected)
-
@name = name
-
@actual = nil
-
@expected_as_array = expected
-
@matcher_execution_context = matcher_execution_context
-
-
class << self
-
# See `Macros#define_user_override` above, for an explanation.
-
include(@user_method_defs = Module.new)
-
self
-
end.class_exec(*expected, &declarations)
-
end
-
-
# Provides the expected value. This will return an array if
-
# multiple arguments were passed to the matcher; otherwise it
-
# will return a single value.
-
# @see #expected_as_array
-
1
def expected
-
if expected_as_array.size == 1
-
expected_as_array[0]
-
else
-
expected_as_array
-
end
-
end
-
-
# Returns the expected value as an an array. This exists primarily
-
# to aid in upgrading from RSpec 2.x, since in RSpec 2, `expected`
-
# always returned an array.
-
# @see #expected
-
1
attr_reader :expected_as_array
-
-
# Adds the name (rather than a cryptic hex number)
-
# so we can identify an instance of
-
# the matcher in error messages (e.g. for `NoMethodError`)
-
1
def inspect
-
"#<#{self.class.name} #{name}>"
-
end
-
-
1
if RUBY_VERSION.to_f >= 1.9
-
# Indicates that this matcher responds to messages
-
# from the `@matcher_execution_context` as well.
-
# Also, supports getting a method object for such methods.
-
1
def respond_to_missing?(method, include_private=false)
-
super || @matcher_execution_context.respond_to?(method, include_private)
-
end
-
else # for 1.8.7
-
# Indicates that this matcher responds to messages
-
# from the `@matcher_execution_context` as well.
-
def respond_to?(method, include_private=false)
-
super || @matcher_execution_context.respond_to?(method, include_private)
-
end
-
end
-
-
1
private
-
-
1
def actual_arg_for(block)
-
block.arity.zero? ? [] : [@actual]
-
end
-
-
# Takes care of forwarding unhandled messages to the
-
# `@matcher_execution_context` (typically the current
-
# running `RSpec::Core::Example`). This is needed by
-
# rspec-rails so that it can define matchers that wrap
-
# Rails' test helper methods, but it's also a useful
-
# feature in its own right.
-
1
def method_missing(method, *args, &block)
-
if @matcher_execution_context.respond_to?(method)
-
@matcher_execution_context.__send__ method, *args, &block
-
else
-
super(method, *args, &block)
-
end
-
end
-
end
-
end
-
end
-
end
-
-
1
RSpec::Matchers.extend RSpec::Matchers::DSL
-
1
module RSpec
-
1
module Matchers
-
1
class << self
-
# @private
-
1
attr_accessor :last_matcher, :last_expectation_handler
-
end
-
-
# @api private
-
# Used by rspec-core to clear the state used to generate
-
# descriptions after an example.
-
1
def self.clear_generated_description
-
self.last_matcher = nil
-
self.last_expectation_handler = nil
-
end
-
-
# @api private
-
# Generates an an example description based on the last expectation.
-
# Used by rspec-core's one-liner syntax.
-
1
def self.generated_description
-
return nil if last_expectation_handler.nil?
-
"#{last_expectation_handler.verb} #{last_description}"
-
end
-
-
1
private
-
-
1
def self.last_description
-
last_matcher.respond_to?(:description) ? last_matcher.description : <<-MESSAGE
-
When you call a matcher in an example without a String, like this:
-
-
specify { expect(object).to matcher }
-
-
or this:
-
-
it { is_expected.to matcher }
-
-
RSpec expects the matcher to have a #description method. You should either
-
add a String to the example this matcher is being used in, or give it a
-
description method. Then you won't have to suffer this lengthy warning again.
-
MESSAGE
-
end
-
end
-
end
-
1
module RSpec
-
1
module Matchers
-
# Provides the necessary plumbing to wrap a matcher with a decorator.
-
# @private
-
1
class MatcherDelegator
-
1
attr_reader :base_matcher
-
-
1
def initialize(base_matcher)
-
@base_matcher = base_matcher
-
end
-
-
1
def method_missing(*args, &block)
-
base_matcher.__send__(*args, &block)
-
end
-
-
1
if ::RUBY_VERSION.to_f > 1.8
-
1
def respond_to_missing?(name, include_all=false)
-
super || base_matcher.respond_to?(name, include_all)
-
end
-
else
-
def respond_to?(name, include_all=false)
-
super || base_matcher.respond_to?(name, include_all)
-
end
-
end
-
-
1
def initialize_copy(other)
-
@base_matcher = @base_matcher.clone
-
super
-
end
-
-
# So `===` is delegated via `method_missing`.
-
1
undef ===
-
1
undef ==
-
end
-
end
-
end
-
1
module RSpec
-
1
module Matchers
-
# @api private
-
# Contains logic to facilitate converting ruby symbols and
-
# objects to english phrases.
-
1
module Pretty
-
# @api private
-
# Converts a symbol into an english expression.
-
1
def split_words(sym)
-
sym.to_s.gsub(/_/, ' ')
-
end
-
1
module_function :split_words
-
-
# @api private
-
# Converts a collection of objects into an english expression.
-
1
def to_sentence(words)
-
return " #{words.inspect}" if !words || Struct === words
-
words = Array(words).map { |w| to_word(w) }
-
case words.length
-
when 0
-
""
-
when 1
-
" #{words[0]}"
-
when 2
-
" #{words[0]} and #{words[1]}"
-
else
-
" #{words[0...-1].join(', ')}, and #{words[-1]}"
-
end
-
end
-
-
# @api private
-
# Converts the given item to string suitable for use in a list expression.
-
1
def to_word(item)
-
is_matcher_with_description?(item) ? item.description : item.inspect
-
end
-
-
# @private
-
# Provides an English expression for the matcher name.
-
1
def name_to_sentence
-
split_words(name)
-
end
-
-
# @api private
-
# Provides a name for the matcher.
-
1
def name
-
defined?(@name) ? @name : underscore(self.class.name.split("::").last)
-
end
-
-
# @private
-
# Borrowed from ActiveSupport
-
1
def underscore(camel_cased_word)
-
word = camel_cased_word.to_s.dup
-
word.gsub!(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
-
word.gsub!(/([a-z\d])([A-Z])/, '\1_\2')
-
word.tr!("-", "_")
-
word.downcase!
-
word
-
end
-
-
1
private
-
-
1
def is_matcher_with_description?(object)
-
RSpec::Matchers.is_a_matcher?(object) && object.respond_to?(:description)
-
end
-
-
# `{ :a => 5, :b => 2 }.inspect` produces:
-
# {:a=>5, :b=>2}
-
# ...but it looks much better as:
-
# {:a => 5, :b => 2}
-
#
-
# This is idempotent and safe to run on a string multiple times.
-
1
def improve_hash_formatting(inspect_string)
-
inspect_string.gsub(/(\S)=>(\S)/, '\1 => \2')
-
end
-
end
-
end
-
end
-
# Namespace for all core RSpec projects.
-
1
module RSpec
-
# Namespace for rspec-rails code.
-
1
module Rails
-
# Railtie to hook into Rails.
-
1
class Railtie < ::Rails::Railtie
-
# Rails-3.0.1 requires config.app_generators instead of 3.0.0's config.generators
-
1
generators = config.respond_to?(:app_generators) ? config.app_generators : config.generators
-
1
generators.integration_tool :rspec
-
1
generators.test_framework :rspec
-
-
1
rake_tasks do
-
load "rspec/rails/tasks/rspec.rake"
-
end
-
end
-
end
-
end
-
1
require 'rspec/core'
-
1
require 'rails/version'
-
1
require 'rspec/rails/extensions'
-
1
require 'rspec/rails/view_rendering'
-
1
require 'rspec/rails/adapters'
-
1
require 'rspec/rails/matchers'
-
1
require 'rspec/rails/fixture_support'
-
1
require 'rspec/rails/example'
-
1
require 'rspec/rails/vendor/capybara'
-
1
require 'rspec/rails/configuration'
-
1
module RSpec
-
-
1
module Rails
-
# Fake class to document RSpec Rails configuration options. In practice,
-
# these are dynamically added to the normal RSpec configuration object.
-
1
class Configuration
-
# @!method infer_spec_type_from_file_location!
-
# Automatically tag specs in conventional directories with matching `type`
-
# metadata so that they have relevant helpers available to them. See
-
# `RSpec::Rails::DIRECTORY_MAPPINGS` for details on which metadata is
-
# applied to each directory.
-
-
# @!method render_views=(val)
-
#
-
# When set to `true`, controller specs will render the relevant view as
-
# well. Defaults to `false`.
-
-
# @!method render_views(val)
-
# Enables view rendering for controllers specs.
-
-
# @!method render_views?
-
# Reader for currently value of `render_views` setting.
-
end
-
-
# Mappings used by `infer_spec_type_from_file_location!`.
-
#
-
# @api private
-
1
DIRECTORY_MAPPINGS = {
-
:controller => %w[spec controllers],
-
:helper => %w[spec helpers],
-
:mailer => %w[spec mailers],
-
:model => %w[spec models],
-
:request => %w[spec (requests|integration|api)],
-
:routing => %w[spec routing],
-
:view => %w[spec views],
-
:feature => %w[spec features]
-
}
-
-
# @private
-
1
def self.initialize_configuration(config)
-
1
config.backtrace_exclusion_patterns << /vendor\//
-
1
config.backtrace_exclusion_patterns << /lib\/rspec\/rails/
-
-
1
config.include RSpec::Rails::ControllerExampleGroup, :type => :controller
-
1
config.include RSpec::Rails::HelperExampleGroup, :type => :helper
-
1
config.include RSpec::Rails::ModelExampleGroup, :type => :model
-
1
config.include RSpec::Rails::RequestExampleGroup, :type => :request
-
1
config.include RSpec::Rails::RoutingExampleGroup, :type => :routing
-
1
config.include RSpec::Rails::ViewExampleGroup, :type => :view
-
1
config.include RSpec::Rails::FeatureExampleGroup, :type => :feature
-
-
1
if defined?(ActionMailer)
-
1
config.include RSpec::Rails::MailerExampleGroup, :type => :mailer
-
end
-
-
# controller settings
-
1
config.add_setting :infer_base_class_for_anonymous_controllers, :default => true
-
-
# fixture support
-
1
config.include RSpec::Rails::FixtureSupport
-
1
config.add_setting :use_transactional_fixtures, :alias_with => :use_transactional_examples
-
1
config.add_setting :use_instantiated_fixtures
-
1
config.add_setting :global_fixtures
-
1
config.add_setting :fixture_path
-
-
# This allows us to expose `render_views` as a config option even though it
-
# breaks the convention of other options by using `render_views` as a
-
# command (i.e. `render_views = true`), where it would normally be used
-
# as a getter. This makes it easier for rspec-rails users because we use
-
# `render_views` directly in example groups, so this aligns the two APIs,
-
# but requires this workaround:
-
1
config.add_setting :rendering_views, :default => false
-
-
1
def config.render_views=(val)
-
self.rendering_views = val
-
end
-
-
1
def config.render_views
-
self.rendering_views = true
-
end
-
-
1
def config.render_views?
-
rendering_views
-
end
-
-
1
def config.infer_spec_type_from_file_location!
-
DIRECTORY_MAPPINGS.each do |type, dir_parts|
-
escaped_path = Regexp.compile(dir_parts.join('[\\\/]') + '[\\\/]')
-
define_derived_metadata(:file_path => escaped_path) do |metadata|
-
metadata[:type] ||= type
-
end
-
end
-
end
-
end
-
-
1
initialize_configuration RSpec.configuration
-
end
-
end
-
1
require 'rspec/rails/example/rails_example_group'
-
1
require 'rspec/rails/example/controller_example_group'
-
1
require 'rspec/rails/example/request_example_group'
-
1
require 'rspec/rails/example/helper_example_group'
-
1
require 'rspec/rails/example/view_example_group'
-
1
require 'rspec/rails/example/mailer_example_group'
-
1
require 'rspec/rails/example/routing_example_group'
-
1
require 'rspec/rails/example/model_example_group'
-
1
require 'rspec/rails/example/feature_example_group'
-
1
module RSpec::Rails
-
# Container module for controller spec functionality.
-
1
module ControllerExampleGroup
-
1
extend ActiveSupport::Concern
-
1
include RSpec::Rails::RailsExampleGroup
-
1
include ActionController::TestCase::Behavior
-
1
include RSpec::Rails::ViewRendering
-
1
include RSpec::Rails::Matchers::RedirectTo
-
1
include RSpec::Rails::Matchers::RenderTemplate
-
1
include RSpec::Rails::Matchers::RoutingMatchers
-
1
include RSpec::Rails::AssertionDelegator.new(ActionDispatch::Assertions::RoutingAssertions)
-
-
# Class-level DSL for controller specs.
-
1
module ClassMethods
-
# @private
-
1
def controller_class
-
described_class
-
end
-
-
# Supports a simple DSL for specifying behavior of ApplicationController.
-
# Creates an anonymous subclass of ApplicationController and evals the
-
# `body` in that context. Also sets up implicit routes for this
-
# controller, that are separate from those defined in "config/routes.rb".
-
#
-
# @note Due to Ruby 1.8 scoping rules in anonymous subclasses, constants
-
# defined in `ApplicationController` must be fully qualified (e.g.
-
# `ApplicationController::AccessDenied`) in the block passed to the
-
# `controller` method. Any instance methods, filters, etc, that are
-
# defined in `ApplicationController`, however, are accessible from
-
# within the block.
-
#
-
# @example
-
# describe ApplicationController do
-
# controller do
-
# def index
-
# raise ApplicationController::AccessDenied
-
# end
-
# end
-
#
-
# describe "handling AccessDenied exceptions" do
-
# it "redirects to the /401.html page" do
-
# get :index
-
# response.should redirect_to("/401.html")
-
# end
-
# end
-
# end
-
#
-
# If you would like to spec a subclass of ApplicationController, call
-
# controller like so:
-
#
-
# controller(ApplicationControllerSubclass) do
-
# # ....
-
# end
-
1
def controller(base_class = nil, &body)
-
if RSpec.configuration.infer_base_class_for_anonymous_controllers?
-
base_class ||= controller_class
-
end
-
base_class ||= defined?(ApplicationController) ? ApplicationController : ActionController::Base
-
-
new_controller_class = Class.new(base_class) do
-
def self.name
-
root_controller = defined?(ApplicationController) ? ApplicationController : ActionController::Base
-
if superclass == root_controller || superclass.abstract?
-
"AnonymousController"
-
else
-
superclass.to_s
-
end
-
end
-
end
-
new_controller_class.class_exec(&body)
-
(class << self; self; end).__send__(:define_method, :controller_class) { new_controller_class }
-
-
before do
-
@orig_routes = self.routes
-
resource_name = @controller.respond_to?(:controller_name) ?
-
@controller.controller_name.to_sym : :anonymous
-
resource_path = @controller.respond_to?(:controller_path) ?
-
@controller.controller_path : resource_name.to_s
-
resource_module = resource_path.rpartition('/').first.presence
-
resource_as = 'anonymous_' + resource_path.tr('/', '_')
-
self.routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
-
r.draw do
-
resources resource_name,
-
:as => resource_as,
-
:module => resource_module,
-
:path => resource_path
-
end
-
end
-
end
-
-
after do
-
self.routes = @orig_routes
-
@orig_routes = nil
-
end
-
end
-
-
# Specifies the routeset that will be used for the example group. This
-
# is most useful when testing Rails engines.
-
#
-
# @example
-
# describe MyEngine::PostsController do
-
# routes { MyEngine::Engine.routes }
-
#
-
# # ...
-
# end
-
1
def routes(&blk)
-
before do
-
self.routes = blk.call
-
end
-
end
-
end
-
-
1
attr_reader :controller, :routes
-
-
# @private
-
#
-
# RSpec Rails uses this to make Rails routes easily available to specs.
-
1
def routes=(routes)
-
@routes = routes
-
assertion_instance.instance_variable_set(:@routes, routes)
-
end
-
-
# @private
-
1
module BypassRescue
-
1
def rescue_with_handler(exception)
-
raise exception
-
end
-
end
-
-
# Extends the controller with a module that overrides
-
# `rescue_with_handler` to raise the exception passed to it. Use this to
-
# specify that an action _should_ raise an exception given appropriate
-
# conditions.
-
#
-
# @example
-
# describe ProfilesController do
-
# it "raises a 403 when a non-admin user tries to view another user's profile" do
-
# profile = create_profile
-
# login_as profile.user
-
#
-
# expect do
-
# bypass_rescue
-
# get :show, :id => profile.id + 1
-
# end.to raise_error(/403 Forbidden/)
-
# end
-
# end
-
1
def bypass_rescue
-
controller.extend(BypassRescue)
-
end
-
-
# If method is a named_route, delegates to the RouteSet associated with
-
# this controller.
-
1
def method_missing(method, *args, &block)
-
if defined?(@routes) && @routes.named_routes.helpers.include?(method)
-
controller.send(method, *args, &block)
-
elsif defined?(@orig_routes) && @orig_routes && @orig_routes.named_routes.helpers.include?(method)
-
controller.send(method, *args, &block)
-
else
-
super
-
end
-
end
-
-
1
included do
-
subject { controller }
-
-
before do
-
self.routes = ::Rails.application.routes
-
end
-
-
around do |ex|
-
previous_allow_forgery_protection_value = ActionController::Base.allow_forgery_protection
-
begin
-
ActionController::Base.allow_forgery_protection = false
-
ex.call
-
ensure
-
ActionController::Base.allow_forgery_protection = previous_allow_forgery_protection_value
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec::Rails
-
# Container module for routing spec functionality.
-
1
module FeatureExampleGroup
-
1
extend ActiveSupport::Concern
-
1
include RSpec::Rails::RailsExampleGroup
-
-
# Default host to be used in Rails route helpers if none is specified.
-
1
DEFAULT_HOST = "www.example.com"
-
-
1
included do
-
app = ::Rails.application
-
if app.respond_to?(:routes)
-
include app.routes.url_helpers if app.routes.respond_to?(:url_helpers)
-
include app.routes.mounted_helpers if app.routes.respond_to?(:mounted_helpers)
-
-
if respond_to?(:default_url_options)
-
default_url_options[:host] ||= ::RSpec::Rails::FeatureExampleGroup::DEFAULT_HOST
-
end
-
end
-
end
-
-
# Shim to check for presence of Capybara. Will delegate if present, raise
-
# if not. We assume here that in most cases `visit` will be the first
-
# Capybara method called in a spec.
-
1
def visit(*)
-
if defined?(super)
-
super
-
else
-
raise "Capybara not loaded, please add it to your Gemfile:\n\ngem \"capybara\""
-
end
-
end
-
end
-
end
-
1
require 'rspec/rails/view_assigns'
-
-
1
module RSpec::Rails
-
# Container module for helper specs.
-
1
module HelperExampleGroup
-
1
extend ActiveSupport::Concern
-
1
include RSpec::Rails::RailsExampleGroup
-
1
include ActionView::TestCase::Behavior
-
1
include RSpec::Rails::ViewAssigns
-
-
# @private
-
1
module ClassMethods
-
1
def determine_default_helper_class(ignore)
-
described_class
-
end
-
end
-
-
# Returns an instance of ActionView::Base with the helper being specified
-
# mixed in, along with any of the built-in rails helpers.
-
1
def helper
-
_view.tap do |v|
-
v.extend(ApplicationHelper) if defined?(ApplicationHelper)
-
v.assign(view_assigns)
-
end
-
end
-
-
1
private
-
-
1
def _controller_path(example)
-
example.example_group.described_class.to_s.sub(/Helper/,'').underscore
-
end
-
-
1
included do
-
before do |example|
-
controller.controller_path = _controller_path(example)
-
end
-
end
-
end
-
end
-
1
module RSpec::Rails
-
# Container module for mailer spec functionality. It is only available if
-
# ActionMailer has been loaded before it.
-
1
module MailerExampleGroup
-
# This blank module is only necessary for YARD processing. It doesn't
-
# handle the conditional `defined?` check below very well.
-
end
-
end
-
-
1
if defined?(ActionMailer)
-
1
module RSpec::Rails
-
# Container module for mailer spec functionality.
-
1
module MailerExampleGroup
-
1
extend ActiveSupport::Concern
-
1
include RSpec::Rails::RailsExampleGroup
-
1
include ActionMailer::TestCase::Behavior
-
-
1
included do
-
include ::Rails.application.routes.url_helpers
-
options = ::Rails.configuration.action_mailer.default_url_options
-
options.each { |key, value| default_url_options[key] = value } if options
-
end
-
-
# Class-level DSL for mailer specs.
-
1
module ClassMethods
-
# Alias for `described_class`.
-
1
def mailer_class
-
described_class
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec::Rails
-
# Container class for model spec functionality. Does not provide anything
-
# special over the common RailsExampleGroup currently.
-
1
module ModelExampleGroup
-
1
extend ActiveSupport::Concern
-
1
include RSpec::Rails::RailsExampleGroup
-
end
-
end
-
# Temporary workaround to resolve circular dependency between rspec-rails' spec
-
# suite and ammeter.
-
1
require 'rspec/rails/matchers'
-
-
1
module RSpec
-
1
module Rails
-
# Common rails example functionality.
-
1
module RailsExampleGroup
-
1
extend ActiveSupport::Concern
-
1
include RSpec::Rails::SetupAndTeardownAdapter
-
1
include RSpec::Rails::MinitestLifecycleAdapter if ::Rails::VERSION::STRING >= '4'
-
1
include RSpec::Rails::MinitestAssertionAdapter
-
1
include RSpec::Rails::Matchers
-
end
-
end
-
end
-
1
module RSpec::Rails
-
# Container class for request spec functionality.
-
1
module RequestExampleGroup
-
1
extend ActiveSupport::Concern
-
1
include RSpec::Rails::RailsExampleGroup
-
1
include ActionDispatch::Integration::Runner
-
1
include ActionDispatch::Assertions
-
1
include RSpec::Rails::Matchers::RedirectTo
-
1
include RSpec::Rails::Matchers::RenderTemplate
-
1
include ActionController::TemplateAssertions
-
-
# Delegates to `Rails.application`.
-
1
def app
-
::Rails.application
-
end
-
-
1
included do
-
before do
-
@routes = ::Rails.application.routes
-
end
-
end
-
end
-
end
-
1
require "action_dispatch/testing/assertions/routing"
-
-
1
module RSpec::Rails
-
# Container module for routing spec functionality.
-
1
module RoutingExampleGroup
-
1
extend ActiveSupport::Concern
-
1
include RSpec::Rails::RailsExampleGroup
-
1
include RSpec::Rails::Matchers::RoutingMatchers
-
1
include RSpec::Rails::Matchers::RoutingMatchers::RouteHelpers
-
1
include RSpec::Rails::AssertionDelegator.new(ActionDispatch::Assertions::RoutingAssertions)
-
-
# Class-level DSL for route specs.
-
1
module ClassMethods
-
# Specifies the routeset that will be used for the example group. This
-
# is most useful when testing Rails engines.
-
#
-
# @example
-
# describe MyEngine::PostsController do
-
# routes { MyEngine::Engine.routes }
-
#
-
# it "routes posts#index" do
-
# expect(:get => "/posts").to
-
# route_to(:controller => "my_engine/posts", :action => "index")
-
# end
-
# end
-
1
def routes(&blk)
-
before do
-
self.routes = blk.call
-
end
-
end
-
end
-
-
1
included do
-
before do
-
self.routes = ::Rails.application.routes
-
end
-
end
-
-
1
attr_reader :routes
-
-
# @private
-
1
def routes=(routes)
-
@routes = routes
-
assertion_instance.instance_variable_set(:@routes, routes)
-
end
-
-
1
private
-
-
1
def method_missing(m, *args, &block)
-
routes.url_helpers.respond_to?(m) ? routes.url_helpers.send(m, *args) : super
-
end
-
end
-
end
-
1
require 'rspec/rails/view_assigns'
-
-
1
module RSpec::Rails
-
# Container class for view spec functionality.
-
1
module ViewExampleGroup
-
1
extend ActiveSupport::Concern
-
1
include RSpec::Rails::RailsExampleGroup
-
1
include ActionView::TestCase::Behavior
-
1
include RSpec::Rails::ViewAssigns
-
1
include RSpec::Rails::Matchers::RenderTemplate
-
-
# @private
-
1
module ClassMethods
-
1
def _default_helper
-
base = metadata[:description].split('/')[0..-2].join('/')
-
(base.camelize + 'Helper').constantize if base
-
rescue NameError
-
nil
-
end
-
-
1
def _default_helpers
-
helpers = [_default_helper].compact
-
helpers << ApplicationHelper if Object.const_defined?('ApplicationHelper')
-
helpers
-
end
-
end
-
-
# DSL exposed to view specs.
-
1
module ExampleMethods
-
# @overload render
-
# @overload render({:partial => path_to_file})
-
# @overload render({:partial => path_to_file}, {... locals ...})
-
# @overload render({:partial => path_to_file}, {... locals ...}) do ... end
-
#
-
# Delegates to ActionView::Base#render, so see documentation on that
-
# for more info.
-
#
-
# The only addition is that you can call render with no arguments, and RSpec
-
# will pass the top level description to render:
-
#
-
# describe "widgets/new.html.erb" do
-
# it "shows all the widgets" do
-
# render # => view.render(:file => "widgets/new.html.erb")
-
# # ...
-
# end
-
# end
-
1
def render(options={}, local_assigns={}, &block)
-
options = _default_render_options if Hash === options and options.empty?
-
super(options, local_assigns, &block)
-
end
-
-
# The instance of `ActionView::Base` that is used to render the template.
-
# Use this to stub methods _before_ calling `render`.
-
#
-
# describe "widgets/new.html.erb" do
-
# it "shows all the widgets" do
-
# view.stub(:foo) { "foo" }
-
# render
-
# # ...
-
# end
-
# end
-
1
def view
-
_view
-
end
-
-
# Simulates the presence of a template on the file system by adding a
-
# Rails' FixtureResolver to the front of the view_paths list. Designed to
-
# help isolate view examples from partials rendered by the view template
-
# that is the subject of the example.
-
#
-
# stub_template("widgets/_widget.html.erb" => "This content.")
-
1
def stub_template(hash)
-
view.view_paths.unshift(ActionView::FixtureResolver.new(hash))
-
end
-
-
# Provides access to the params hash that will be available within the
-
# view.
-
#
-
# params[:foo] = 'bar'
-
1
def params
-
controller.params
-
end
-
-
# @deprecated Use `view` instead.
-
1
def template
-
RSpec.deprecate("template", :replacement => "view")
-
view
-
end
-
-
# @deprecated Use `rendered` instead.
-
1
def response
-
# `assert_template` expects `response` to implement a #body method
-
# like an `ActionDispatch::Response` does to force the view to render.
-
# For backwards compatibility, we use #response as an alias for
-
# #rendered, but it needs to implement #body to avoid `assert_template`
-
# raising a `NoMethodError`.
-
unless rendered.respond_to?(:body)
-
def rendered.body; self; end;
-
end
-
-
rendered
-
end
-
-
1
private
-
-
1
def _default_render_options
-
if ::Rails::VERSION::STRING >= '3.2'
-
# pluck the handler, format, and locale out of, eg, posts/index.de.html.haml
-
template, *components = _default_file_to_render.split('.')
-
handler, format, locale = *components.reverse
-
-
render_options = {:template => template}
-
render_options[:handlers] = [handler] if handler
-
render_options[:formats] = [format] if format
-
render_options[:locales] = [locale] if locale
-
-
render_options
-
else
-
{:template => _default_file_to_render}
-
end
-
end
-
-
1
def _path_parts
-
_default_file_to_render.split("/")
-
end
-
-
1
def _controller_path
-
_path_parts[0..-2].join("/")
-
end
-
-
1
def _inferred_action
-
_path_parts.last.split(".").first
-
end
-
-
1
def _include_controller_helpers
-
helpers = controller._helpers
-
view.singleton_class.class_exec do
-
include helpers unless included_modules.include?(helpers)
-
end
-
end
-
end
-
-
1
included do
-
include ExampleMethods
-
-
helper(*_default_helpers)
-
-
before do
-
_include_controller_helpers
-
if view.lookup_context.respond_to?(:prefixes)
-
# rails 3.1
-
view.lookup_context.prefixes << _controller_path
-
end
-
-
# fixes bug with differing formats
-
view.lookup_context.view_paths.each(&:clear_cache)
-
-
controller.controller_path = _controller_path
-
controller.request.path_parameters[:controller] = _controller_path
-
controller.request.path_parameters[:action] = _inferred_action unless _inferred_action =~ /^_/
-
end
-
-
let(:_default_file_to_render) do |example|
-
example.example_group.top_level_description
-
end
-
end
-
end
-
end
-
-
1
require 'rspec/rails/extensions/active_record/proxy'
-
1
RSpec.configure do |rspec|
-
# Delay this in order to give users a chance to configure `expect_with`...
-
1
rspec.before(:suite) do
-
if defined?(RSpec::Matchers) && RSpec::Matchers.configuration.syntax.include?(:should) && defined?(ActiveRecord::Associations)
-
# In Rails 3.0, it was AssociationProxy.
-
# In 3.1+, it's CollectionProxy.
-
const_name = [:CollectionProxy, :AssociationProxy].find do |const|
-
ActiveRecord::Associations.const_defined?(const)
-
end
-
-
proxy_class = ActiveRecord::Associations.const_get(const_name)
-
-
RSpec::Matchers.configuration.add_should_and_should_not_to proxy_class
-
end
-
end
-
end
-
-
1
module RSpec
-
1
module Rails
-
# @private
-
1
module FixtureSupport
-
1
if defined?(ActiveRecord::TestFixtures)
-
1
extend ActiveSupport::Concern
-
1
include RSpec::Rails::SetupAndTeardownAdapter
-
1
include RSpec::Rails::MinitestLifecycleAdapter if ::ActiveRecord::VERSION::STRING > '4'
-
1
include RSpec::Rails::MinitestAssertionAdapter
-
1
include ActiveRecord::TestFixtures
-
-
1
included do
-
# TODO (DC 2011-06-25) this is necessary because fixture_file_upload
-
# accesses fixture_path directly on ActiveSupport::TestCase. This is
-
# fixed in rails by https://github.com/rails/rails/pull/1861, which
-
# should be part of the 3.1 release, at which point we can include
-
# these lines for rails < 3.1.
-
ActiveSupport::TestCase.class_exec do
-
include ActiveRecord::TestFixtures
-
self.fixture_path = RSpec.configuration.fixture_path
-
end
-
# /TODO
-
-
self.fixture_path = RSpec.configuration.fixture_path
-
self.use_transactional_fixtures = RSpec.configuration.use_transactional_fixtures
-
self.use_instantiated_fixtures = RSpec.configuration.use_instantiated_fixtures
-
fixtures RSpec.configuration.global_fixtures if RSpec.configuration.global_fixtures
-
end
-
end
-
end
-
end
-
end
-
1
require 'rspec/core/warnings'
-
1
require 'rspec/expectations'
-
-
1
module RSpec::Rails
-
1
module Matchers
-
end
-
end
-
-
1
begin
-
1
require 'test/unit/assertionfailederror'
-
rescue LoadError
-
1
module Test
-
1
module Unit
-
1
class AssertionFailedError < StandardError
-
end
-
end
-
end
-
end
-
-
1
require 'rspec/rails/matchers/have_rendered'
-
1
require 'rspec/rails/matchers/redirect_to'
-
1
require 'rspec/rails/matchers/routing_matchers'
-
1
require 'rspec/rails/matchers/be_new_record'
-
1
require 'rspec/rails/matchers/be_a_new'
-
1
require 'rspec/rails/matchers/relation_match_array'
-
1
require 'rspec/rails/matchers/be_valid'
-
1
require 'rspec/rails/matchers/have_http_status'
-
1
module RSpec::Rails::Matchers
-
# @api private
-
#
-
# Matcher class for `be_a_new`. Should not be instantiated directly.
-
#
-
# @see RSpec::Rails::Matchers#be_a_new
-
1
class BeANew < RSpec::Matchers::BuiltIn::BaseMatcher
-
# @private
-
1
def initialize(expected)
-
@expected = expected
-
end
-
-
# @private
-
1
def matches?(actual)
-
@actual = actual
-
actual.is_a?(expected) && actual.new_record? && attributes_match?(actual)
-
end
-
-
# @api public
-
# @see RSpec::Rails::Matchers#be_a_new
-
1
def with(expected_attributes)
-
attributes.merge!(expected_attributes)
-
self
-
end
-
-
# @private
-
1
def failure_message
-
[].tap do |message|
-
unless actual.is_a?(expected) && actual.new_record?
-
message << "expected #{actual.inspect} to be a new #{expected.inspect}"
-
end
-
unless attributes_match?(actual)
-
if unmatched_attributes.size > 1
-
message << "attributes #{unmatched_attributes.inspect} were not set on #{actual.inspect}"
-
else
-
message << "attribute #{unmatched_attributes.inspect} was not set on #{actual.inspect}"
-
end
-
end
-
end.join(' and ')
-
end
-
-
1
private
-
-
1
def attributes
-
@attributes ||= {}
-
end
-
-
1
def attributes_match?(actual)
-
attributes.stringify_keys.all? do |key, value|
-
actual.attributes[key].eql?(value)
-
end
-
end
-
-
1
def unmatched_attributes
-
attributes.stringify_keys.reject do |key, value|
-
actual.attributes[key].eql?(value)
-
end
-
end
-
end
-
-
# Passes if actual is an instance of `model_class` and returns `false` for
-
# `persisted?`. Typically used to specify instance variables assigned to
-
# views by controller actions
-
#
-
# Use the `with` method to specify the specific attributes to match on the
-
# new record.
-
#
-
# @example
-
# get :new
-
# assigns(:thing).should be_a_new(Thing)
-
#
-
# post :create, :thing => { :name => "Illegal Value" }
-
# assigns(:thing).should be_a_new(Thing).with(:name => nil)
-
1
def be_a_new(model_class)
-
BeANew.new(model_class)
-
end
-
end
-
1
module RSpec::Rails::Matchers
-
# @private
-
1
class BeANewRecord < RSpec::Matchers::BuiltIn::BaseMatcher
-
1
def matches?(actual)
-
!actual.persisted?
-
end
-
-
1
def failure_message
-
"expected #{actual.inspect} to be a new record, but was persisted"
-
end
-
-
1
def failure_message_when_negated
-
"expected #{actual.inspect} to be persisted, but was a new record"
-
end
-
end
-
-
# Passes if actual returns `false` for `persisted?`.
-
#
-
# @example
-
# get :new
-
# expect(assigns(:thing)).to be_new_record
-
1
def be_new_record
-
BeANewRecord.new
-
end
-
end
-
1
module RSpec::Rails::Matchers
-
# @private
-
1
class BeValid < RSpec::Matchers::BuiltIn::Be
-
1
def initialize(*args)
-
@args = args
-
end
-
-
1
def matches?(actual)
-
@actual = actual
-
actual.valid?(*@args)
-
end
-
-
1
def failure_message
-
message = "expected #{actual.inspect} to be valid"
-
-
if actual.respond_to?(:errors)
-
errors = if actual.errors.respond_to?(:full_messages)
-
actual.errors.full_messages
-
else
-
actual.errors
-
end
-
-
message << ", but got errors: #{errors.map(&:to_s).join(', ')}"
-
end
-
-
message
-
end
-
-
1
def failure_message_when_negated
-
"expected #{actual.inspect} not to be valid"
-
end
-
end
-
-
# Passes if the given model instance's `valid?` method is true, meaning all
-
# of the `ActiveModel::Validations` passed and no errors exist. If a message
-
# is not given, a default message is shown listing each error.
-
#
-
# @example
-
# thing = Thing.new
-
# expect(thing).to be_valid
-
1
def be_valid(*args)
-
BeValid.new(*args)
-
end
-
end
-
# The following code inspired and modified from Rails' `assert_response`:
-
#
-
# https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/testing/assertions/response.rb#L22-L38
-
#
-
# Thank you to all the Rails devs who did the heavy lifting on this!
-
-
1
module RSpec::Rails::Matchers
-
# Namespace for various implementations of `have_http_status`.
-
#
-
# @api private
-
1
module HaveHttpStatus
-
# Instantiates an instance of the proper matcher based on the provided
-
# `target`.
-
#
-
# @param target [Object] expected http status or code
-
# @return response matcher instance
-
1
def self.matcher_for_status(target)
-
if GenericStatus.valid_statuses.include?(target)
-
GenericStatus.new(target)
-
elsif Symbol === target
-
SymbolicStatus.new(target)
-
else
-
NumericCode.new(target)
-
end
-
end
-
-
# @api private
-
# Conversion function to coerce the provided object into an
-
# `ActionDispatch::TestResponse`.
-
#
-
# @param obj [Object] object to convert to a response
-
# @return [ActionDispatch::TestResponse]
-
1
def as_test_response(obj)
-
if ::ActionDispatch::Response === obj
-
::ActionDispatch::TestResponse.from_response(obj)
-
elsif ::ActionDispatch::TestResponse === obj
-
obj
-
elsif obj.respond_to?(:status_code) && obj.respond_to?(:response_headers)
-
# Acts As Capybara Session
-
# Hack to support `Capybara::Session` without having to load Capybara or
-
# catch `NameError`s for the undefined constants
-
::ActionDispatch::TestResponse.new.tap{ |resp|
-
resp.status = obj.status_code
-
resp.headers = obj.response_headers
-
resp.body = obj.body
-
}
-
else
-
raise TypeError, "Invalid response type: #{obj}"
-
end
-
end
-
1
module_function :as_test_response
-
-
# @return [String, nil] a formatted failure message if `@invalid_response`
-
# is present, `nil` otherwise
-
1
def invalid_response_type_message
-
if @invalid_response
-
"expected a response object, but an instance of " +
-
"#{@invalid_response.class} was received"
-
end
-
end
-
-
# @api private
-
# Provides an implementation for `have_http_status` matching against
-
# numeric http status codes.
-
#
-
# Not intended to be instantiated directly.
-
#
-
# @example
-
# expect(response).to have_http_status(404)
-
#
-
# @see RSpec::Rails::Matchers.have_http_status
-
1
class NumericCode < RSpec::Matchers::BuiltIn::BaseMatcher
-
1
include HaveHttpStatus
-
-
1
def initialize(code)
-
@expected = code.to_i
-
@actual = nil
-
@invalid_response = nil
-
end
-
-
# @param [Object] response object providing an http code to match
-
# @return [Boolean] `true` if the numeric code matched the `response` code
-
1
def matches?(response)
-
test_response = as_test_response(response)
-
@actual = test_response.response_code
-
expected == @actual
-
rescue TypeError => _ignored
-
@invalid_response = response
-
false
-
end
-
-
# @return [String]
-
1
def description
-
"respond with numeric status code #{expected}"
-
end
-
-
# @return [String] explaining why the match failed
-
1
def failure_message
-
invalid_response_type_message ||
-
"expected the response to have status code #{expected.inspect}" +
-
" but it was #{actual.inspect}"
-
end
-
-
# @return [String] explaining why the match failed
-
1
def failure_message_when_negated
-
invalid_response_type_message ||
-
"expected the response not to have status code #{expected.inspect}" +
-
" but it did"
-
end
-
end
-
-
# @api private
-
# Provides an implementation for `have_http_status` matching against
-
# Rack symbol http status codes.
-
#
-
# Not intended to be instantiated directly.
-
#
-
# @example
-
# expect(response).to have_http_status(:created)
-
#
-
# @see RSpec::Rails::Matchers.have_http_status
-
# @see https://github.com/rack/rack/blob/master/lib/rack/utils.rb `Rack::Utils::SYMBOL_TO_STATUS_CODE`
-
1
class SymbolicStatus < RSpec::Matchers::BuiltIn::BaseMatcher
-
1
include HaveHttpStatus
-
-
1
def initialize(status)
-
@expected_status = status
-
@actual = nil
-
@invalid_response = nil
-
unless set_expected_code!
-
raise ArgumentError, "Invalid HTTP status: #{status.inspect}"
-
end
-
end
-
-
# @param [Object] response object providing an http code to match
-
# @return [Boolean] `true` if Rack's associated numeric HTTP code matched
-
# the `response` code
-
1
def matches?(response)
-
test_response = as_test_response(response)
-
@actual = test_response.response_code
-
expected == @actual
-
rescue TypeError => _ignored
-
@invalid_response = response
-
false
-
end
-
-
# @return [String]
-
1
def description
-
"respond with status code #{pp_expected}"
-
end
-
-
# @return [String] explaining why the match failed
-
1
def failure_message
-
invalid_response_type_message ||
-
"expected the response to have status code #{pp_expected} but it" +
-
" was #{pp_actual}"
-
end
-
-
# @return [String] explaining why the match failed
-
1
def failure_message_when_negated
-
invalid_response_type_message ||
-
"expected the response not to have status code #{pp_expected} " +
-
"but it did"
-
end
-
-
# The initialized expected status symbol
-
1
attr_reader :expected_status
-
1
private :expected_status
-
-
1
private
-
-
# @return [Symbol] representing the actual http numeric code
-
1
def actual_status
-
if actual
-
@actual_status ||= compute_status_from(actual)
-
end
-
end
-
-
# Reverse lookup of the Rack status code symbol based on the numeric http
-
# code
-
#
-
# @param code [Fixnum] http status code to look up
-
# @return [Symbol] representing the http numeric code
-
1
def compute_status_from(code)
-
status, _ = Rack::Utils::SYMBOL_TO_STATUS_CODE.find{ |_, c| c == code }
-
status
-
end
-
-
# @return [String] pretty format the actual response status
-
1
def pp_actual
-
pp_status(actual_status, actual)
-
end
-
-
# @return [String] pretty format the expected status and associated code
-
1
def pp_expected
-
pp_status(expected_status, expected)
-
end
-
-
# @return [String] pretty format the actual response status
-
1
def pp_status(status, code)
-
if status
-
"#{status.inspect} (#{code})"
-
else
-
code.to_s
-
end
-
end
-
-
# Sets `expected` to the numeric http code based on the Rack
-
# `expected_status` status
-
#
-
# @see Rack::Utils::SYMBOL_TO_STATUS_CODE
-
# @return [nil] if an associated code could not be found
-
1
def set_expected_code!
-
@expected ||= Rack::Utils::SYMBOL_TO_STATUS_CODE[expected_status]
-
end
-
end
-
-
# @api private
-
# Provides an implementation for `have_http_status` matching against
-
# `ActionDispatch::TestResponse` http status category queries.
-
#
-
# Not intended to be instantiated directly.
-
#
-
# @example
-
# expect(response).to have_http_status(:success)
-
# expect(response).to have_http_status(:error)
-
# expect(response).to have_http_status(:missing)
-
# expect(response).to have_http_status(:redirect)
-
#
-
# @see RSpec::Rails::Matchers.have_http_status
-
# @see ActionDispatch::TestResponse
-
1
class GenericStatus < RSpec::Matchers::BuiltIn::BaseMatcher
-
1
include HaveHttpStatus
-
-
# @return [Array<Symbol>] of status codes which represent a HTTP status
-
# code "group"
-
# @see https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/testing/test_response.rb `ActionDispatch::TestResponse`
-
1
def self.valid_statuses
-
[:error, :success, :missing, :redirect]
-
end
-
-
1
def initialize(type)
-
unless self.class.valid_statuses.include?(type)
-
raise ArgumentError, "Invalid generic HTTP status: #{type.inspect}"
-
end
-
@expected = type
-
@actual = nil
-
@invalid_response = nil
-
end
-
-
# @return [Boolean] `true` if Rack's associated numeric HTTP code matched
-
# the `response` code
-
1
def matches?(response)
-
test_response = as_test_response(response)
-
@actual = test_response.response_code
-
test_response.send("#{expected}?")
-
rescue TypeError => _ignored
-
@invalid_response = response
-
false
-
end
-
-
# @return [String]
-
1
def description
-
"respond with #{type_message}"
-
end
-
-
# @return [String] explaining why the match failed
-
1
def failure_message
-
invalid_response_type_message ||
-
"expected the response to have #{type_message} but it was #{actual}"
-
end
-
-
# @return [String] explaining why the match failed
-
1
def failure_message_when_negated
-
invalid_response_type_message ||
-
"expected the response not to have #{type_message} but it was #{actual}"
-
end
-
-
1
private
-
-
# @return [String] formating the expected status and associated code(s)
-
1
def type_message
-
@type_message ||= (expected == :error ? "an error" : "a #{expected}") +
-
" status code (#{type_codes})"
-
end
-
-
# @return [String] formatting the associated code(s) for the various
-
# status code "groups"
-
# @see https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/testing/test_response.rb `ActionDispatch::TestResponse`
-
# @see https://github.com/rack/rack/blob/master/lib/rack/response.rb `Rack::Response`
-
1
def type_codes
-
# At the time of this commit the most recent version of
-
# `ActionDispatch::TestResponse` defines the following aliases:
-
#
-
# alias_method :success?, :successful?
-
# alias_method :missing?, :not_found?
-
# alias_method :redirect?, :redirection?
-
# alias_method :error?, :server_error?
-
#
-
# It's parent `ActionDispatch::Response` includes
-
# `Rack::Response::Helpers` which defines the aliased methods as:
-
#
-
# def successful?; status >= 200 && status < 300; end
-
# def redirection?; status >= 300 && status < 400; end
-
# def server_error?; status >= 500 && status < 600; end
-
# def not_found?; status == 404; end
-
#
-
# @see https://github.com/rails/rails/blob/ca200378/actionpack/lib/action_dispatch/testing/test_response.rb#L17-L27
-
# @see https://github.com/rails/rails/blob/ca200378/actionpack/lib/action_dispatch/http/response.rb#L74
-
# @see https://github.com/rack/rack/blob/ce4a3959/lib/rack/response.rb#L119-L122
-
@type_codes ||= case expected
-
when :error
-
"5xx"
-
when :success
-
"2xx"
-
when :missing
-
"404"
-
when :redirect
-
"3xx"
-
end
-
end
-
end
-
end
-
-
# @api public
-
# Passes if `response` has a matching HTTP status code.
-
#
-
# The following symbolic status codes are allowed:
-
#
-
# - `Rack::Utils::SYMBOL_TO_STATUS_CODE`
-
# - One of the defined `ActionDispatch::TestResponse` aliases:
-
# - `:error`
-
# - `:missing`
-
# - `:redirect`
-
# - `:success`
-
#
-
# @example Accepts numeric and symbol statuses
-
# expect(response).to have_http_status(404)
-
# expect(response).to have_http_status(:created)
-
# expect(response).to have_http_status(:success)
-
# expect(response).to have_http_status(:error)
-
# expect(response).to have_http_status(:missing)
-
# expect(response).to have_http_status(:redirect)
-
#
-
# @example Works with standard `response` objects and Capybara's `page`
-
# expect(response).to have_http_status(404)
-
# expect(page).to have_http_status(:created)
-
#
-
# @see https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/testing/test_response.rb `ActionDispatch::TestResponse`
-
# @see https://github.com/rack/rack/blob/master/lib/rack/utils.rb `Rack::Utils::SYMBOL_TO_STATUS_CODE`
-
1
def have_http_status(target)
-
raise ArgumentError, "Invalid HTTP status: nil" unless target
-
HaveHttpStatus.matcher_for_status(target)
-
end
-
end
-
1
module RSpec::Rails::Matchers
-
# Matcher for template rendering.
-
1
module RenderTemplate
-
# @private
-
1
class RenderTemplateMatcher < RSpec::Matchers::BuiltIn::BaseMatcher
-
-
1
def initialize(scope, expected, message=nil)
-
@expected = Symbol === expected ? expected.to_s : expected
-
@message = message
-
@scope = scope
-
end
-
-
# @api private
-
1
def matches?(*)
-
match_unless_raises ActiveSupport::TestCase::Assertion do
-
@scope.assert_template expected, @message
-
end
-
end
-
-
# @api private
-
1
def failure_message
-
rescued_exception.message
-
end
-
-
# @api private
-
1
def failure_message_when_negated
-
"expected not to render #{expected.inspect}, but did"
-
end
-
end
-
-
# Delegates to `assert_template`.
-
#
-
# @example
-
# expect(response).to have_rendered("new")
-
1
def have_rendered(options, message=nil)
-
RenderTemplateMatcher.new(self, options, message)
-
end
-
-
1
alias_method :render_template, :have_rendered
-
end
-
end
-
1
module RSpec::Rails::Matchers
-
# Matcher for redirects.
-
1
module RedirectTo
-
# @private
-
1
class RedirectTo < RSpec::Matchers::BuiltIn::BaseMatcher
-
-
1
def initialize(scope, expected)
-
@expected = expected
-
@scope = scope
-
end
-
-
1
def matches?(_)
-
match_unless_raises ActiveSupport::TestCase::Assertion do
-
@scope.assert_redirected_to(@expected)
-
end
-
end
-
-
1
def failure_message
-
rescued_exception.message
-
end
-
-
1
def failure_message_when_negated
-
"expected not to redirect to #{@expected.inspect}, but did"
-
end
-
end
-
-
# Delegates to `assert_redirected_to`.
-
#
-
# @example
-
# expect(response).to redirect_to(:action => "new")
-
1
def redirect_to(target)
-
RedirectTo.new(self, target)
-
end
-
end
-
end
-
1
if defined?(ActiveRecord::Relation)
-
1
RSpec::Matchers::BuiltIn::OperatorMatcher.register(ActiveRecord::Relation, '=~', RSpec::Matchers::BuiltIn::ContainExactly)
-
end
-
1
module RSpec::Rails::Matchers
-
# Matchers to help with specs for routing code.
-
1
module RoutingMatchers
-
1
extend RSpec::Matchers::DSL
-
-
# @private
-
1
class RouteToMatcher < RSpec::Matchers::BuiltIn::BaseMatcher
-
-
1
def initialize(scope, *expected)
-
@scope = scope
-
@expected = expected[1] || {}
-
if Hash === expected[0]
-
@expected.merge!(expected[0])
-
else
-
controller, action = expected[0].split('#')
-
@expected.merge!(:controller => controller, :action => action)
-
end
-
end
-
-
1
def matches?(verb_to_path_map)
-
@actual = @verb_to_path_map = verb_to_path_map
-
# assert_recognizes does not consider ActionController::RoutingError an
-
# assertion failure, so we have to capture that and Assertion here.
-
match_unless_raises ActiveSupport::TestCase::Assertion, ActionController::RoutingError do
-
path, query = *verb_to_path_map.values.first.split('?')
-
@scope.assert_recognizes(
-
@expected,
-
{:method => verb_to_path_map.keys.first, :path => path},
-
Rack::Utils::parse_nested_query(query)
-
)
-
end
-
end
-
-
1
def failure_message
-
rescued_exception.message
-
end
-
-
1
def failure_message_when_negated
-
"expected #{@actual.inspect} not to route to #{@expected.inspect}"
-
end
-
-
1
def description
-
"route #{@actual.inspect} to #{@expected.inspect}"
-
end
-
end
-
-
# Delegates to `assert_recognizes`. Supports short-hand controller/action
-
# declarations (e.g. `"controller#action"`).
-
#
-
# @example
-
#
-
# expect(:get => "/things/special").to route_to(
-
# :controller => "things",
-
# :action => "special"
-
# )
-
#
-
# expect(:get => "/things/special").to route_to("things#special")
-
#
-
# @see http://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_recognizes
-
1
def route_to(*expected)
-
RouteToMatcher.new(self, *expected)
-
end
-
-
# @private
-
1
class BeRoutableMatcher < RSpec::Matchers::BuiltIn::BaseMatcher
-
-
1
def initialize(scope)
-
@scope = scope
-
end
-
-
1
def matches?(path)
-
@actual = path
-
match_unless_raises ActionController::RoutingError do
-
@routing_options = @scope.routes.recognize_path(
-
path.values.first, :method => path.keys.first
-
)
-
end
-
end
-
-
1
def failure_message
-
"expected #{@actual.inspect} to be routable"
-
end
-
-
1
def failure_message_when_negated
-
"expected #{@actual.inspect} not to be routable, but it routes to #{@routing_options.inspect}"
-
end
-
end
-
-
# Passes if the route expression is recognized by the Rails router based on
-
# the declarations in `config/routes.rb`. Delegates to
-
# `RouteSet#recognize_path`.
-
#
-
# @example You can use route helpers provided by rspec-rails.
-
# expect(:get => "/a/path").to be_routable
-
# expect(:post => "/another/path").to be_routable
-
# expect(:put => "/yet/another/path").to be_routable
-
1
def be_routable
-
BeRoutableMatcher.new(self)
-
end
-
-
# Helpers for matching different route types.
-
1
module RouteHelpers
-
# @!method get
-
# @!method post
-
# @!method put
-
# @!method patch
-
# @!method delete
-
# @!method options
-
# @!method head
-
#
-
# Shorthand method for matching this type of route.
-
1
%w(get post put patch delete options head).each do |method|
-
7
define_method method do |path|
-
{ method.to_sym => path }
-
end
-
end
-
end
-
end
-
end
-
1
begin
-
1
require 'capybara/rspec'
-
rescue LoadError
-
end
-
-
1
begin
-
1
require 'capybara/rails'
-
rescue LoadError
-
end
-
-
1
if defined?(Capybara)
-
require 'rspec/support/version_checker'
-
RSpec::Support::VersionChecker.new('capybara', Capybara::VERSION, '2.2.0').check_version!
-
-
RSpec.configure do |c|
-
if defined?(Capybara::DSL)
-
c.include Capybara::DSL, :type => :feature
-
end
-
-
if defined?(Capybara::RSpecMatchers)
-
c.include Capybara::RSpecMatchers, :type => :view
-
c.include Capybara::RSpecMatchers, :type => :helper
-
c.include Capybara::RSpecMatchers, :type => :mailer
-
c.include Capybara::RSpecMatchers, :type => :controller
-
c.include Capybara::RSpecMatchers, :type => :feature
-
end
-
-
unless defined?(Capybara::RSpecMatchers) || defined?(Capybara::DSL)
-
c.include Capybara, :type => :request
-
c.include Capybara, :type => :controller
-
end
-
end
-
end
-
1
module RSpec
-
1
module Rails
-
# Helpers for making instance variables available to views.
-
1
module ViewAssigns
-
# Assigns a value to an instance variable in the scope of the
-
# view being rendered.
-
#
-
# @example
-
#
-
# assign(:widget, stub_model(Widget))
-
1
def assign(key, value)
-
_encapsulated_assigns[key] = value
-
end
-
-
# Compat-shim for AbstractController::Rendering#view_assigns
-
#
-
# _assigns was deprecated in favor of view_assigns after
-
# Rails-3.0.0 was released. Since we are not able to predict when
-
# the _assigns/view_assigns patch will be released (I thought it
-
# would have been in 3.0.1, but 3.0.1 bypassed this change for a
-
# security fix), this bit ensures that we do the right thing without
-
# knowing anything about the Rails version we are dealing with.
-
#
-
# Once that change _is_ released, this can be changed to something
-
# that checks for the Rails version when the module is being
-
# interpreted, as it was before commit dd0095.
-
1
def view_assigns
-
super.merge(_encapsulated_assigns)
-
rescue
-
_assigns
-
end
-
-
# @private
-
1
def _assigns
-
super.merge(_encapsulated_assigns)
-
end
-
-
1
private
-
-
1
def _encapsulated_assigns
-
@_encapsulated_assigns ||= {}
-
end
-
-
end
-
end
-
end
-
1
RSpec::Support.require_rspec_support 'encoded_string'
-
1
RSpec::Support.require_rspec_support 'hunk_generator'
-
-
1
require 'pp'
-
-
1
module RSpec
-
1
module Support
-
1
class Differ
-
1
def diff(actual, expected)
-
diff = ""
-
-
if actual && expected
-
if all_strings?(actual, expected)
-
if any_multiline_strings?(actual, expected)
-
diff = diff_as_string(coerce_to_string(actual), coerce_to_string(expected))
-
end
-
elsif no_procs?(actual, expected) && no_numbers?(actual, expected)
-
diff = diff_as_object(actual, expected)
-
end
-
end
-
-
diff.to_s
-
end
-
-
1
def diff_as_string(actual, expected)
-
@encoding = pick_encoding actual, expected
-
-
@actual = EncodedString.new(actual, @encoding)
-
@expected = EncodedString.new(expected, @encoding)
-
-
output = EncodedString.new("\n", @encoding)
-
-
hunks.each_cons(2) do |prev_hunk, current_hunk|
-
begin
-
if current_hunk.overlaps?(prev_hunk)
-
add_old_hunk_to_hunk(current_hunk, prev_hunk)
-
else
-
add_to_output(output, prev_hunk.diff(format).to_s)
-
end
-
ensure
-
add_to_output(output, "\n")
-
end
-
end
-
-
if hunks.last
-
finalize_output(output, hunks.last.diff(format).to_s)
-
end
-
-
color_diff output
-
rescue Encoding::CompatibilityError
-
handle_encoding_errors
-
end
-
-
1
def diff_as_object(actual, expected)
-
actual_as_string = object_to_string(actual)
-
expected_as_string = object_to_string(expected)
-
diff_as_string(actual_as_string, expected_as_string)
-
end
-
-
1
attr_reader :color
-
1
alias_method :color?, :color
-
-
1
def initialize(opts={})
-
@color = opts.fetch(:color, false)
-
@object_preparer = opts.fetch(:object_preparer, lambda { |string| string })
-
end
-
-
1
private
-
-
1
def no_procs?(*args)
-
args.flatten.none? { |a| Proc === a}
-
end
-
-
1
def all_strings?(*args)
-
args.flatten.all? { |a| String === a}
-
end
-
-
1
def any_multiline_strings?(*args)
-
all_strings?(*args) && args.flatten.any? { |a| multiline?(a) }
-
end
-
-
1
def no_numbers?(*args)
-
args.flatten.none? { |a| Numeric === a}
-
end
-
-
1
def coerce_to_string(string_or_array)
-
return string_or_array unless Array === string_or_array
-
diffably_stringify(string_or_array).join("\n")
-
end
-
-
1
def diffably_stringify(array)
-
array.map do |entry|
-
if Array === entry
-
entry.inspect
-
else
-
entry.to_s.gsub("\n", "\\n")
-
end
-
end
-
end
-
-
1
if String.method_defined?(:encoding)
-
1
def multiline?(string)
-
string.include?("\n".encode(string.encoding))
-
end
-
else
-
def multiline?(string)
-
string.include?("\n")
-
end
-
end
-
-
1
def hunks
-
@hunks ||= HunkGenerator.new(@actual, @expected).hunks
-
end
-
-
1
def finalize_output(output, final_line)
-
add_to_output(output, final_line)
-
add_to_output(output, "\n")
-
end
-
-
1
def add_to_output(output, string)
-
output << string
-
end
-
-
1
def add_old_hunk_to_hunk(hunk, oldhunk)
-
hunk.merge(oldhunk)
-
end
-
-
1
def format
-
:unified
-
end
-
-
1
def color(text, color_code)
-
"\e[#{color_code}m#{text}\e[0m"
-
end
-
-
1
def red(text)
-
color(text, 31)
-
end
-
-
1
def green(text)
-
color(text, 32)
-
end
-
-
1
def blue(text)
-
color(text, 34)
-
end
-
-
1
def normal(text)
-
color(text, 0)
-
end
-
-
1
def color_diff(diff)
-
return diff unless color?
-
-
diff.lines.map { |line|
-
case line[0].chr
-
when "+"
-
green line
-
when "-"
-
red line
-
when "@"
-
line[1].chr == "@" ? blue(line) : normal(line)
-
else
-
normal(line)
-
end
-
}.join
-
end
-
-
1
def object_to_string(object)
-
object = @object_preparer.call(object)
-
case object
-
when Hash
-
object.keys.sort_by { |k| k.to_s }.map do |key|
-
pp_key = PP.singleline_pp(key, "")
-
pp_value = PP.singleline_pp(object[key], "")
-
-
"#{pp_key} => #{pp_value},"
-
end.join("\n")
-
when String
-
object =~ /\n/ ? object : object.inspect
-
else
-
PP.pp(object,"")
-
end
-
end
-
-
1
if String.method_defined?(:encoding)
-
1
def pick_encoding(source_a, source_b)
-
Encoding.compatible?(source_a, source_b) || Encoding.default_external
-
end
-
else
-
def pick_encoding(source_a, source_b)
-
end
-
end
-
-
1
def handle_encoding_errors
-
if @actual.source_encoding != @expected.source_encoding
-
"Could not produce a diff because the encoding of the actual string (#{@actual.source_encoding}) "+
-
"differs from the encoding of the expected string (#{@expected.source_encoding})"
-
else
-
"Could not produce a diff because of the encoding of the string (#{@expected.source_encoding})"
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Support
-
# @private
-
1
class EncodedString
-
-
1
MRI_UNICODE_UNKOWN_CHARACTER = "\xEF\xBF\xBD"
-
-
1
def initialize(string, encoding = nil)
-
@encoding = encoding
-
@source_encoding = detect_source_encoding(string)
-
@string = matching_encoding(string)
-
end
-
1
attr_reader :source_encoding
-
-
1
delegated_methods = String.instance_methods.map(&:to_s) & %w[eql? lines == encoding empty?]
-
1
delegated_methods.each do |name|
-
5
define_method(name) { |*args, &block| @string.__send__(name, *args, &block) }
-
end
-
-
1
def <<(string)
-
@string << matching_encoding(string)
-
end
-
-
1
def split(regex_or_string)
-
@string.split(matching_encoding(regex_or_string))
-
end
-
-
1
def to_s
-
@string
-
end
-
1
alias :to_str :to_s
-
-
1
private
-
-
1
if String.method_defined?(:encoding)
-
1
def matching_encoding(string)
-
string.encode(@encoding)
-
rescue Encoding::UndefinedConversionError, Encoding::InvalidByteSequenceError
-
normalize_missing(string.encode(@encoding, :invalid => :replace, :undef => :replace))
-
rescue Encoding::ConverterNotFoundError
-
normalize_missing(string.force_encoding(@encoding).encode(:invalid => :replace))
-
end
-
-
1
def normalize_missing(string)
-
if @encoding.to_s == "UTF-8"
-
string.gsub(MRI_UNICODE_UNKOWN_CHARACTER.force_encoding(@encoding), "?")
-
else
-
string
-
end
-
end
-
-
1
def detect_source_encoding(string)
-
string.encoding
-
end
-
else
-
def matching_encoding(string)
-
string
-
end
-
-
def detect_source_encoding(string)
-
'US-ASCII'
-
end
-
end
-
end
-
end
-
end
-
1
module RSpec
-
1
module Support
-
# Provides a means to fuzzy-match between two arbitrary objects.
-
# Understands array/hash nesting. Uses `===` or `==` to
-
# perform the matching.
-
1
module FuzzyMatcher
-
# @api private
-
1
def self.values_match?(expected, actual)
-
if Array === expected && Enumerable === actual
-
return arrays_match?(expected, actual.to_a)
-
elsif Hash === expected && Hash === actual
-
return hashes_match?(expected, actual)
-
elsif actual == expected
-
return true
-
end
-
-
begin
-
expected === actual
-
rescue ArgumentError
-
# Some objects, like 0-arg lambdas on 1.9+, raise
-
# ArgumentError for `expected === actual`.
-
false
-
end
-
end
-
-
# @private
-
1
def self.arrays_match?(expected_list, actual_list)
-
return false if expected_list.size != actual_list.size
-
-
expected_list.zip(actual_list).all? do |expected, actual|
-
values_match?(expected, actual)
-
end
-
end
-
-
# @private
-
1
def self.hashes_match?(expected_hash, actual_hash)
-
return false if expected_hash.size != actual_hash.size
-
-
expected_hash.all? do |expected_key, expected_value|
-
actual_value = actual_hash.fetch(expected_key) { return false }
-
values_match?(expected_value, actual_value)
-
end
-
end
-
-
1
private_class_method :arrays_match?, :hashes_match?
-
end
-
end
-
end
-
-
1
require 'diff/lcs'
-
1
require 'diff/lcs/hunk'
-
-
1
module RSpec
-
1
module Support
-
# @private
-
1
class HunkGenerator
-
1
def initialize(actual, expected)
-
@actual = actual
-
@expected = expected
-
end
-
-
1
def hunks
-
@file_length_difference = 0
-
@hunks ||= diffs.map do |piece|
-
build_hunk(piece)
-
end
-
end
-
-
1
private
-
-
1
def diffs
-
Diff::LCS.diff(expected_lines, actual_lines)
-
end
-
-
1
def expected_lines
-
@expected.split("\n").map! { |e| e.chomp }
-
end
-
-
1
def actual_lines
-
@actual.split("\n").map! { |e| e.chomp }
-
end
-
-
1
def build_hunk(piece)
-
Diff::LCS::Hunk.new(
-
expected_lines, actual_lines, piece, context_lines, @file_length_difference
-
).tap do |h|
-
@file_length_difference = h.file_length_difference
-
end
-
end
-
-
1
def context_lines
-
3
-
end
-
-
end
-
end
-
end
-
1
dir = File.dirname(__FILE__)
-
1
$LOAD_PATH.unshift dir unless $LOAD_PATH.include?(dir)
-
-
# This is necessary to set so that the Haml code that tries to load Sass
-
# knows that Sass is indeed loading,
-
# even if there's some crazy autoload stuff going on.
-
1
SASS_BEGUN_TO_LOAD = true unless defined?(SASS_BEGUN_TO_LOAD)
-
-
1
require 'sass/version'
-
-
# The module that contains everything Sass-related:
-
#
-
# * {Sass::Engine} is the class used to render Sass/SCSS within Ruby code.
-
# * {Sass::Plugin} is interfaces with web frameworks (Rails and Merb in particular).
-
# * {Sass::SyntaxError} is raised when Sass encounters an error.
-
# * {Sass::CSS} handles conversion of CSS to Sass.
-
#
-
# Also see the {file:SASS_REFERENCE.md full Sass reference}.
-
1
module Sass
-
# The global load paths for Sass files. This is meant for plugins and
-
# libraries to register the paths to their Sass stylesheets to that they may
-
# be `@imported`. This load path is used by every instance of [Sass::Engine].
-
# They are lower-precedence than any load paths passed in via the
-
# {file:SASS_REFERENCE.md#load_paths-option `:load_paths` option}.
-
#
-
# If the `SASS_PATH` environment variable is set,
-
# the initial value of `load_paths` will be initialized based on that.
-
# The variable should be a colon-separated list of path names
-
# (semicolon-separated on Windows).
-
#
-
# Note that files on the global load path are never compiled to CSS
-
# themselves, even if they aren't partials. They exist only to be imported.
-
#
-
# @example
-
# Sass.load_paths << File.dirname(__FILE__ + '/sass')
-
# @return [Array<String, Pathname, Sass::Importers::Base>]
-
1
def self.load_paths
-
@load_paths ||= ENV['SASS_PATH'] ?
-
ENV['SASS_PATH'].split(Sass::Util.windows? ? ';' : ':') : []
-
end
-
-
# Compile a Sass or SCSS string to CSS.
-
# Defaults to SCSS.
-
#
-
# @param contents [String] The contents of the Sass file.
-
# @param options [{Symbol => Object}] An options hash;
-
# see {file:SASS_REFERENCE.md#sass_options the Sass options documentation}
-
# @raise [Sass::SyntaxError] if there's an error in the document
-
# @raise [Encoding::UndefinedConversionError] if the source encoding
-
# cannot be converted to UTF-8
-
# @raise [ArgumentError] if the document uses an unknown encoding with `@charset`
-
1
def self.compile(contents, options = {})
-
options[:syntax] ||= :scss
-
Engine.new(contents, options).to_css
-
end
-
-
# Compile a file on disk to CSS.
-
#
-
# @param filename [String] The path to the Sass, SCSS, or CSS file on disk.
-
# @param options [{Symbol => Object}] An options hash;
-
# see {file:SASS_REFERENCE.md#sass_options the Sass options documentation}
-
# @raise [Sass::SyntaxError] if there's an error in the document
-
# @raise [Encoding::UndefinedConversionError] if the source encoding
-
# cannot be converted to UTF-8
-
# @raise [ArgumentError] if the document uses an unknown encoding with `@charset`
-
#
-
# @overload compile_file(filename, options = {})
-
# Return the compiled CSS rather than writing it to a file.
-
#
-
# @return [String] The compiled CSS.
-
#
-
# @overload compile_file(filename, css_filename, options = {})
-
# Write the compiled CSS to a file.
-
#
-
# @param css_filename [String] The location to which to write the compiled CSS.
-
1
def self.compile_file(filename, *args)
-
options = args.last.is_a?(Hash) ? args.pop : {}
-
css_filename = args.shift
-
result = Sass::Engine.for_file(filename, options).render
-
if css_filename
-
options[:css_filename] ||= css_filename
-
open(css_filename,"w") {|css_file| css_file.write(result)}
-
nil
-
else
-
result
-
end
-
end
-
end
-
-
1
require 'sass/logger'
-
1
require 'sass/util'
-
-
1
require 'sass/engine'
-
1
require 'sass/plugin' if defined?(Merb::Plugins)
-
1
require 'sass/railtie'
-
1
require 'stringio'
-
-
1
module Sass
-
# Sass cache stores are in charge of storing cached information,
-
# especially parse trees for Sass documents.
-
#
-
# User-created importers must inherit from {CacheStores::Base}.
-
1
module CacheStores
-
end
-
end
-
-
1
require 'sass/cache_stores/base'
-
1
require 'sass/cache_stores/filesystem'
-
1
require 'sass/cache_stores/memory'
-
1
require 'sass/cache_stores/chain'
-
1
module Sass
-
1
module CacheStores
-
# An abstract base class for backends for the Sass cache.
-
# Any key-value store can act as such a backend;
-
# it just needs to implement the
-
# \{#_store} and \{#_retrieve} methods.
-
#
-
# To use a cache store with Sass,
-
# use the {file:SASS_REFERENCE.md#cache_store-option `:cache_store` option}.
-
#
-
# @abstract
-
1
class Base
-
# Store cached contents for later retrieval
-
# Must be implemented by all CacheStore subclasses
-
#
-
# Note: cache contents contain binary data.
-
#
-
# @param key [String] The key to store the contents under
-
# @param version [String] The current sass version.
-
# Cached contents must not be retrieved across different versions of sass.
-
# @param sha [String] The sha of the sass source.
-
# Cached contents must not be retrieved if the sha has changed.
-
# @param contents [String] The contents to store.
-
1
def _store(key, version, sha, contents)
-
raise "#{self.class} must implement #_store."
-
end
-
-
# Retrieved cached contents.
-
# Must be implemented by all subclasses.
-
#
-
# Note: if the key exists but the sha or version have changed,
-
# then the key may be deleted by the cache store, if it wants to do so.
-
#
-
# @param key [String] The key to retrieve
-
# @param version [String] The current sass version.
-
# Cached contents must not be retrieved across different versions of sass.
-
# @param sha [String] The sha of the sass source.
-
# Cached contents must not be retrieved if the sha has changed.
-
# @return [String] The contents that were previously stored.
-
# @return [NilClass] when the cache key is not found or the version or sha have changed.
-
1
def _retrieve(key, version, sha)
-
raise "#{self.class} must implement #_retrieve."
-
end
-
-
# Store a {Sass::Tree::RootNode}.
-
#
-
# @param key [String] The key to store it under.
-
# @param sha [String] The checksum for the contents that are being stored.
-
# @param obj [Object] The object to cache.
-
1
def store(key, sha, root)
-
_store(key, Sass::VERSION, sha, Marshal.dump(root))
-
rescue TypeError, LoadError => e
-
Sass::Util.sass_warn "Warning. Error encountered while saving cache #{path_to(key)}: #{e}"
-
nil
-
end
-
-
# Retrieve a {Sass::Tree::RootNode}.
-
#
-
# @param key [String] The key the root element was stored under.
-
# @param sha [String] The checksum of the root element's content.
-
# @return [Object] The cached object.
-
1
def retrieve(key, sha)
-
contents = _retrieve(key, Sass::VERSION, sha)
-
Marshal.load(contents) if contents
-
rescue EOFError, TypeError, ArgumentError, LoadError => e
-
Sass::Util.sass_warn "Warning. Error encountered while reading cache #{path_to(key)}: #{e}"
-
nil
-
end
-
-
# Return the key for the sass file.
-
#
-
# The `(sass_dirname, sass_basename)` pair
-
# should uniquely identify the Sass document,
-
# but otherwise there are no restrictions on their content.
-
#
-
# @param sass_dirname [String]
-
# The fully-expanded location of the Sass file.
-
# This corresponds to the directory name on a filesystem.
-
# @param sass_basename [String] The name of the Sass file that is being referenced.
-
# This corresponds to the basename on a filesystem.
-
1
def key(sass_dirname, sass_basename)
-
dir = Digest::SHA1.hexdigest(sass_dirname)
-
filename = "#{sass_basename}c"
-
"#{dir}/#{filename}"
-
end
-
end
-
end
-
end
-
1
module Sass
-
1
module CacheStores
-
# A meta-cache that chains multiple caches together.
-
# Specifically:
-
#
-
# * All `#store`s are passed to all caches.
-
# * `#retrieve`s are passed to each cache until one has a hit.
-
# * When one cache has a hit, the value is `#store`d in all earlier caches.
-
1
class Chain < Base
-
# Create a new cache chaining the given caches.
-
#
-
# @param caches [Array<Sass::CacheStores::Base>] The caches to chain.
-
1
def initialize(*caches)
-
@caches = caches
-
end
-
-
# @see Base#store
-
1
def store(key, sha, obj)
-
@caches.each {|c| c.store(key, sha, obj)}
-
end
-
-
# @see Base#retrieve
-
1
def retrieve(key, sha)
-
@caches.each_with_index do |c, i|
-
next unless obj = c.retrieve(key, sha)
-
@caches[0...i].each {|prev| prev.store(key, sha, obj)}
-
return obj
-
end
-
nil
-
end
-
end
-
end
-
end
-
1
require 'fileutils'
-
-
1
module Sass
-
1
module CacheStores
-
# A backend for the Sass cache using the filesystem.
-
1
class Filesystem < Base
-
# The directory where the cached files will be stored.
-
#
-
# @return [String]
-
1
attr_accessor :cache_location
-
-
# @param cache_location [String] see \{#cache\_location}
-
1
def initialize(cache_location)
-
@cache_location = cache_location
-
end
-
-
# @see Base#\_retrieve
-
1
def _retrieve(key, version, sha)
-
return unless File.readable?(path_to(key))
-
File.open(path_to(key), "rb") do |f|
-
if f.readline("\n").strip == version && f.readline("\n").strip == sha
-
return f.read
-
end
-
end
-
begin
-
File.unlink path_to(key)
-
rescue Errno::ENOENT
-
# Already deleted. Race condition?
-
end
-
nil
-
rescue EOFError, TypeError, ArgumentError => e
-
Sass::Util.sass_warn "Warning. Error encountered while reading cache #{path_to(key)}: #{e}"
-
end
-
-
# @see Base#\_store
-
1
def _store(key, version, sha, contents)
-
# return unless File.writable?(File.dirname(@cache_location))
-
# return if File.exists?(@cache_location) && !File.writable?(@cache_location)
-
compiled_filename = path_to(key)
-
# return if File.exists?(File.dirname(compiled_filename)) && !File.writable?(File.dirname(compiled_filename))
-
# return if File.exists?(compiled_filename) && !File.writable?(compiled_filename)
-
FileUtils.mkdir_p(File.dirname(compiled_filename))
-
Sass::Util.atomic_create_and_write_file(compiled_filename, 0600) do |f|
-
f.puts(version)
-
f.puts(sha)
-
f.write(contents)
-
end
-
rescue Errno::EACCES
-
#pass
-
end
-
-
1
private
-
-
# Returns the path to a file for the given key.
-
#
-
# @param key [String]
-
# @return [String] The path to the cache file.
-
1
def path_to(key)
-
key = key.gsub(/[<>:\\|?*%]/) {|c| "%%%03d" % Sass::Util.ord(c)}
-
File.join(cache_location, key)
-
end
-
end
-
end
-
end
-
1
module Sass
-
1
module CacheStores
-
# A backend for the Sass cache using in-process memory.
-
1
class Memory < Base
-
# Since the {Memory} store is stored in the Sass tree's options hash,
-
# when the options get serialized as part of serializing the tree,
-
# you get crazy exponential growth in the size of the cached objects
-
# unless you don't dump the cache.
-
#
-
# @private
-
1
def _dump(depth)
-
""
-
end
-
-
# If we deserialize this class, just make a new empty one.
-
#
-
# @private
-
1
def self._load(repr)
-
Memory.new
-
end
-
-
# Create a new, empty cache store.
-
1
def initialize
-
@contents = {}
-
end
-
-
# @see Base#retrieve
-
1
def retrieve(key, sha)
-
if @contents.has_key?(key)
-
return unless @contents[key][:sha] == sha
-
obj = @contents[key][:obj]
-
obj.respond_to?(:deep_copy) ? obj.deep_copy : obj.dup
-
end
-
end
-
-
# @see Base#store
-
1
def store(key, sha, obj)
-
@contents[key] = {:sha => sha, :obj => obj}
-
end
-
-
# Destructively clear the cache.
-
1
def reset!
-
@contents = {}
-
end
-
end
-
end
-
end
-
1
require 'set'
-
1
require 'digest/sha1'
-
1
require 'sass/cache_stores'
-
1
require 'sass/tree/node'
-
1
require 'sass/tree/root_node'
-
1
require 'sass/tree/rule_node'
-
1
require 'sass/tree/comment_node'
-
1
require 'sass/tree/prop_node'
-
1
require 'sass/tree/directive_node'
-
1
require 'sass/tree/media_node'
-
1
require 'sass/tree/supports_node'
-
1
require 'sass/tree/css_import_node'
-
1
require 'sass/tree/variable_node'
-
1
require 'sass/tree/mixin_def_node'
-
1
require 'sass/tree/mixin_node'
-
1
require 'sass/tree/trace_node'
-
1
require 'sass/tree/content_node'
-
1
require 'sass/tree/function_node'
-
1
require 'sass/tree/return_node'
-
1
require 'sass/tree/extend_node'
-
1
require 'sass/tree/if_node'
-
1
require 'sass/tree/while_node'
-
1
require 'sass/tree/for_node'
-
1
require 'sass/tree/each_node'
-
1
require 'sass/tree/debug_node'
-
1
require 'sass/tree/warn_node'
-
1
require 'sass/tree/import_node'
-
1
require 'sass/tree/charset_node'
-
1
require 'sass/tree/visitors/base'
-
1
require 'sass/tree/visitors/perform'
-
1
require 'sass/tree/visitors/cssize'
-
1
require 'sass/tree/visitors/extend'
-
1
require 'sass/tree/visitors/convert'
-
1
require 'sass/tree/visitors/to_css'
-
1
require 'sass/tree/visitors/deep_copy'
-
1
require 'sass/tree/visitors/set_options'
-
1
require 'sass/tree/visitors/check_nesting'
-
1
require 'sass/selector'
-
1
require 'sass/environment'
-
1
require 'sass/script'
-
1
require 'sass/scss'
-
1
require 'sass/error'
-
1
require 'sass/importers'
-
1
require 'sass/shared'
-
1
require 'sass/media'
-
1
require 'sass/supports'
-
-
1
module Sass
-
-
# A Sass mixin or function.
-
#
-
# `name`: `String`
-
# : The name of the mixin/function.
-
#
-
# `args`: `Array<(Script::Node, Script::Node)>`
-
# : The arguments for the mixin/function.
-
# Each element is a tuple containing the variable node of the argument
-
# and the parse tree for the default value of the argument.
-
#
-
# `splat`: `Script::Node?`
-
# : The variable node of the splat argument for this callable, or null.
-
#
-
# `environment`: {Sass::Environment}
-
# : The environment in which the mixin/function was defined.
-
# This is captured so that the mixin/function can have access
-
# to local variables defined in its scope.
-
#
-
# `tree`: `Array<Tree::Node>`
-
# : The parse tree for the mixin/function.
-
#
-
# `has_content`: `Boolean`
-
# : Whether the callable accepts a content block.
-
#
-
# `type`: `String`
-
# : The user-friendly name of the type of the callable.
-
1
Callable = Struct.new(:name, :args, :splat, :environment, :tree, :has_content, :type)
-
-
# This class handles the parsing and compilation of the Sass template.
-
# Example usage:
-
#
-
# template = File.load('stylesheets/sassy.sass')
-
# sass_engine = Sass::Engine.new(template)
-
# output = sass_engine.render
-
# puts output
-
1
class Engine
-
1
include Sass::Util
-
-
# A line of Sass code.
-
#
-
# `text`: `String`
-
# : The text in the line, without any whitespace at the beginning or end.
-
#
-
# `tabs`: `Fixnum`
-
# : The level of indentation of the line.
-
#
-
# `index`: `Fixnum`
-
# : The line number in the original document.
-
#
-
# `offset`: `Fixnum`
-
# : The number of bytes in on the line that the text begins.
-
# This ends up being the number of bytes of leading whitespace.
-
#
-
# `filename`: `String`
-
# : The name of the file in which this line appeared.
-
#
-
# `children`: `Array<Line>`
-
# : The lines nested below this one.
-
#
-
# `comment_tab_str`: `String?`
-
# : The prefix indentation for this comment, if it is a comment.
-
1
class Line < Struct.new(:text, :tabs, :index, :offset, :filename, :children, :comment_tab_str)
-
1
def comment?
-
text[0] == COMMENT_CHAR && (text[1] == SASS_COMMENT_CHAR || text[1] == CSS_COMMENT_CHAR)
-
end
-
end
-
-
# The character that begins a CSS property.
-
1
PROPERTY_CHAR = ?:
-
-
# The character that designates the beginning of a comment,
-
# either Sass or CSS.
-
1
COMMENT_CHAR = ?/
-
-
# The character that follows the general COMMENT_CHAR and designates a Sass comment,
-
# which is not output as a CSS comment.
-
1
SASS_COMMENT_CHAR = ?/
-
-
# The character that indicates that a comment allows interpolation
-
# and should be preserved even in `:compressed` mode.
-
1
SASS_LOUD_COMMENT_CHAR = ?!
-
-
# The character that follows the general COMMENT_CHAR and designates a CSS comment,
-
# which is embedded in the CSS document.
-
1
CSS_COMMENT_CHAR = ?*
-
-
# The character used to denote a compiler directive.
-
1
DIRECTIVE_CHAR = ?@
-
-
# Designates a non-parsed rule.
-
1
ESCAPE_CHAR = ?\\
-
-
# Designates block as mixin definition rather than CSS rules to output
-
1
MIXIN_DEFINITION_CHAR = ?=
-
-
# Includes named mixin declared using MIXIN_DEFINITION_CHAR
-
1
MIXIN_INCLUDE_CHAR = ?+
-
-
# The regex that matches and extracts data from
-
# properties of the form `:name prop`.
-
1
PROPERTY_OLD = /^:([^\s=:"]+)\s*(?:\s+|$)(.*)/
-
-
# The default options for Sass::Engine.
-
# @api public
-
1
DEFAULT_OPTIONS = {
-
:style => :nested,
-
:load_paths => ['.'],
-
:cache => true,
-
:cache_location => './.sass-cache',
-
:syntax => :sass,
-
:filesystem_importer => Sass::Importers::Filesystem
-
}.freeze
-
-
# Converts a Sass options hash into a standard form, filling in
-
# default values and resolving aliases.
-
#
-
# @param options [{Symbol => Object}] The options hash;
-
# see {file:SASS_REFERENCE.md#sass_options the Sass options documentation}
-
# @return [{Symbol => Object}] The normalized options hash.
-
# @private
-
1
def self.normalize_options(options)
-
options = DEFAULT_OPTIONS.merge(options.reject {|k, v| v.nil?})
-
-
# If the `:filename` option is passed in without an importer,
-
# assume it's using the default filesystem importer.
-
options[:importer] ||= options[:filesystem_importer].new(".") if options[:filename]
-
-
# Tracks the original filename of the top-level Sass file
-
options[:original_filename] ||= options[:filename]
-
-
options[:cache_store] ||= Sass::CacheStores::Chain.new(
-
Sass::CacheStores::Memory.new, Sass::CacheStores::Filesystem.new(options[:cache_location]))
-
# Support both, because the docs said one and the other actually worked
-
# for quite a long time.
-
options[:line_comments] ||= options[:line_numbers]
-
-
options[:load_paths] = (options[:load_paths] + Sass.load_paths).map do |p|
-
next p unless p.is_a?(String) || (defined?(Pathname) && p.is_a?(Pathname))
-
options[:filesystem_importer].new(p.to_s)
-
end
-
-
# Backwards compatibility
-
options[:property_syntax] ||= options[:attribute_syntax]
-
case options[:property_syntax]
-
when :alternate; options[:property_syntax] = :new
-
when :normal; options[:property_syntax] = :old
-
end
-
-
options
-
end
-
-
# Returns the {Sass::Engine} for the given file.
-
# This is preferable to Sass::Engine.new when reading from a file
-
# because it properly sets up the Engine's metadata,
-
# enables parse-tree caching,
-
# and infers the syntax from the filename.
-
#
-
# @param filename [String] The path to the Sass or SCSS file
-
# @param options [{Symbol => Object}] The options hash;
-
# See {file:SASS_REFERENCE.md#sass_options the Sass options documentation}.
-
# @return [Sass::Engine] The Engine for the given Sass or SCSS file.
-
# @raise [Sass::SyntaxError] if there's an error in the document.
-
1
def self.for_file(filename, options)
-
had_syntax = options[:syntax]
-
-
if had_syntax
-
# Use what was explicitly specificed
-
elsif filename =~ /\.scss$/
-
options.merge!(:syntax => :scss)
-
elsif filename =~ /\.sass$/
-
options.merge!(:syntax => :sass)
-
end
-
-
Sass::Engine.new(File.read(filename), options.merge(:filename => filename))
-
end
-
-
# The options for the Sass engine.
-
# See {file:SASS_REFERENCE.md#sass_options the Sass options documentation}.
-
#
-
# @return [{Symbol => Object}]
-
1
attr_reader :options
-
-
# Creates a new Engine. Note that Engine should only be used directly
-
# when compiling in-memory Sass code.
-
# If you're compiling a single Sass file from the filesystem,
-
# use \{Sass::Engine.for\_file}.
-
# If you're compiling multiple files from the filesystem,
-
# use {Sass::Plugin}.
-
#
-
# @param template [String] The Sass template.
-
# This template can be encoded using any encoding
-
# that can be converted to Unicode.
-
# If the template contains an `@charset` declaration,
-
# that overrides the Ruby encoding
-
# (see {file:SASS_REFERENCE.md#encodings the encoding documentation})
-
# @param options [{Symbol => Object}] An options hash.
-
# See {file:SASS_REFERENCE.md#sass_options the Sass options documentation}.
-
# @see {Sass::Engine.for_file}
-
# @see {Sass::Plugin}
-
1
def initialize(template, options={})
-
@options = self.class.normalize_options(options)
-
@template = template
-
end
-
-
# Render the template to CSS.
-
#
-
# @return [String] The CSS
-
# @raise [Sass::SyntaxError] if there's an error in the document
-
# @raise [Encoding::UndefinedConversionError] if the source encoding
-
# cannot be converted to UTF-8
-
# @raise [ArgumentError] if the document uses an unknown encoding with `@charset`
-
1
def render
-
return _render unless @options[:quiet]
-
Sass::Util.silence_sass_warnings {_render}
-
end
-
1
alias_method :to_css, :render
-
-
# Parses the document into its parse tree. Memoized.
-
#
-
# @return [Sass::Tree::Node] The root of the parse tree.
-
# @raise [Sass::SyntaxError] if there's an error in the document
-
1
def to_tree
-
@tree ||= @options[:quiet] ?
-
Sass::Util.silence_sass_warnings {_to_tree} :
-
_to_tree
-
end
-
-
# Returns the original encoding of the document,
-
# or `nil` under Ruby 1.8.
-
#
-
# @return [Encoding, nil]
-
# @raise [Encoding::UndefinedConversionError] if the source encoding
-
# cannot be converted to UTF-8
-
# @raise [ArgumentError] if the document uses an unknown encoding with `@charset`
-
1
def source_encoding
-
check_encoding!
-
@original_encoding
-
end
-
-
# Gets a set of all the documents
-
# that are (transitive) dependencies of this document,
-
# not including the document itself.
-
#
-
# @return [[Sass::Engine]] The dependency documents.
-
1
def dependencies
-
_dependencies(Set.new, engines = Set.new)
-
Sass::Util.array_minus(engines, [self])
-
end
-
-
# Helper for \{#dependencies}.
-
#
-
# @private
-
1
def _dependencies(seen, engines)
-
return if seen.include?(key = [@options[:filename], @options[:importer]])
-
seen << key
-
engines << self
-
to_tree.grep(Tree::ImportNode) do |n|
-
next if n.css_import?
-
n.imported_file._dependencies(seen, engines)
-
end
-
end
-
-
1
private
-
-
1
def _render
-
rendered = _to_tree.render
-
return rendered if ruby1_8?
-
begin
-
# Try to convert the result to the original encoding,
-
# but if that doesn't work fall back on UTF-8
-
rendered = rendered.encode(source_encoding)
-
rescue EncodingError
-
end
-
rendered.gsub(Regexp.new('\A@charset "(.*?)"'.encode(source_encoding)),
-
"@charset \"#{source_encoding.name}\"".encode(source_encoding))
-
end
-
-
1
def _to_tree
-
if (@options[:cache] || @options[:read_cache]) &&
-
@options[:filename] && @options[:importer]
-
key = sassc_key
-
sha = Digest::SHA1.hexdigest(@template)
-
-
if root = @options[:cache_store].retrieve(key, sha)
-
root.options = @options
-
return root
-
end
-
end
-
-
check_encoding!
-
-
if @options[:syntax] == :scss
-
root = Sass::SCSS::Parser.new(@template, @options[:filename]).parse
-
else
-
root = Tree::RootNode.new(@template)
-
append_children(root, tree(tabulate(@template)).first, true)
-
end
-
-
root.options = @options
-
if @options[:cache] && key && sha
-
begin
-
old_options = root.options
-
root.options = {}
-
@options[:cache_store].store(key, sha, root)
-
ensure
-
root.options = old_options
-
end
-
end
-
root
-
rescue SyntaxError => e
-
e.modify_backtrace(:filename => @options[:filename], :line => @line)
-
e.sass_template = @template
-
raise e
-
end
-
-
1
def sassc_key
-
@options[:cache_store].key(*@options[:importer].key(@options[:filename], @options))
-
end
-
-
1
def check_encoding!
-
return if @checked_encoding
-
@checked_encoding = true
-
@template, @original_encoding = check_sass_encoding(@template) do |msg, line|
-
raise Sass::SyntaxError.new(msg, :line => line)
-
end
-
end
-
-
1
def tabulate(string)
-
tab_str = nil
-
comment_tab_str = nil
-
first = true
-
lines = []
-
string.gsub(/\r\n|\r|\n/, "\n").scan(/^[^\n]*?$/).each_with_index do |line, index|
-
index += (@options[:line] || 1)
-
if line.strip.empty?
-
lines.last.text << "\n" if lines.last && lines.last.comment?
-
next
-
end
-
-
line_tab_str = line[/^\s*/]
-
unless line_tab_str.empty?
-
if tab_str.nil?
-
comment_tab_str ||= line_tab_str
-
next if try_comment(line, lines.last, "", comment_tab_str, index)
-
comment_tab_str = nil
-
end
-
-
tab_str ||= line_tab_str
-
-
raise SyntaxError.new("Indenting at the beginning of the document is illegal.",
-
:line => index) if first
-
-
raise SyntaxError.new("Indentation can't use both tabs and spaces.",
-
:line => index) if tab_str.include?(?\s) && tab_str.include?(?\t)
-
end
-
first &&= !tab_str.nil?
-
if tab_str.nil?
-
lines << Line.new(line.strip, 0, index, 0, @options[:filename], [])
-
next
-
end
-
-
comment_tab_str ||= line_tab_str
-
if try_comment(line, lines.last, tab_str * lines.last.tabs, comment_tab_str, index)
-
next
-
else
-
comment_tab_str = nil
-
end
-
-
line_tabs = line_tab_str.scan(tab_str).size
-
if tab_str * line_tabs != line_tab_str
-
message = <<END.strip.gsub("\n", ' ')
-
Inconsistent indentation: #{Sass::Shared.human_indentation line_tab_str, true} used for indentation,
-
but the rest of the document was indented using #{Sass::Shared.human_indentation tab_str}.
-
END
-
raise SyntaxError.new(message, :line => index)
-
end
-
-
lines << Line.new(line.strip, line_tabs, index, tab_str.size, @options[:filename], [])
-
end
-
lines
-
end
-
-
1
def try_comment(line, last, tab_str, comment_tab_str, index)
-
return unless last && last.comment?
-
# Nested comment stuff must be at least one whitespace char deeper
-
# than the normal indentation
-
return unless line =~ /^#{tab_str}\s/
-
unless line =~ /^(?:#{comment_tab_str})(.*)$/
-
raise SyntaxError.new(<<MSG.strip.gsub("\n", " "), :line => index)
-
Inconsistent indentation:
-
previous line was indented by #{Sass::Shared.human_indentation comment_tab_str},
-
but this line was indented by #{Sass::Shared.human_indentation line[/^\s*/]}.
-
MSG
-
end
-
-
last.comment_tab_str ||= comment_tab_str
-
last.text << "\n" << line
-
true
-
end
-
-
1
def tree(arr, i = 0)
-
return [], i if arr[i].nil?
-
-
base = arr[i].tabs
-
nodes = []
-
while (line = arr[i]) && line.tabs >= base
-
if line.tabs > base
-
raise SyntaxError.new("The line was indented #{line.tabs - base} levels deeper than the previous line.",
-
:line => line.index) if line.tabs > base + 1
-
-
nodes.last.children, i = tree(arr, i)
-
else
-
nodes << line
-
i += 1
-
end
-
end
-
return nodes, i
-
end
-
-
1
def build_tree(parent, line, root = false)
-
@line = line.index
-
node_or_nodes = parse_line(parent, line, root)
-
-
Array(node_or_nodes).each do |node|
-
# Node is a symbol if it's non-outputting, like a variable assignment
-
next unless node.is_a? Tree::Node
-
-
node.line = line.index
-
node.filename = line.filename
-
-
append_children(node, line.children, false)
-
end
-
-
node_or_nodes
-
end
-
-
1
def append_children(parent, children, root)
-
continued_rule = nil
-
continued_comment = nil
-
children.each do |line|
-
child = build_tree(parent, line, root)
-
-
if child.is_a?(Tree::RuleNode)
-
if child.continued? && child.children.empty?
-
if continued_rule
-
continued_rule.add_rules child
-
else
-
continued_rule = child
-
end
-
next
-
elsif continued_rule
-
continued_rule.add_rules child
-
continued_rule.children = child.children
-
continued_rule, child = nil, continued_rule
-
end
-
elsif continued_rule
-
continued_rule = nil
-
end
-
-
if child.is_a?(Tree::CommentNode) && child.type == :silent
-
if continued_comment &&
-
child.line == continued_comment.line +
-
continued_comment.lines + 1
-
continued_comment.value += ["\n"] + child.value
-
next
-
end
-
-
continued_comment = child
-
end
-
-
check_for_no_children(child)
-
validate_and_append_child(parent, child, line, root)
-
end
-
-
parent
-
end
-
-
1
def validate_and_append_child(parent, child, line, root)
-
case child
-
when Array
-
child.each {|c| validate_and_append_child(parent, c, line, root)}
-
when Tree::Node
-
parent << child
-
end
-
end
-
-
1
def check_for_no_children(node)
-
return unless node.is_a?(Tree::RuleNode) && node.children.empty?
-
Sass::Util.sass_warn(<<WARNING.strip)
-
WARNING on line #{node.line}#{" of #{node.filename}" if node.filename}:
-
This selector doesn't have any properties and will not be rendered.
-
WARNING
-
end
-
-
1
def parse_line(parent, line, root)
-
case line.text[0]
-
when PROPERTY_CHAR
-
if line.text[1] == PROPERTY_CHAR ||
-
(@options[:property_syntax] == :new &&
-
line.text =~ PROPERTY_OLD && $2.empty?)
-
# Support CSS3-style pseudo-elements,
-
# which begin with ::,
-
# as well as pseudo-classes
-
# if we're using the new property syntax
-
Tree::RuleNode.new(parse_interp(line.text))
-
else
-
name, value = line.text.scan(PROPERTY_OLD)[0]
-
raise SyntaxError.new("Invalid property: \"#{line.text}\".",
-
:line => @line) if name.nil? || value.nil?
-
parse_property(name, parse_interp(name), value, :old, line)
-
end
-
when ?$
-
parse_variable(line)
-
when COMMENT_CHAR
-
parse_comment(line)
-
when DIRECTIVE_CHAR
-
parse_directive(parent, line, root)
-
when ESCAPE_CHAR
-
Tree::RuleNode.new(parse_interp(line.text[1..-1]))
-
when MIXIN_DEFINITION_CHAR
-
parse_mixin_definition(line)
-
when MIXIN_INCLUDE_CHAR
-
if line.text[1].nil? || line.text[1] == ?\s
-
Tree::RuleNode.new(parse_interp(line.text))
-
else
-
parse_mixin_include(line, root)
-
end
-
else
-
parse_property_or_rule(line)
-
end
-
end
-
-
1
def parse_property_or_rule(line)
-
scanner = Sass::Util::MultibyteStringScanner.new(line.text)
-
hack_char = scanner.scan(/[:\*\.]|\#(?!\{)/)
-
parser = Sass::SCSS::Parser.new(scanner, @options[:filename], @line)
-
-
unless res = parser.parse_interp_ident
-
return Tree::RuleNode.new(parse_interp(line.text))
-
end
-
res.unshift(hack_char) if hack_char
-
if comment = scanner.scan(Sass::SCSS::RX::COMMENT)
-
res << comment
-
end
-
-
name = line.text[0...scanner.pos]
-
if scanner.scan(/\s*:(?:\s|$)/)
-
parse_property(name, res, scanner.rest, :new, line)
-
else
-
res.pop if comment
-
Tree::RuleNode.new(res + parse_interp(scanner.rest))
-
end
-
end
-
-
1
def parse_property(name, parsed_name, value, prop, line)
-
if value.strip.empty?
-
expr = Sass::Script::String.new("")
-
else
-
expr = parse_script(value, :offset => line.offset + line.text.index(value))
-
end
-
node = Tree::PropNode.new(parse_interp(name), expr, prop)
-
if value.strip.empty? && line.children.empty?
-
raise SyntaxError.new(
-
"Invalid property: \"#{node.declaration}\" (no value)." +
-
node.pseudo_class_selector_message)
-
end
-
-
node
-
end
-
-
1
def parse_variable(line)
-
name, value, default = line.text.scan(Script::MATCH)[0]
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath variable declarations.",
-
:line => @line + 1) unless line.children.empty?
-
raise SyntaxError.new("Invalid variable: \"#{line.text}\".",
-
:line => @line) unless name && value
-
-
expr = parse_script(value, :offset => line.offset + line.text.index(value))
-
-
Tree::VariableNode.new(name, expr, default)
-
end
-
-
1
def parse_comment(line)
-
if line.text[1] == CSS_COMMENT_CHAR || line.text[1] == SASS_COMMENT_CHAR
-
silent = line.text[1] == SASS_COMMENT_CHAR
-
loud = !silent && line.text[2] == SASS_LOUD_COMMENT_CHAR
-
if silent
-
value = [line.text]
-
else
-
value = self.class.parse_interp(line.text, line.index, line.offset, :filename => @filename)
-
end
-
value = with_extracted_values(value) do |str|
-
str = str.gsub(/^#{line.comment_tab_str}/m, '')[2..-1] # get rid of // or /*
-
format_comment_text(str, silent)
-
end
-
type = if silent then :silent elsif loud then :loud else :normal end
-
Tree::CommentNode.new(value, type)
-
else
-
Tree::RuleNode.new(parse_interp(line.text))
-
end
-
end
-
-
1
def parse_directive(parent, line, root)
-
directive, whitespace, value = line.text[1..-1].split(/(\s+)/, 2)
-
offset = directive.size + whitespace.size + 1 if whitespace
-
-
# If value begins with url( or ",
-
# it's a CSS @import rule and we don't want to touch it.
-
case directive
-
when 'import'
-
parse_import(line, value, offset)
-
when 'mixin'
-
parse_mixin_definition(line)
-
when 'content'
-
parse_content_directive(line)
-
when 'include'
-
parse_mixin_include(line, root)
-
when 'function'
-
parse_function(line, root)
-
when 'for'
-
parse_for(line, root, value)
-
when 'each'
-
parse_each(line, root, value)
-
when 'else'
-
parse_else(parent, line, value)
-
when 'while'
-
raise SyntaxError.new("Invalid while directive '@while': expected expression.") unless value
-
Tree::WhileNode.new(parse_script(value, :offset => offset))
-
when 'if'
-
raise SyntaxError.new("Invalid if directive '@if': expected expression.") unless value
-
Tree::IfNode.new(parse_script(value, :offset => offset))
-
when 'debug'
-
raise SyntaxError.new("Invalid debug directive '@debug': expected expression.") unless value
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath debug directives.",
-
:line => @line + 1) unless line.children.empty?
-
offset = line.offset + line.text.index(value).to_i
-
Tree::DebugNode.new(parse_script(value, :offset => offset))
-
when 'extend'
-
raise SyntaxError.new("Invalid extend directive '@extend': expected expression.") unless value
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath extend directives.",
-
:line => @line + 1) unless line.children.empty?
-
optional = !!value.gsub!(/\s+#{Sass::SCSS::RX::OPTIONAL}$/, '')
-
offset = line.offset + line.text.index(value).to_i
-
Tree::ExtendNode.new(parse_interp(value, offset), optional)
-
when 'warn'
-
raise SyntaxError.new("Invalid warn directive '@warn': expected expression.") unless value
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath warn directives.",
-
:line => @line + 1) unless line.children.empty?
-
offset = line.offset + line.text.index(value).to_i
-
Tree::WarnNode.new(parse_script(value, :offset => offset))
-
when 'return'
-
raise SyntaxError.new("Invalid @return: expected expression.") unless value
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath return directives.",
-
:line => @line + 1) unless line.children.empty?
-
offset = line.offset + line.text.index(value).to_i
-
Tree::ReturnNode.new(parse_script(value, :offset => offset))
-
when 'charset'
-
name = value && value[/\A(["'])(.*)\1\Z/, 2] #"
-
raise SyntaxError.new("Invalid charset directive '@charset': expected string.") unless name
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath charset directives.",
-
:line => @line + 1) unless line.children.empty?
-
Tree::CharsetNode.new(name)
-
when 'media'
-
parser = Sass::SCSS::Parser.new(value, @options[:filename], @line)
-
Tree::MediaNode.new(parser.parse_media_query_list.to_a)
-
when nil
-
raise SyntaxError.new("Invalid directive: '@'.")
-
else
-
unprefixed_directive = directive.gsub(/^-[a-z0-9]+-/i, '')
-
if unprefixed_directive == 'supports'
-
parser = Sass::SCSS::Parser.new(value, @options[:filename], @line)
-
return Tree::SupportsNode.new(directive, parser.parse_supports_condition)
-
end
-
-
Tree::DirectiveNode.new(
-
value.nil? ? ["@#{directive}"] : ["@#{directive} "] + parse_interp(value, offset))
-
end
-
end
-
-
1
def parse_for(line, root, text)
-
var, from_expr, to_name, to_expr = text.scan(/^([^\s]+)\s+from\s+(.+)\s+(to|through)\s+(.+)$/).first
-
-
if var.nil? # scan failed, try to figure out why for error message
-
if text !~ /^[^\s]+/
-
expected = "variable name"
-
elsif text !~ /^[^\s]+\s+from\s+.+/
-
expected = "'from <expr>'"
-
else
-
expected = "'to <expr>' or 'through <expr>'"
-
end
-
raise SyntaxError.new("Invalid for directive '@for #{text}': expected #{expected}.")
-
end
-
raise SyntaxError.new("Invalid variable \"#{var}\".") unless var =~ Script::VALIDATE
-
-
var = var[1..-1]
-
parsed_from = parse_script(from_expr, :offset => line.offset + line.text.index(from_expr))
-
parsed_to = parse_script(to_expr, :offset => line.offset + line.text.index(to_expr))
-
Tree::ForNode.new(var, parsed_from, parsed_to, to_name == 'to')
-
end
-
-
1
def parse_each(line, root, text)
-
var, list_expr = text.scan(/^([^\s]+)\s+in\s+(.+)$/).first
-
-
if var.nil? # scan failed, try to figure out why for error message
-
if text !~ /^[^\s]+/
-
expected = "variable name"
-
elsif text !~ /^[^\s]+\s+from\s+.+/
-
expected = "'in <expr>'"
-
end
-
raise SyntaxError.new("Invalid for directive '@each #{text}': expected #{expected}.")
-
end
-
raise SyntaxError.new("Invalid variable \"#{var}\".") unless var =~ Script::VALIDATE
-
-
var = var[1..-1]
-
parsed_list = parse_script(list_expr, :offset => line.offset + line.text.index(list_expr))
-
Tree::EachNode.new(var, parsed_list)
-
end
-
-
1
def parse_else(parent, line, text)
-
previous = parent.children.last
-
raise SyntaxError.new("@else must come after @if.") unless previous.is_a?(Tree::IfNode)
-
-
if text
-
if text !~ /^if\s+(.+)/
-
raise SyntaxError.new("Invalid else directive '@else #{text}': expected 'if <expr>'.")
-
end
-
expr = parse_script($1, :offset => line.offset + line.text.index($1))
-
end
-
-
node = Tree::IfNode.new(expr)
-
append_children(node, line.children, false)
-
previous.add_else node
-
nil
-
end
-
-
1
def parse_import(line, value, offset)
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath import directives.",
-
:line => @line + 1) unless line.children.empty?
-
-
scanner = Sass::Util::MultibyteStringScanner.new(value)
-
values = []
-
-
loop do
-
unless node = parse_import_arg(scanner, offset + scanner.pos)
-
raise SyntaxError.new("Invalid @import: expected file to import, was #{scanner.rest.inspect}",
-
:line => @line)
-
end
-
values << node
-
break unless scanner.scan(/,\s*/)
-
end
-
-
if scanner.scan(/;/)
-
raise SyntaxError.new("Invalid @import: expected end of line, was \";\".",
-
:line => @line)
-
end
-
-
return values
-
end
-
-
1
def parse_import_arg(scanner, offset)
-
return if scanner.eos?
-
-
if scanner.match?(/url\(/i)
-
script_parser = Sass::Script::Parser.new(scanner, @line, offset, @options)
-
str = script_parser.parse_string
-
media_parser = Sass::SCSS::Parser.new(scanner, @options[:filename], @line)
-
media = media_parser.parse_media_query_list
-
return Tree::CssImportNode.new(str, media.to_a)
-
end
-
-
unless str = scanner.scan(Sass::SCSS::RX::STRING)
-
return Tree::ImportNode.new(scanner.scan(/[^,;]+/))
-
end
-
-
val = scanner[1] || scanner[2]
-
scanner.scan(/\s*/)
-
if !scanner.match?(/[,;]|$/)
-
media_parser = Sass::SCSS::Parser.new(scanner, @options[:filename], @line)
-
media = media_parser.parse_media_query_list
-
Tree::CssImportNode.new(str || uri, media.to_a)
-
elsif val =~ /^(https?:)?\/\//
-
Tree::CssImportNode.new("url(#{val})")
-
else
-
Tree::ImportNode.new(val)
-
end
-
end
-
-
1
MIXIN_DEF_RE = /^(?:=|@mixin)\s*(#{Sass::SCSS::RX::IDENT})(.*)$/
-
1
def parse_mixin_definition(line)
-
name, arg_string = line.text.scan(MIXIN_DEF_RE).first
-
raise SyntaxError.new("Invalid mixin \"#{line.text[1..-1]}\".") if name.nil?
-
-
offset = line.offset + line.text.size - arg_string.size
-
args, splat = Script::Parser.new(arg_string.strip, @line, offset, @options).
-
parse_mixin_definition_arglist
-
Tree::MixinDefNode.new(name, args, splat)
-
end
-
-
1
CONTENT_RE = /^@content\s*(.+)?$/
-
1
def parse_content_directive(line)
-
trailing = line.text.scan(CONTENT_RE).first.first
-
raise SyntaxError.new("Invalid content directive. Trailing characters found: \"#{trailing}\".") unless trailing.nil?
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath @content directives.",
-
:line => line.index + 1) unless line.children.empty?
-
Tree::ContentNode.new
-
end
-
-
1
MIXIN_INCLUDE_RE = /^(?:\+|@include)\s*(#{Sass::SCSS::RX::IDENT})(.*)$/
-
1
def parse_mixin_include(line, root)
-
name, arg_string = line.text.scan(MIXIN_INCLUDE_RE).first
-
raise SyntaxError.new("Invalid mixin include \"#{line.text}\".") if name.nil?
-
-
offset = line.offset + line.text.size - arg_string.size
-
args, keywords, splat = Script::Parser.new(arg_string.strip, @line, offset, @options).
-
parse_mixin_include_arglist
-
Tree::MixinNode.new(name, args, keywords, splat)
-
end
-
-
1
FUNCTION_RE = /^@function\s*(#{Sass::SCSS::RX::IDENT})(.*)$/
-
1
def parse_function(line, root)
-
name, arg_string = line.text.scan(FUNCTION_RE).first
-
raise SyntaxError.new("Invalid function definition \"#{line.text}\".") if name.nil?
-
-
offset = line.offset + line.text.size - arg_string.size
-
args, splat = Script::Parser.new(arg_string.strip, @line, offset, @options).
-
parse_function_definition_arglist
-
Tree::FunctionNode.new(name, args, splat)
-
end
-
-
1
def parse_script(script, options = {})
-
line = options[:line] || @line
-
offset = options[:offset] || 0
-
Script.parse(script, line, offset, @options)
-
end
-
-
1
def format_comment_text(text, silent)
-
content = text.split("\n")
-
-
if content.first && content.first.strip.empty?
-
removed_first = true
-
content.shift
-
end
-
-
return silent ? "//" : "/* */" if content.empty?
-
content.last.gsub!(%r{ ?\*/ *$}, '')
-
content.map! {|l| l.gsub!(/^\*( ?)/, '\1') || (l.empty? ? "" : " ") + l}
-
content.first.gsub!(/^ /, '') unless removed_first
-
if silent
-
"//" + content.join("\n//")
-
else
-
# The #gsub fixes the case of a trailing */
-
"/*" + content.join("\n *").gsub(/ \*\Z/, '') + " */"
-
end
-
end
-
-
1
def parse_interp(text, offset = 0)
-
self.class.parse_interp(text, @line, offset, :filename => @filename)
-
end
-
-
# It's important that this have strings (at least)
-
# at the beginning, the end, and between each Script::Node.
-
#
-
# @private
-
1
def self.parse_interp(text, line, offset, options)
-
res = []
-
rest = Sass::Shared.handle_interpolation text do |scan|
-
escapes = scan[2].size
-
res << scan.matched[0...-2 - escapes]
-
if escapes % 2 == 1
-
res << "\\" * (escapes - 1) << '#{'
-
else
-
res << "\\" * [0, escapes - 1].max
-
res << Script::Parser.new(
-
scan, line, offset + scan.pos - scan.matched_size, options).
-
parse_interpolated
-
end
-
end
-
res << rest
-
end
-
end
-
end
-
1
require 'set'
-
-
1
module Sass
-
# The lexical environment for SassScript.
-
# This keeps track of variable, mixin, and function definitions.
-
#
-
# A new environment is created for each level of Sass nesting.
-
# This allows variables to be lexically scoped.
-
# The new environment refers to the environment in the upper scope,
-
# so it has access to variables defined in enclosing scopes,
-
# but new variables are defined locally.
-
#
-
# Environment also keeps track of the {Engine} options
-
# so that they can be made available to {Sass::Script::Functions}.
-
1
class Environment
-
# The enclosing environment,
-
# or nil if this is the global environment.
-
#
-
# @return [Environment]
-
1
attr_reader :parent
-
1
attr_reader :options
-
1
attr_writer :caller
-
1
attr_writer :content
-
-
# @param options [{Symbol => Object}] The options hash. See
-
# {file:SASS_REFERENCE.md#sass_options the Sass options documentation}.
-
# @param parent [Environment] See \{#parent}
-
1
def initialize(parent = nil, options = nil)
-
@parent = parent
-
@options = options || (parent && parent.options) || {}
-
end
-
-
# The environment of the caller of this environment's mixin or function.
-
# @return {Environment?}
-
1
def caller
-
@caller || (@parent && @parent.caller)
-
end
-
-
# The content passed to this environmnet. This is naturally only set
-
# for mixin body environments with content passed in.
-
# @return {Environment?}
-
1
def content
-
@content || (@parent && @parent.content)
-
end
-
-
1
private
-
-
1
class << self
-
1
private
-
1
UNDERSCORE, DASH = '_', '-'
-
-
# Note: when updating this,
-
# update sass/yard/inherited_hash.rb as well.
-
1
def inherited_hash(name)
-
3
class_eval <<RUBY, __FILE__, __LINE__ + 1
-
def #{name}(name)
-
_#{name}(name.tr(UNDERSCORE, DASH))
-
end
-
-
def _#{name}(name)
-
(@#{name}s && @#{name}s[name]) || @parent && @parent._#{name}(name)
-
end
-
protected :_#{name}
-
-
def set_#{name}(name, value)
-
name = name.tr(UNDERSCORE, DASH)
-
@#{name}s[name] = value unless try_set_#{name}(name, value)
-
end
-
-
def try_set_#{name}(name, value)
-
@#{name}s ||= {}
-
if @#{name}s.include?(name)
-
@#{name}s[name] = value
-
true
-
elsif @parent
-
@parent.try_set_#{name}(name, value)
-
else
-
false
-
end
-
end
-
protected :try_set_#{name}
-
-
def set_local_#{name}(name, value)
-
@#{name}s ||= {}
-
@#{name}s[name.tr(UNDERSCORE, DASH)] = value
-
end
-
RUBY
-
end
-
end
-
-
# variable
-
# Script::Literal
-
1
inherited_hash :var
-
# mixin
-
# Sass::Callable
-
1
inherited_hash :mixin
-
# function
-
# Sass::Callable
-
1
inherited_hash :function
-
end
-
end
-
1
module Sass
-
# An exception class that keeps track of
-
# the line of the Sass template it was raised on
-
# and the Sass file that was being parsed (if applicable).
-
#
-
# All Sass errors are raised as {Sass::SyntaxError}s.
-
#
-
# When dealing with SyntaxErrors,
-
# it's important to provide filename and line number information.
-
# This will be used in various error reports to users, including backtraces;
-
# see \{#sass\_backtrace} for details.
-
#
-
# Some of this information is usually provided as part of the constructor.
-
# New backtrace entries can be added with \{#add\_backtrace},
-
# which is called when an exception is raised between files (e.g. with `@import`).
-
#
-
# Often, a chunk of code will all have similar backtrace information -
-
# the same filename or even line.
-
# It may also be useful to have a default line number set.
-
# In those situations, the default values can be used
-
# by omitting the information on the original exception,
-
# and then calling \{#modify\_backtrace} in a wrapper `rescue`.
-
# When doing this, be sure that all exceptions ultimately end up
-
# with the information filled in.
-
1
class SyntaxError < StandardError
-
# The backtrace of the error within Sass files.
-
# This is an array of hashes containing information for a single entry.
-
# The hashes have the following keys:
-
#
-
# `:filename`
-
# : The name of the file in which the exception was raised,
-
# or `nil` if no filename is available.
-
#
-
# `:mixin`
-
# : The name of the mixin in which the exception was raised,
-
# or `nil` if it wasn't raised in a mixin.
-
#
-
# `:line`
-
# : The line of the file on which the error occurred. Never nil.
-
#
-
# This information is also included in standard backtrace format
-
# in the output of \{#backtrace}.
-
#
-
# @return [Aray<{Symbol => Object>}]
-
1
attr_accessor :sass_backtrace
-
-
# The text of the template where this error was raised.
-
#
-
# @return [String]
-
1
attr_accessor :sass_template
-
-
# @param msg [String] The error message
-
# @param attrs [{Symbol => Object}] The information in the backtrace entry.
-
# See \{#sass\_backtrace}
-
1
def initialize(msg, attrs = {})
-
@message = msg
-
@sass_backtrace = []
-
add_backtrace(attrs)
-
end
-
-
# The name of the file in which the exception was raised.
-
# This could be `nil` if no filename is available.
-
#
-
# @return [String, nil]
-
1
def sass_filename
-
sass_backtrace.first[:filename]
-
end
-
-
# The name of the mixin in which the error occurred.
-
# This could be `nil` if the error occurred outside a mixin.
-
#
-
# @return [Fixnum]
-
1
def sass_mixin
-
sass_backtrace.first[:mixin]
-
end
-
-
# The line of the Sass template on which the error occurred.
-
#
-
# @return [Fixnum]
-
1
def sass_line
-
sass_backtrace.first[:line]
-
end
-
-
# Adds an entry to the exception's Sass backtrace.
-
#
-
# @param attrs [{Symbol => Object}] The information in the backtrace entry.
-
# See \{#sass\_backtrace}
-
1
def add_backtrace(attrs)
-
sass_backtrace << attrs.reject {|k, v| v.nil?}
-
end
-
-
# Modify the top Sass backtrace entries
-
# (that is, the most deeply nested ones)
-
# to have the given attributes.
-
#
-
# Specifically, this goes through the backtrace entries
-
# from most deeply nested to least,
-
# setting the given attributes for each entry.
-
# If an entry already has one of the given attributes set,
-
# the pre-existing attribute takes precedence
-
# and is not used for less deeply-nested entries
-
# (even if they don't have that attribute set).
-
#
-
# @param attrs [{Symbol => Object}] The information to add to the backtrace entry.
-
# See \{#sass\_backtrace}
-
1
def modify_backtrace(attrs)
-
attrs = attrs.reject {|k, v| v.nil?}
-
# Move backwards through the backtrace
-
(0...sass_backtrace.size).to_a.reverse.each do |i|
-
entry = sass_backtrace[i]
-
sass_backtrace[i] = attrs.merge(entry)
-
attrs.reject! {|k, v| entry.include?(k)}
-
break if attrs.empty?
-
end
-
end
-
-
# @return [String] The error message
-
1
def to_s
-
@message
-
end
-
-
# Returns the standard exception backtrace,
-
# including the Sass backtrace.
-
#
-
# @return [Array<String>]
-
1
def backtrace
-
return nil if super.nil?
-
return super if sass_backtrace.all? {|h| h.empty?}
-
sass_backtrace.map do |h|
-
"#{h[:filename] || "(sass)"}:#{h[:line]}" +
-
(h[:mixin] ? ":in `#{h[:mixin]}'" : "")
-
end + super
-
end
-
-
# Returns a string representation of the Sass backtrace.
-
#
-
# @param default_filename [String] The filename to use for unknown files
-
# @see #sass_backtrace
-
# @return [String]
-
1
def sass_backtrace_str(default_filename = "an unknown file")
-
lines = self.message.split("\n")
-
msg = lines[0] + lines[1..-1].
-
map {|l| "\n" + (" " * "Syntax error: ".size) + l}.join
-
"Syntax error: #{msg}" +
-
Sass::Util.enum_with_index(sass_backtrace).map do |entry, i|
-
"\n #{i == 0 ? "on" : "from"} line #{entry[:line]}" +
-
" of #{entry[:filename] || default_filename}" +
-
(entry[:mixin] ? ", in `#{entry[:mixin]}'" : "")
-
end.join
-
end
-
-
1
class << self
-
# Returns an error report for an exception in CSS format.
-
#
-
# @param e [Exception]
-
# @param options [{Symbol => Object}] The options passed to {Sass::Engine#initialize}
-
# @return [String] The error report
-
# @raise [Exception] `e`, if the
-
# {file:SASS_REFERENCE.md#full_exception-option `:full_exception`} option
-
# is set to false.
-
1
def exception_to_css(e, options)
-
raise e unless options[:full_exception]
-
-
header = header_string(e, options)
-
-
<<END
-
/*
-
#{header.gsub("*/", "*\\/")}
-
-
Backtrace:\n#{e.backtrace.join("\n").gsub("*/", "*\\/")}
-
*/
-
body:before {
-
white-space: pre;
-
font-family: monospace;
-
content: "#{header.gsub('"', '\"').gsub("\n", '\\A ')}"; }
-
END
-
end
-
-
1
private
-
-
1
def header_string(e, options)
-
unless e.is_a?(Sass::SyntaxError) && e.sass_line && e.sass_template
-
return "#{e.class}: #{e.message}"
-
end
-
-
line_offset = options[:line] || 1
-
line_num = e.sass_line + 1 - line_offset
-
min = [line_num - 6, 0].max
-
section = e.sass_template.rstrip.split("\n")[min ... line_num + 5]
-
return e.sass_backtrace_str if section.nil? || section.empty?
-
-
e.sass_backtrace_str + "\n\n" + Sass::Util.enum_with_index(section).
-
map {|line, i| "#{line_offset + min + i}: #{line}"}.join("\n")
-
end
-
end
-
end
-
-
# The class for Sass errors that are raised due to invalid unit conversions
-
# in SassScript.
-
1
class UnitConversionError < SyntaxError; end
-
end
-
1
module Sass
-
# Sass importers are in charge of taking paths passed to `@import`
-
# and finding the appropriate Sass code for those paths.
-
# By default, this code is always loaded from the filesystem,
-
# but importers could be added to load from a database or over HTTP.
-
#
-
# Each importer is in charge of a single load path
-
# (or whatever the corresponding notion is for the backend).
-
# Importers can be placed in the {file:SASS_REFERENCE.md#load_paths-option `:load_paths` array}
-
# alongside normal filesystem paths.
-
#
-
# When resolving an `@import`, Sass will go through the load paths
-
# looking for an importer that successfully imports the path.
-
# Once one is found, the imported file is used.
-
#
-
# User-created importers must inherit from {Importers::Base}.
-
1
module Importers
-
end
-
end
-
-
1
require 'sass/importers/base'
-
1
require 'sass/importers/filesystem'
-
1
module Sass
-
1
module Importers
-
# The abstract base class for Sass importers.
-
# All importers should inherit from this.
-
#
-
# At the most basic level, an importer is given a string
-
# and must return a {Sass::Engine} containing some Sass code.
-
# This string can be interpreted however the importer wants;
-
# however, subclasses are encouraged to use the URI format
-
# for pathnames.
-
#
-
# Importers that have some notion of "relative imports"
-
# should take a single load path in their constructor,
-
# and interpret paths as relative to that.
-
# They should also implement the \{#find\_relative} method.
-
#
-
# Importers should be serializable via `Marshal.dump`.
-
# In addition to the standard `_dump` and `_load` methods,
-
# importers can define `_before_dump`, `_after_dump`, `_around_dump`,
-
# and `_after_load` methods as per {Sass::Util#dump} and {Sass::Util#load}.
-
#
-
# @abstract
-
1
class Base
-
-
# Find a Sass file relative to another file.
-
# Importers without a notion of "relative paths"
-
# should just return nil here.
-
#
-
# If the importer does have a notion of "relative paths",
-
# it should ignore its load path during this method.
-
#
-
# See \{#find} for important information on how this method should behave.
-
#
-
# The `:filename` option passed to the returned {Sass::Engine}
-
# should be of a format that could be passed to \{#find}.
-
#
-
# @param uri [String] The URI to import. This is not necessarily relative,
-
# but this method should only return true if it is.
-
# @param base [String] The base filename. If `uri` is relative,
-
# it should be interpreted as relative to `base`.
-
# `base` is guaranteed to be in a format importable by this importer.
-
# @param options [{Symbol => Object}] Options for the Sass file
-
# containing the `@import` that's currently being resolved.
-
# @return [Sass::Engine, nil] An Engine containing the imported file,
-
# or nil if it couldn't be found or was in the wrong format.
-
1
def find_relative(uri, base, options)
-
Sass::Util.abstract(self)
-
end
-
-
# Find a Sass file, if it exists.
-
#
-
# This is the primary entry point of the Importer.
-
# It corresponds directly to an `@import` statement in Sass.
-
# It should do three basic things:
-
#
-
# * Determine if the URI is in this importer's format.
-
# If not, return nil.
-
# * Determine if the file indicated by the URI actually exists and is readable.
-
# If not, return nil.
-
# * Read the file and place the contents in a {Sass::Engine}.
-
# Return that engine.
-
#
-
# If this importer's format allows for file extensions,
-
# it should treat them the same way as the default {Filesystem} importer.
-
# If the URI explicitly has a `.sass` or `.scss` filename,
-
# the importer should look for that exact file
-
# and import it as the syntax indicated.
-
# If it doesn't exist, the importer should return nil.
-
#
-
# If the URI doesn't have either of these extensions,
-
# the importer should look for files with the extensions.
-
# If no such files exist, it should return nil.
-
#
-
# The {Sass::Engine} to be returned should be passed `options`,
-
# with a few modifications. `:syntax` should be set appropriately,
-
# `:filename` should be set to `uri`,
-
# and `:importer` should be set to this importer.
-
#
-
# @param uri [String] The URI to import.
-
# @param options [{Symbol => Object}] Options for the Sass file
-
# containing the `@import` that's currently being resolved.
-
# This is safe for subclasses to modify destructively.
-
# Callers should only pass in a value they don't mind being destructively modified.
-
# @return [Sass::Engine, nil] An Engine containing the imported file,
-
# or nil if it couldn't be found or was in the wrong format.
-
1
def find(uri, options)
-
Sass::Util.abstract(self)
-
end
-
-
# Returns the time the given Sass file was last modified.
-
#
-
# If the given file has been deleted or the time can't be accessed
-
# for some other reason, this should return nil.
-
#
-
# @param uri [String] The URI of the file to check.
-
# Comes from a `:filename` option set on an engine returned by this importer.
-
# @param options [{Symbol => Objet}] Options for the Sass file
-
# containing the `@import` currently being checked.
-
# @return [Time, nil]
-
1
def mtime(uri, options)
-
Sass::Util.abstract(self)
-
end
-
-
# Get the cache key pair for the given Sass URI.
-
# The URI need not be checked for validity.
-
#
-
# The only strict requirement is that the returned pair of strings
-
# uniquely identify the file at the given URI.
-
# However, the first component generally corresponds roughly to the directory,
-
# and the second to the basename, of the URI.
-
#
-
# Note that keys must be unique *across importers*.
-
# Thus it's probably a good idea to include the importer name
-
# at the beginning of the first component.
-
#
-
# @param uri [String] A URI known to be valid for this importer.
-
# @param options [{Symbol => Object}] Options for the Sass file
-
# containing the `@import` currently being checked.
-
# @return [(String, String)] The key pair which uniquely identifies
-
# the file at the given URI.
-
1
def key(uri, options)
-
Sass::Util.abstract(self)
-
end
-
-
# A string representation of the importer.
-
# Should be overridden by subclasses.
-
#
-
# This is used to help debugging,
-
# and should usually just show the load path encapsulated by this importer.
-
#
-
# @return [String]
-
1
def to_s
-
Sass::Util.abstract(self)
-
end
-
end
-
end
-
end
-
-
-
1
require 'pathname'
-
1
require 'set'
-
-
1
module Sass
-
1
module Importers
-
# The default importer, used for any strings found in the load path.
-
# Simply loads Sass files from the filesystem using the default logic.
-
1
class Filesystem < Base
-
-
1
attr_accessor :root
-
-
# Creates a new filesystem importer that imports files relative to a given path.
-
#
-
# @param root [String] The root path.
-
# This importer will import files relative to this path.
-
1
def initialize(root)
-
@root = File.expand_path(root)
-
@same_name_warnings = Set.new
-
end
-
-
# @see Base#find_relative
-
1
def find_relative(name, base, options)
-
_find(File.dirname(base), name, options)
-
end
-
-
# @see Base#find
-
1
def find(name, options)
-
_find(@root, name, options)
-
end
-
-
# @see Base#mtime
-
1
def mtime(name, options)
-
file, _ = Sass::Util.destructure(find_real_file(@root, name, options))
-
File.mtime(file) if file
-
rescue Errno::ENOENT
-
nil
-
end
-
-
# @see Base#key
-
1
def key(name, options)
-
[self.class.name + ":" + File.dirname(File.expand_path(name)),
-
File.basename(name)]
-
end
-
-
# @see Base#to_s
-
1
def to_s
-
@root
-
end
-
-
1
def hash
-
@root.hash
-
end
-
-
1
def eql?(other)
-
root.eql?(other.root)
-
end
-
-
1
protected
-
-
# If a full uri is passed, this removes the root from it
-
# otherwise returns the name unchanged
-
1
def remove_root(name)
-
if name.index(@root + "/") == 0
-
name[(@root.length + 1)..-1]
-
else
-
name
-
end
-
end
-
-
# A hash from file extensions to the syntaxes for those extensions.
-
# The syntaxes must be `:sass` or `:scss`.
-
#
-
# This can be overridden by subclasses that want normal filesystem importing
-
# with unusual extensions.
-
#
-
# @return [{String => Symbol}]
-
1
def extensions
-
{'sass' => :sass, 'scss' => :scss}
-
end
-
-
# Given an `@import`ed path, returns an array of possible
-
# on-disk filenames and their corresponding syntaxes for that path.
-
#
-
# @param name [String] The filename.
-
# @return [Array(String, Symbol)] An array of pairs.
-
# The first element of each pair is a filename to look for;
-
# the second element is the syntax that file would be in (`:sass` or `:scss`).
-
1
def possible_files(name)
-
name = escape_glob_characters(name)
-
dirname, basename, extname = split(name)
-
sorted_exts = extensions.sort
-
syntax = extensions[extname]
-
-
if syntax
-
ret = [["#{dirname}/{_,}#{basename}.#{extensions.invert[syntax]}", syntax]]
-
else
-
ret = sorted_exts.map {|ext, syn| ["#{dirname}/{_,}#{basename}.#{ext}", syn]}
-
end
-
-
# JRuby chokes when trying to import files from JARs when the path starts with './'.
-
ret.map {|f, s| [f.sub(%r{^\./}, ''), s]}
-
end
-
-
1
def escape_glob_characters(name)
-
name.gsub(/[\*\[\]\{\}\?]/) do |char|
-
"\\#{char}"
-
end
-
end
-
-
1
REDUNDANT_DIRECTORY = %r{#{Regexp.escape(File::SEPARATOR)}\.#{Regexp.escape(File::SEPARATOR)}}
-
# Given a base directory and an `@import`ed name,
-
# finds an existant file that matches the name.
-
#
-
# @param dir [String] The directory relative to which to search.
-
# @param name [String] The filename to search for.
-
# @return [(String, Symbol)] A filename-syntax pair.
-
1
def find_real_file(dir, name, options)
-
# on windows 'dir' can be in native File::ALT_SEPARATOR form
-
dir = dir.gsub(File::ALT_SEPARATOR, File::SEPARATOR) unless File::ALT_SEPARATOR.nil?
-
-
found = possible_files(remove_root(name)).map do |f, s|
-
path = (dir == "." || Pathname.new(f).absolute?) ? f : "#{escape_glob_characters(dir)}/#{f}"
-
Dir[path].map do |full_path|
-
full_path.gsub!(REDUNDANT_DIRECTORY, File::SEPARATOR)
-
[Pathname.new(full_path).cleanpath.to_s, s]
-
end
-
end
-
found = Sass::Util.flatten(found, 1)
-
return if found.empty?
-
-
if found.size > 1 && !@same_name_warnings.include?(found.first.first)
-
found.each {|(f, _)| @same_name_warnings << f}
-
relative_to = Pathname.new(dir)
-
if options[:_line]
-
# If _line exists, we're here due to an actual import in an
-
# import_node and we want to print a warning for a user writing an
-
# ambiguous import.
-
candidates = found.map {|(f, _)| " " + Pathname.new(f).relative_path_from(relative_to).to_s}.join("\n")
-
Sass::Util.sass_warn <<WARNING
-
WARNING: On line #{options[:_line]}#{" of #{options[:filename]}" if options[:filename]}:
-
It's not clear which file to import for '@import "#{name}"'.
-
Candidates:
-
#{candidates}
-
For now I'll choose #{File.basename found.first.first}.
-
This will be an error in future versions of Sass.
-
WARNING
-
else
-
# Otherwise, we're here via StalenessChecker, and we want to print a
-
# warning for a user running `sass --watch` with two ambiguous files.
-
candidates = found.map {|(f, _)| " " + File.basename(f)}.join("\n")
-
Sass::Util.sass_warn <<WARNING
-
WARNING: In #{File.dirname(name)}:
-
There are multiple files that match the name "#{File.basename(name)}":
-
#{candidates}
-
WARNING
-
end
-
end
-
found.first
-
end
-
-
# Splits a filename into three parts, a directory part, a basename, and an extension
-
# Only the known extensions returned from the extensions method will be recognized as such.
-
1
def split(name)
-
extension = nil
-
dirname, basename = File.dirname(name), File.basename(name)
-
if basename =~ /^(.*)\.(#{extensions.keys.map{|e| Regexp.escape(e)}.join('|')})$/
-
basename = $1
-
extension = $2
-
end
-
[dirname, basename, extension]
-
end
-
-
1
private
-
-
1
def _find(dir, name, options)
-
full_filename, syntax = Sass::Util.destructure(find_real_file(dir, name, options))
-
return unless full_filename && File.readable?(full_filename)
-
-
options[:syntax] = syntax
-
options[:filename] = full_filename
-
options[:importer] = self
-
Sass::Engine.new(File.read(full_filename), options)
-
end
-
end
-
end
-
end
-
1
module Sass::Logger
-
-
end
-
-
1
require "sass/logger/log_level"
-
1
require "sass/logger/base"
-
-
1
module Sass
-
-
1
class << self
-
1
attr_accessor :logger
-
end
-
-
1
self.logger = Sass::Logger::Base.new
-
end
-
1
require 'sass/logger/log_level'
-
-
1
class Sass::Logger::Base
-
-
1
include Sass::Logger::LogLevel
-
-
1
attr_accessor :log_level
-
1
attr_accessor :disabled
-
-
1
log_level :trace
-
1
log_level :debug
-
1
log_level :info
-
1
log_level :warn
-
1
log_level :error
-
-
1
def initialize(log_level = :debug)
-
2
self.log_level = log_level
-
end
-
-
1
def logging_level?(level)
-
!disabled && self.class.log_level?(level, log_level)
-
end
-
-
1
def log(level, message)
-
self._log(level, message) if logging_level?(level)
-
end
-
-
1
def _log(level, message)
-
Kernel::warn(message)
-
end
-
-
end
-
1
module Sass
-
1
module Logger
-
1
module LogLevel
-
-
1
def self.included(base)
-
1
base.extend(ClassMethods)
-
end
-
-
1
module ClassMethods
-
1
def inherited(subclass)
-
1
subclass.log_levels = subclass.superclass.log_levels.dup
-
end
-
-
1
def log_levels
-
11
@log_levels ||= {}
-
end
-
-
1
def log_levels=(levels)
-
1
@log_levels = levels
-
end
-
-
1
def log_level?(level, min_level)
-
log_levels[level] >= log_levels[min_level]
-
end
-
-
1
def log_level(name, options = {})
-
5
if options[:prepend]
-
level = log_levels.values.min
-
level = level.nil? ? 0 : level - 1
-
else
-
5
level = log_levels.values.max
-
5
level = level.nil? ? 0 : level + 1
-
end
-
5
log_levels.update(name => level)
-
5
define_logger(name)
-
end
-
-
1
def define_logger(name, options = {})
-
5
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{name}(message)
-
#{options.fetch(:to, :log)}(#{name.inspect}, message)
-
end
-
RUBY
-
end
-
end
-
-
end
-
end
-
end
-
# A namespace for the `@media` query parse tree.
-
1
module Sass::Media
-
# A comma-separated list of queries.
-
#
-
# media_query [ ',' S* media_query ]*
-
1
class QueryList
-
# The queries contained in this list.
-
#
-
# @return [Array<Query>]
-
1
attr_accessor :queries
-
-
# @param queries [Array<Query>] See \{#queries}
-
1
def initialize(queries)
-
@queries = queries
-
end
-
-
# Merges this query list with another. The returned query list
-
# queries for the intersection between the two inputs.
-
#
-
# Both query lists should be resolved.
-
#
-
# @param other [QueryList]
-
# @return [QueryList?] The merged list, or nil if there is no intersection.
-
1
def merge(other)
-
new_queries = queries.map {|q1| other.queries.map {|q2| q1.merge(q2)}}.flatten.compact
-
return if new_queries.empty?
-
QueryList.new(new_queries)
-
end
-
-
# Returns the CSS for the media query list.
-
#
-
# @return [String]
-
1
def to_css
-
queries.map {|q| q.to_css}.join(', ')
-
end
-
-
# Returns the Sass/SCSS code for the media query list.
-
#
-
# @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize}).
-
# @return [String]
-
1
def to_src(options)
-
queries.map {|q| q.to_src(options)}.join(', ')
-
end
-
-
# Returns a representation of the query as an array of strings and
-
# potentially {Sass::Script::Node}s (if there's interpolation in it). When
-
# the interpolation is resolved and the strings are joined together, this
-
# will be the string representation of this query.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
1
def to_a
-
Sass::Util.intersperse(queries.map {|q| q.to_a}, ', ').flatten
-
end
-
-
# Returns a deep copy of this query list and all its children.
-
#
-
# @return [QueryList]
-
1
def deep_copy
-
QueryList.new(queries.map {|q| q.deep_copy})
-
end
-
end
-
-
# A single media query.
-
#
-
# [ [ONLY | NOT]? S* media_type S* | expression ] [ AND S* expression ]*
-
1
class Query
-
# The modifier for the query.
-
#
-
# When parsed as Sass code, this contains strings and SassScript nodes. When
-
# parsed as CSS, it contains a single string (accessible via
-
# \{#resolved_modifier}).
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
1
attr_accessor :modifier
-
-
# The type of the query (e.g. `"screen"` or `"print"`).
-
#
-
# When parsed as Sass code, this contains strings and SassScript nodes. When
-
# parsed as CSS, it contains a single string (accessible via
-
# \{#resolved_type}).
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
1
attr_accessor :type
-
-
# The trailing expressions in the query.
-
#
-
# When parsed as Sass code, each expression contains strings and SassScript
-
# nodes. When parsed as CSS, each one contains a single string.
-
#
-
# @return [Array<Array<String, Sass::Script::Node>>]
-
1
attr_accessor :expressions
-
-
# @param modifier [Array<String, Sass::Script::Node>] See \{#modifier}
-
# @param type [Array<String, Sass::Script::Node>] See \{#type}
-
# @param expressions [Array<Array<String, Sass::Script::Node>>] See \{#expressions}
-
1
def initialize(modifier, type, expressions)
-
@modifier = modifier
-
@type = type
-
@expressions = expressions
-
end
-
-
# See \{#modifier}.
-
# @return [String]
-
1
def resolved_modifier
-
# modifier should contain only a single string
-
modifier.first || ''
-
end
-
-
# See \{#type}.
-
# @return [String]
-
1
def resolved_type
-
# type should contain only a single string
-
type.first || ''
-
end
-
-
# Merges this query with another. The returned query queries for
-
# the intersection between the two inputs.
-
#
-
# Both queries should be resolved.
-
#
-
# @param other [Query]
-
# @return [Query?] The merged query, or nil if there is no intersection.
-
1
def merge(other)
-
m1, t1 = resolved_modifier.downcase, resolved_type.downcase
-
m2, t2 = other.resolved_modifier.downcase, other.resolved_type.downcase
-
t1 = t2 if t1.empty?
-
t2 = t1 if t2.empty?
-
if ((m1 == 'not') ^ (m2 == 'not'))
-
return if t1 == t2
-
type = m1 == 'not' ? t2 : t1
-
mod = m1 == 'not' ? m2 : m1
-
elsif m1 == 'not' && m2 == 'not'
-
# CSS has no way of representing "neither screen nor print"
-
return unless t1 == t2
-
type = t1
-
mod = 'not'
-
elsif t1 != t2
-
return
-
else # t1 == t2, neither m1 nor m2 are "not"
-
type = t1
-
mod = m1.empty? ? m2 : m1
-
end
-
return Query.new([mod], [type], other.expressions + expressions)
-
end
-
-
# Returns the CSS for the media query.
-
#
-
# @return [String]
-
1
def to_css
-
css = ''
-
css << resolved_modifier
-
css << ' ' unless resolved_modifier.empty?
-
css << resolved_type
-
css << ' and ' unless resolved_type.empty? || expressions.empty?
-
css << expressions.map do |e|
-
# It's possible for there to be script nodes in Expressions even when
-
# we're converting to CSS in the case where we parsed the document as
-
# CSS originally (as in css_test.rb).
-
e.map {|c| c.is_a?(Sass::Script::Node) ? c.to_sass : c.to_s}.join
-
end.join(' and ')
-
css
-
end
-
-
# Returns the Sass/SCSS code for the media query.
-
#
-
# @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize}).
-
# @return [String]
-
1
def to_src(options)
-
src = ''
-
src << Sass::Media._interp_to_src(modifier, options)
-
src << ' ' unless modifier.empty?
-
src << Sass::Media._interp_to_src(type, options)
-
src << ' and ' unless type.empty? || expressions.empty?
-
src << expressions.map do |e|
-
Sass::Media._interp_to_src(e, options)
-
end.join(' and ')
-
src
-
end
-
-
# @see \{MediaQuery#to\_a}
-
1
def to_a
-
res = []
-
res += modifier
-
res << ' ' unless modifier.empty?
-
res += type
-
res << ' and ' unless type.empty? || expressions.empty?
-
res += Sass::Util.intersperse(expressions, ' and ').flatten
-
res
-
end
-
-
# Returns a deep copy of this query and all its children.
-
#
-
# @return [Query]
-
1
def deep_copy
-
Query.new(
-
modifier.map {|c| c.is_a?(Sass::Script::Node) ? c.deep_copy : c},
-
type.map {|c| c.is_a?(Sass::Script::Node) ? c.deep_copy : c},
-
expressions.map {|e| e.map {|c| c.is_a?(Sass::Script::Node) ? c.deep_copy : c}})
-
end
-
end
-
-
# Converts an interpolation array to source.
-
#
-
# @param [Array<String, Sass::Script::Node>] The interpolation array to convert.
-
# @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize}).
-
# @return [String]
-
1
def self._interp_to_src(interp, options)
-
interp.map do |r|
-
next r if r.is_a?(String)
-
"\#{#{r.to_sass(options)}}"
-
end.join
-
end
-
end
-
# Rails 3.0.0.beta.2+, < 3.1
-
1
if defined?(ActiveSupport) && Sass::Util.has?(:public_method, ActiveSupport, :on_load) &&
-
!Sass::Util.ap_geq?('3.1.0.beta')
-
require 'sass/plugin/configuration'
-
ActiveSupport.on_load(:before_configuration) do
-
require 'sass'
-
require 'sass/plugin'
-
require 'sass/plugin/rails'
-
end
-
end
-
1
module Sass
-
# The root directory of the Sass source tree.
-
# This may be overridden by the package manager
-
# if the lib directory is separated from the main source tree.
-
# @api public
-
1
ROOT_DIR = File.expand_path(File.join(__FILE__, "../../.."))
-
end
-
1
require 'sass/script/node'
-
1
require 'sass/script/variable'
-
1
require 'sass/script/funcall'
-
1
require 'sass/script/operation'
-
1
require 'sass/script/literal'
-
1
require 'sass/script/parser'
-
-
1
module Sass
-
# SassScript is code that's embedded in Sass documents
-
# to allow for property values to be computed from variables.
-
#
-
# This module contains code that handles the parsing and evaluation of SassScript.
-
1
module Script
-
# The regular expression used to parse variables.
-
1
MATCH = /^\$(#{Sass::SCSS::RX::IDENT})\s*:\s*(.+?)(!(?i:default))?$/
-
-
# The regular expression used to validate variables without matching.
-
1
VALIDATE = /^\$#{Sass::SCSS::RX::IDENT}$/
-
-
# Parses a string of SassScript
-
#
-
# @param value [String] The SassScript
-
# @param line [Fixnum] The number of the line on which the SassScript appeared.
-
# Used for error reporting
-
# @param offset [Fixnum] The number of characters in on `line` that the SassScript started.
-
# Used for error reporting
-
# @param options [{Symbol => Object}] An options hash;
-
# see {file:SASS_REFERENCE.md#sass_options the Sass options documentation}
-
# @return [Script::Node] The root node of the parse tree
-
1
def self.parse(value, line, offset, options = {})
-
Parser.parse(value, line, offset, options)
-
rescue Sass::SyntaxError => e
-
e.message << ": #{value.inspect}." if e.message == "SassScript error"
-
e.modify_backtrace(:line => line, :filename => options[:filename])
-
raise e
-
end
-
-
end
-
end
-
1
module Sass::Script
-
# A SassScript object representing a variable argument list. This works just
-
# like a normal list, but can also contain keyword arguments.
-
#
-
# The keyword arguments attached to this list are unused except when this is
-
# passed as a glob argument to a function or mixin.
-
1
class ArgList < List
-
# Whether \{#keywords} has been accessed. If so, we assume that all keywords
-
# were valid for the function that created this ArgList.
-
#
-
# @return [Boolean]
-
1
attr_accessor :keywords_accessed
-
-
# Creates a new argument list.
-
#
-
# @param value [Array<Literal>] See \{List#value}.
-
# @param keywords [Hash<String, Literal>] See \{#keywords}
-
# @param separator [String] See \{List#separator}.
-
1
def initialize(value, keywords, separator)
-
super(value, separator)
-
@keywords = keywords
-
end
-
-
# The keyword arguments attached to this list.
-
#
-
# @return [Hash<String, Literal>]
-
1
def keywords
-
@keywords_accessed = true
-
@keywords
-
end
-
-
# @see Node#children
-
1
def children
-
super + @keywords.values
-
end
-
-
# @see Node#deep_copy
-
1
def deep_copy
-
node = super
-
node.instance_variable_set('@keywords',
-
Sass::Util.map_hash(@keywords) {|k, v| [k, v.deep_copy]})
-
node
-
end
-
-
1
protected
-
-
# @see Node#_perform
-
1
def _perform(environment)
-
self
-
end
-
end
-
end
-
1
require 'sass/script/literal'
-
-
1
module Sass::Script
-
# A SassScript object representing a boolean (true or false) value.
-
1
class Bool < Literal
-
# The Ruby value of the boolean.
-
#
-
# @return [Boolean]
-
1
attr_reader :value
-
1
alias_method :to_bool, :value
-
-
# @return [String] "true" or "false"
-
1
def to_s(opts = {})
-
@value.to_s
-
end
-
1
alias_method :to_sass, :to_s
-
end
-
end
-
1
require 'sass/script/literal'
-
-
1
module Sass::Script
-
# A SassScript object representing a CSS color.
-
#
-
# A color may be represented internally as RGBA, HSLA, or both.
-
# It's originally represented as whatever its input is;
-
# if it's created with RGB values, it's represented as RGBA,
-
# and if it's created with HSL values, it's represented as HSLA.
-
# Once a property is accessed that requires the other representation --
-
# for example, \{#red} for an HSL color --
-
# that component is calculated and cached.
-
#
-
# The alpha channel of a color is independent of its RGB or HSL representation.
-
# It's always stored, as 1 if nothing else is specified.
-
# If only the alpha channel is modified using \{#with},
-
# the cached RGB and HSL values are retained.
-
1
class Color < Literal
-
2
class << self; include Sass::Util; end
-
-
# A hash from color names to `[red, green, blue]` value arrays.
-
1
COLOR_NAMES = map_vals({
-
'aliceblue' => 0xf0f8ff,
-
'antiquewhite' => 0xfaebd7,
-
'aqua' => 0x00ffff,
-
'aquamarine' => 0x7fffd4,
-
'azure' => 0xf0ffff,
-
'beige' => 0xf5f5dc,
-
'bisque' => 0xffe4c4,
-
'black' => 0x000000,
-
'blanchedalmond' => 0xffebcd,
-
'blue' => 0x0000ff,
-
'blueviolet' => 0x8a2be2,
-
'brown' => 0xa52a2a,
-
'burlywood' => 0xdeb887,
-
'cadetblue' => 0x5f9ea0,
-
'chartreuse' => 0x7fff00,
-
'chocolate' => 0xd2691e,
-
'coral' => 0xff7f50,
-
'cornflowerblue' => 0x6495ed,
-
'cornsilk' => 0xfff8dc,
-
'crimson' => 0xdc143c,
-
'cyan' => 0x00ffff,
-
'darkblue' => 0x00008b,
-
'darkcyan' => 0x008b8b,
-
'darkgoldenrod' => 0xb8860b,
-
'darkgray' => 0xa9a9a9,
-
'darkgrey' => 0xa9a9a9,
-
'darkgreen' => 0x006400,
-
'darkkhaki' => 0xbdb76b,
-
'darkmagenta' => 0x8b008b,
-
'darkolivegreen' => 0x556b2f,
-
'darkorange' => 0xff8c00,
-
'darkorchid' => 0x9932cc,
-
'darkred' => 0x8b0000,
-
'darksalmon' => 0xe9967a,
-
'darkseagreen' => 0x8fbc8f,
-
'darkslateblue' => 0x483d8b,
-
'darkslategray' => 0x2f4f4f,
-
'darkslategrey' => 0x2f4f4f,
-
'darkturquoise' => 0x00ced1,
-
'darkviolet' => 0x9400d3,
-
'deeppink' => 0xff1493,
-
'deepskyblue' => 0x00bfff,
-
'dimgray' => 0x696969,
-
'dimgrey' => 0x696969,
-
'dodgerblue' => 0x1e90ff,
-
'firebrick' => 0xb22222,
-
'floralwhite' => 0xfffaf0,
-
'forestgreen' => 0x228b22,
-
'fuchsia' => 0xff00ff,
-
'gainsboro' => 0xdcdcdc,
-
'ghostwhite' => 0xf8f8ff,
-
'gold' => 0xffd700,
-
'goldenrod' => 0xdaa520,
-
'gray' => 0x808080,
-
'green' => 0x008000,
-
'greenyellow' => 0xadff2f,
-
'honeydew' => 0xf0fff0,
-
'hotpink' => 0xff69b4,
-
'indianred' => 0xcd5c5c,
-
'indigo' => 0x4b0082,
-
'ivory' => 0xfffff0,
-
'khaki' => 0xf0e68c,
-
'lavender' => 0xe6e6fa,
-
'lavenderblush' => 0xfff0f5,
-
'lawngreen' => 0x7cfc00,
-
'lemonchiffon' => 0xfffacd,
-
'lightblue' => 0xadd8e6,
-
'lightcoral' => 0xf08080,
-
'lightcyan' => 0xe0ffff,
-
'lightgoldenrodyellow' => 0xfafad2,
-
'lightgreen' => 0x90ee90,
-
'lightgray' => 0xd3d3d3,
-
'lightgrey' => 0xd3d3d3,
-
'lightpink' => 0xffb6c1,
-
'lightsalmon' => 0xffa07a,
-
'lightseagreen' => 0x20b2aa,
-
'lightskyblue' => 0x87cefa,
-
'lightslategray' => 0x778899,
-
'lightslategrey' => 0x778899,
-
'lightsteelblue' => 0xb0c4de,
-
'lightyellow' => 0xffffe0,
-
'lime' => 0x00ff00,
-
'limegreen' => 0x32cd32,
-
'linen' => 0xfaf0e6,
-
'magenta' => 0xff00ff,
-
'maroon' => 0x800000,
-
'mediumaquamarine' => 0x66cdaa,
-
'mediumblue' => 0x0000cd,
-
'mediumorchid' => 0xba55d3,
-
'mediumpurple' => 0x9370db,
-
'mediumseagreen' => 0x3cb371,
-
'mediumslateblue' => 0x7b68ee,
-
'mediumspringgreen' => 0x00fa9a,
-
'mediumturquoise' => 0x48d1cc,
-
'mediumvioletred' => 0xc71585,
-
'midnightblue' => 0x191970,
-
'mintcream' => 0xf5fffa,
-
'mistyrose' => 0xffe4e1,
-
'moccasin' => 0xffe4b5,
-
'navajowhite' => 0xffdead,
-
'navy' => 0x000080,
-
'oldlace' => 0xfdf5e6,
-
'olive' => 0x808000,
-
'olivedrab' => 0x6b8e23,
-
'orange' => 0xffa500,
-
'orangered' => 0xff4500,
-
'orchid' => 0xda70d6,
-
'palegoldenrod' => 0xeee8aa,
-
'palegreen' => 0x98fb98,
-
'paleturquoise' => 0xafeeee,
-
'palevioletred' => 0xdb7093,
-
'papayawhip' => 0xffefd5,
-
'peachpuff' => 0xffdab9,
-
'peru' => 0xcd853f,
-
'pink' => 0xffc0cb,
-
'plum' => 0xdda0dd,
-
'powderblue' => 0xb0e0e6,
-
'purple' => 0x800080,
-
'red' => 0xff0000,
-
'rosybrown' => 0xbc8f8f,
-
'royalblue' => 0x4169e1,
-
'saddlebrown' => 0x8b4513,
-
'salmon' => 0xfa8072,
-
'sandybrown' => 0xf4a460,
-
'seagreen' => 0x2e8b57,
-
'seashell' => 0xfff5ee,
-
'sienna' => 0xa0522d,
-
'silver' => 0xc0c0c0,
-
'skyblue' => 0x87ceeb,
-
'slateblue' => 0x6a5acd,
-
'slategray' => 0x708090,
-
'slategrey' => 0x708090,
-
'snow' => 0xfffafa,
-
'springgreen' => 0x00ff7f,
-
'steelblue' => 0x4682b4,
-
'tan' => 0xd2b48c,
-
'teal' => 0x008080,
-
'thistle' => 0xd8bfd8,
-
'tomato' => 0xff6347,
-
'turquoise' => 0x40e0d0,
-
'violet' => 0xee82ee,
-
'wheat' => 0xf5deb3,
-
'white' => 0xffffff,
-
'whitesmoke' => 0xf5f5f5,
-
'yellow' => 0xffff00,
-
'yellowgreen' => 0x9acd32
-
584
}) {|color| (0..2).map {|n| color >> (n << 3) & 0xff}.reverse}
-
-
# A hash from `[red, green, blue]` value arrays to color names.
-
147
COLOR_NAMES_REVERSE = map_hash(hash_to_a(COLOR_NAMES)) {|k, v| [v, k]}
-
-
# Constructs an RGB or HSL color object,
-
# optionally with an alpha channel.
-
#
-
# The RGB values must be between 0 and 255.
-
# The saturation and lightness values must be between 0 and 100.
-
# The alpha value must be between 0 and 1.
-
#
-
# @raise [Sass::SyntaxError] if any color value isn't in the specified range
-
#
-
# @overload initialize(attrs)
-
# The attributes are specified as a hash.
-
# This hash must contain either `:hue`, `:saturation`, and `:value` keys,
-
# or `:red`, `:green`, and `:blue` keys.
-
# It cannot contain both HSL and RGB keys.
-
# It may also optionally contain an `:alpha` key.
-
#
-
# @param attrs [{Symbol => Numeric}] A hash of color attributes to values
-
# @raise [ArgumentError] if not enough attributes are specified,
-
# or both RGB and HSL attributes are specified
-
#
-
# @overload initialize(rgba)
-
# The attributes are specified as an array.
-
# This overload only supports RGB or RGBA colors.
-
#
-
# @param rgba [Array<Numeric>] A three- or four-element array
-
# of the red, green, blue, and optionally alpha values (respectively)
-
# of the color
-
# @raise [ArgumentError] if not enough attributes are specified
-
1
def initialize(attrs, allow_both_rgb_and_hsl = false)
-
super(nil)
-
-
if attrs.is_a?(Array)
-
unless (3..4).include?(attrs.size)
-
raise ArgumentError.new("Color.new(array) expects a three- or four-element array")
-
end
-
-
red, green, blue = attrs[0...3].map {|c| c.to_i}
-
@attrs = {:red => red, :green => green, :blue => blue}
-
@attrs[:alpha] = attrs[3] ? attrs[3].to_f : 1
-
else
-
attrs = attrs.reject {|k, v| v.nil?}
-
hsl = [:hue, :saturation, :lightness] & attrs.keys
-
rgb = [:red, :green, :blue] & attrs.keys
-
if !allow_both_rgb_and_hsl && !hsl.empty? && !rgb.empty?
-
raise ArgumentError.new("Color.new(hash) may not have both HSL and RGB keys specified")
-
elsif hsl.empty? && rgb.empty?
-
raise ArgumentError.new("Color.new(hash) must have either HSL or RGB keys specified")
-
elsif !hsl.empty? && hsl.size != 3
-
raise ArgumentError.new("Color.new(hash) must have all three HSL values specified")
-
elsif !rgb.empty? && rgb.size != 3
-
raise ArgumentError.new("Color.new(hash) must have all three RGB values specified")
-
end
-
-
@attrs = attrs
-
@attrs[:hue] %= 360 if @attrs[:hue]
-
@attrs[:alpha] ||= 1
-
end
-
-
[:red, :green, :blue].each do |k|
-
next if @attrs[k].nil?
-
@attrs[k] = @attrs[k].to_i
-
Sass::Util.check_range("#{k.to_s.capitalize} value", 0..255, @attrs[k])
-
end
-
-
[:saturation, :lightness].each do |k|
-
next if @attrs[k].nil?
-
value = Number.new(@attrs[k], ['%']) # Get correct unit for error messages
-
@attrs[k] = Sass::Util.check_range("#{k.to_s.capitalize}", 0..100, value, '%')
-
end
-
-
@attrs[:alpha] = Sass::Util.check_range("Alpha channel", 0..1, @attrs[:alpha])
-
end
-
-
# The red component of the color.
-
#
-
# @return [Fixnum]
-
1
def red
-
hsl_to_rgb!
-
@attrs[:red]
-
end
-
-
# The green component of the color.
-
#
-
# @return [Fixnum]
-
1
def green
-
hsl_to_rgb!
-
@attrs[:green]
-
end
-
-
# The blue component of the color.
-
#
-
# @return [Fixnum]
-
1
def blue
-
hsl_to_rgb!
-
@attrs[:blue]
-
end
-
-
# The hue component of the color.
-
#
-
# @return [Numeric]
-
1
def hue
-
rgb_to_hsl!
-
@attrs[:hue]
-
end
-
-
# The saturation component of the color.
-
#
-
# @return [Numeric]
-
1
def saturation
-
rgb_to_hsl!
-
@attrs[:saturation]
-
end
-
-
# The lightness component of the color.
-
#
-
# @return [Numeric]
-
1
def lightness
-
rgb_to_hsl!
-
@attrs[:lightness]
-
end
-
-
# The alpha channel (opacity) of the color.
-
# This is 1 unless otherwise defined.
-
#
-
# @return [Fixnum]
-
1
def alpha
-
@attrs[:alpha]
-
end
-
-
# Returns whether this color object is translucent;
-
# that is, whether the alpha channel is non-1.
-
#
-
# @return [Boolean]
-
1
def alpha?
-
alpha < 1
-
end
-
-
# Returns the red, green, and blue components of the color.
-
#
-
# @return [Array<Fixnum>] A frozen three-element array of the red, green, and blue
-
# values (respectively) of the color
-
1
def rgb
-
[red, green, blue].freeze
-
end
-
-
# Returns the hue, saturation, and lightness components of the color.
-
#
-
# @return [Array<Fixnum>] A frozen three-element array of the
-
# hue, saturation, and lightness values (respectively) of the color
-
1
def hsl
-
[hue, saturation, lightness].freeze
-
end
-
-
# The SassScript `==` operation.
-
# **Note that this returns a {Sass::Script::Bool} object,
-
# not a Ruby boolean**.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Bool] True if this literal is the same as the other,
-
# false otherwise
-
1
def eq(other)
-
Sass::Script::Bool.new(
-
other.is_a?(Color) && rgb == other.rgb && alpha == other.alpha)
-
end
-
-
# Returns a copy of this color with one or more channels changed.
-
# RGB or HSL colors may be changed, but not both at once.
-
#
-
# For example:
-
#
-
# Color.new([10, 20, 30]).with(:blue => 40)
-
# #=> rgb(10, 40, 30)
-
# Color.new([126, 126, 126]).with(:red => 0, :green => 255)
-
# #=> rgb(0, 255, 126)
-
# Color.new([255, 0, 127]).with(:saturation => 60)
-
# #=> rgb(204, 51, 127)
-
# Color.new([1, 2, 3]).with(:alpha => 0.4)
-
# #=> rgba(1, 2, 3, 0.4)
-
#
-
# @param attrs [{Symbol => Numeric}]
-
# A map of channel names (`:red`, `:green`, `:blue`,
-
# `:hue`, `:saturation`, `:lightness`, or `:alpha`) to values
-
# @return [Color] The new Color object
-
# @raise [ArgumentError] if both RGB and HSL keys are specified
-
1
def with(attrs)
-
attrs = attrs.reject {|k, v| v.nil?}
-
hsl = !([:hue, :saturation, :lightness] & attrs.keys).empty?
-
rgb = !([:red, :green, :blue] & attrs.keys).empty?
-
if hsl && rgb
-
raise ArgumentError.new("Cannot specify HSL and RGB values for a color at the same time")
-
end
-
-
if hsl
-
[:hue, :saturation, :lightness].each {|k| attrs[k] ||= send(k)}
-
elsif rgb
-
[:red, :green, :blue].each {|k| attrs[k] ||= send(k)}
-
else
-
# If we're just changing the alpha channel,
-
# keep all the HSL/RGB stuff we've calculated
-
attrs = @attrs.merge(attrs)
-
end
-
attrs[:alpha] ||= alpha
-
-
Color.new(attrs, :allow_both_rgb_and_hsl)
-
end
-
-
# The SassScript `+` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Adds the number to each of the RGB color channels.
-
#
-
# {Color}
-
# : Adds each of the RGB color channels together.
-
#
-
# {Literal}
-
# : See {Literal#plus}.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Color] The resulting color
-
# @raise [Sass::SyntaxError] if `other` is a number with units
-
1
def plus(other)
-
if other.is_a?(Sass::Script::Number) || other.is_a?(Sass::Script::Color)
-
piecewise(other, :+)
-
else
-
super
-
end
-
end
-
-
# The SassScript `-` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Subtracts the number from each of the RGB color channels.
-
#
-
# {Color}
-
# : Subtracts each of the other color's RGB color channels from this color's.
-
#
-
# {Literal}
-
# : See {Literal#minus}.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Color] The resulting color
-
# @raise [Sass::SyntaxError] if `other` is a number with units
-
1
def minus(other)
-
if other.is_a?(Sass::Script::Number) || other.is_a?(Sass::Script::Color)
-
piecewise(other, :-)
-
else
-
super
-
end
-
end
-
-
# The SassScript `*` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Multiplies the number by each of the RGB color channels.
-
#
-
# {Color}
-
# : Multiplies each of the RGB color channels together.
-
#
-
# @param other [Number, Color] The right-hand side of the operator
-
# @return [Color] The resulting color
-
# @raise [Sass::SyntaxError] if `other` is a number with units
-
1
def times(other)
-
if other.is_a?(Sass::Script::Number) || other.is_a?(Sass::Script::Color)
-
piecewise(other, :*)
-
else
-
raise NoMethodError.new(nil, :times)
-
end
-
end
-
-
# The SassScript `/` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Divides each of the RGB color channels by the number.
-
#
-
# {Color}
-
# : Divides each of this color's RGB color channels by the other color's.
-
#
-
# {Literal}
-
# : See {Literal#div}.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Color] The resulting color
-
# @raise [Sass::SyntaxError] if `other` is a number with units
-
1
def div(other)
-
if other.is_a?(Sass::Script::Number) || other.is_a?(Sass::Script::Color)
-
piecewise(other, :/)
-
else
-
super
-
end
-
end
-
-
# The SassScript `%` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Takes each of the RGB color channels module the number.
-
#
-
# {Color}
-
# : Takes each of this color's RGB color channels modulo the other color's.
-
#
-
# @param other [Number, Color] The right-hand side of the operator
-
# @return [Color] The resulting color
-
# @raise [Sass::SyntaxError] if `other` is a number with units
-
1
def mod(other)
-
if other.is_a?(Sass::Script::Number) || other.is_a?(Sass::Script::Color)
-
piecewise(other, :%)
-
else
-
raise NoMethodError.new(nil, :mod)
-
end
-
end
-
-
# Returns a string representation of the color.
-
# This is usually the color's hex value,
-
# but if the color has a name that's used instead.
-
#
-
# @return [String] The string representation
-
1
def to_s(opts = {})
-
return rgba_str if alpha?
-
return smallest if options[:style] == :compressed
-
return COLOR_NAMES_REVERSE[rgb] if COLOR_NAMES_REVERSE[rgb]
-
hex_str
-
end
-
1
alias_method :to_sass, :to_s
-
-
# Returns a string representation of the color.
-
#
-
# @return [String] The hex value
-
1
def inspect
-
alpha? ? rgba_str : hex_str
-
end
-
-
1
private
-
-
1
def smallest
-
small_hex_str = hex_str.gsub(/^#(.)\1(.)\2(.)\3$/, '#\1\2\3')
-
return small_hex_str unless (color = COLOR_NAMES_REVERSE[rgb]) &&
-
color.size <= small_hex_str.size
-
return color
-
end
-
-
1
def rgba_str
-
split = options[:style] == :compressed ? ',' : ', '
-
"rgba(#{rgb.join(split)}#{split}#{Number.round(alpha)})"
-
end
-
-
1
def hex_str
-
red, green, blue = rgb.map { |num| num.to_s(16).rjust(2, '0') }
-
"##{red}#{green}#{blue}"
-
end
-
-
1
def piecewise(other, operation)
-
other_num = other.is_a? Number
-
if other_num && !other.unitless?
-
raise Sass::SyntaxError.new("Cannot add a number with units (#{other}) to a color (#{self}).")
-
end
-
-
result = []
-
for i in (0...3)
-
res = rgb[i].send(operation, other_num ? other.value : other.rgb[i])
-
result[i] = [ [res, 255].min, 0 ].max
-
end
-
-
if !other_num && other.alpha != alpha
-
raise Sass::SyntaxError.new("Alpha channels must be equal: #{self} #{operation} #{other}")
-
end
-
-
with(:red => result[0], :green => result[1], :blue => result[2])
-
end
-
-
1
def hsl_to_rgb!
-
return if @attrs[:red] && @attrs[:blue] && @attrs[:green]
-
-
h = @attrs[:hue] / 360.0
-
s = @attrs[:saturation] / 100.0
-
l = @attrs[:lightness] / 100.0
-
-
# Algorithm from the CSS3 spec: http://www.w3.org/TR/css3-color/#hsl-color.
-
m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s
-
m1 = l * 2 - m2
-
@attrs[:red], @attrs[:green], @attrs[:blue] = [
-
hue_to_rgb(m1, m2, h + 1.0/3),
-
hue_to_rgb(m1, m2, h),
-
hue_to_rgb(m1, m2, h - 1.0/3)
-
].map {|c| (c * 0xff).round}
-
end
-
-
1
def hue_to_rgb(m1, m2, h)
-
h += 1 if h < 0
-
h -= 1 if h > 1
-
return m1 + (m2 - m1) * h * 6 if h * 6 < 1
-
return m2 if h * 2 < 1
-
return m1 + (m2 - m1) * (2.0/3 - h) * 6 if h * 3 < 2
-
return m1
-
end
-
-
1
def rgb_to_hsl!
-
return if @attrs[:hue] && @attrs[:saturation] && @attrs[:lightness]
-
r, g, b = [:red, :green, :blue].map {|k| @attrs[k] / 255.0}
-
-
# Algorithm from http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
-
max = [r, g, b].max
-
min = [r, g, b].min
-
d = max - min
-
-
h =
-
case max
-
when min; 0
-
when r; 60 * (g-b)/d
-
when g; 60 * (b-r)/d + 120
-
when b; 60 * (r-g)/d + 240
-
end
-
-
l = (max + min)/2.0
-
-
s =
-
if max == min
-
0
-
elsif l < 0.5
-
d/(2*l)
-
else
-
d/(2 - 2*l)
-
end
-
-
@attrs[:hue] = h % 360
-
@attrs[:saturation] = s * 100
-
@attrs[:lightness] = l * 100
-
end
-
end
-
end
-
1
module Sass
-
1
module Script
-
# This is a subclass of {Lexer} for use in parsing plain CSS properties.
-
#
-
# @see Sass::SCSS::CssParser
-
1
class CssLexer < Lexer
-
1
private
-
-
1
def token
-
important || super
-
end
-
-
1
def string(re, *args)
-
if re == :uri
-
return unless uri = scan(URI)
-
return [:string, Script::String.new(uri)]
-
end
-
-
return unless scan(STRING)
-
[:string, Script::String.new((@scanner[1] || @scanner[2]).gsub(/\\(['"])/, '\1'), :string)]
-
end
-
-
1
def important
-
return unless s = scan(IMPORTANT)
-
[:raw, s]
-
end
-
end
-
end
-
end
-
1
require 'sass/script'
-
1
require 'sass/script/css_lexer'
-
-
1
module Sass
-
1
module Script
-
# This is a subclass of {Parser} for use in parsing plain CSS properties.
-
#
-
# @see Sass::SCSS::CssParser
-
1
class CssParser < Parser
-
1
private
-
-
# @private
-
1
def lexer_class; CssLexer; end
-
-
# We need a production that only does /,
-
# since * and % aren't allowed in plain CSS
-
1
production :div, :unary_plus, :div
-
-
1
def string
-
return number unless tok = try_tok(:string)
-
return tok.value unless @lexer.peek && @lexer.peek.type == :begin_interpolation
-
end
-
-
# Short-circuit all the SassScript-only productions
-
1
alias_method :interpolation, :space
-
1
alias_method :or_expr, :div
-
1
alias_method :unary_div, :ident
-
1
alias_method :paren, :string
-
end
-
end
-
end
-
1
require 'sass/script/functions'
-
-
1
module Sass
-
1
module Script
-
# A SassScript parse node representing a function call.
-
#
-
# A function call either calls one of the functions in {Script::Functions},
-
# or if no function with the given name exists
-
# it returns a string representation of the function call.
-
1
class Funcall < Node
-
# The name of the function.
-
#
-
# @return [String]
-
1
attr_reader :name
-
-
# The arguments to the function.
-
#
-
# @return [Array<Script::Node>]
-
1
attr_reader :args
-
-
# The keyword arguments to the function.
-
#
-
# @return [{String => Script::Node}]
-
1
attr_reader :keywords
-
-
# The splat argument for this function, if one exists.
-
#
-
# @return [Script::Node?]
-
1
attr_accessor :splat
-
-
# @param name [String] See \{#name}
-
# @param args [Array<Script::Node>] See \{#args}
-
# @param splat [Script::Node] See \{#splat}
-
# @param keywords [{String => Script::Node}] See \{#keywords}
-
1
def initialize(name, args, keywords, splat)
-
@name = name
-
@args = args
-
@keywords = keywords
-
@splat = splat
-
super()
-
end
-
-
# @return [String] A string representation of the function call
-
1
def inspect
-
args = @args.map {|a| a.inspect}.join(', ')
-
keywords = Sass::Util.hash_to_a(@keywords).
-
map {|k, v| "$#{k}: #{v.inspect}"}.join(', ')
-
if self.splat
-
splat = (args.empty? && keywords.empty?) ? "" : ", "
-
splat = "#{splat}#{self.splat.inspect}..."
-
end
-
"#{name}(#{args}#{', ' unless args.empty? || keywords.empty?}#{keywords}#{splat})"
-
end
-
-
# @see Node#to_sass
-
1
def to_sass(opts = {})
-
arg_to_sass = lambda do |arg|
-
sass = arg.to_sass(opts)
-
sass = "(#{sass})" if arg.is_a?(Sass::Script::List) && arg.separator == :comma
-
sass
-
end
-
-
args = @args.map(&arg_to_sass).join(', ')
-
keywords = Sass::Util.hash_to_a(@keywords).
-
map {|k, v| "$#{dasherize(k, opts)}: #{arg_to_sass[v]}"}.join(', ')
-
if self.splat
-
splat = (args.empty? && keywords.empty?) ? "" : ", "
-
splat = "#{splat}#{arg_to_sass[self.splat]}..."
-
end
-
"#{dasherize(name, opts)}(#{args}#{', ' unless args.empty? || keywords.empty?}#{keywords}#{splat})"
-
end
-
-
# Returns the arguments to the function.
-
#
-
# @return [Array<Node>]
-
# @see Node#children
-
1
def children
-
res = @args + @keywords.values
-
res << @splat if @splat
-
res
-
end
-
-
# @see Node#deep_copy
-
1
def deep_copy
-
node = dup
-
node.instance_variable_set('@args', args.map {|a| a.deep_copy})
-
node.instance_variable_set('@keywords', Hash[keywords.map {|k, v| [k, v.deep_copy]}])
-
node
-
end
-
-
1
protected
-
-
# Evaluates the function call.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Literal] The SassScript object that is the value of the function call
-
# @raise [Sass::SyntaxError] if the function call raises an ArgumentError
-
1
def _perform(environment)
-
args = @args.map {|a| a.perform(environment)}
-
splat = @splat.perform(environment) if @splat
-
if fn = environment.function(@name)
-
keywords = Sass::Util.map_hash(@keywords) {|k, v| [k, v.perform(environment)]}
-
return without_original(perform_sass_fn(fn, args, keywords, splat))
-
end
-
-
ruby_name = @name.tr('-', '_')
-
args = construct_ruby_args(ruby_name, args, splat, environment)
-
-
unless Functions.callable?(ruby_name)
-
without_original(opts(to_literal(args)))
-
else
-
without_original(opts(Functions::EvaluationContext.new(environment.options).
-
send(ruby_name, *args)))
-
end
-
rescue ArgumentError => e
-
message = e.message
-
-
# If this is a legitimate Ruby-raised argument error, re-raise it.
-
# Otherwise, it's an error in the user's stylesheet, so wrap it.
-
if Sass::Util.rbx?
-
# Rubinius has a different error report string than vanilla Ruby. It
-
# also doesn't put the actual method for which the argument error was
-
# thrown in the backtrace, nor does it include `send`, so we look for
-
# `_perform`.
-
if e.message =~ /^method '([^']+)': given (\d+), expected (\d+)/
-
error_name, given, expected = $1, $2, $3
-
raise e if error_name != ruby_name || e.backtrace[0] !~ /:in `_perform'$/
-
message = "wrong number of arguments (#{given} for #{expected})"
-
end
-
elsif Sass::Util.jruby?
-
if Sass::Util.jruby1_6?
-
should_maybe_raise = e.message =~ /^wrong number of arguments \((\d+) for (\d+)\)/ &&
-
# The one case where JRuby does include the Ruby name of the function
-
# is manually-thrown ArgumentErrors, which are indistinguishable from
-
# legitimate ArgumentErrors. We treat both of these as
-
# Sass::SyntaxErrors even though it can hide Ruby errors.
-
e.backtrace[0] !~ /:in `(block in )?#{ruby_name}'$/
-
else
-
should_maybe_raise = e.message =~ /^wrong number of arguments calling `[^`]+` \((\d+) for (\d+)\)/
-
given, expected = $1, $2
-
end
-
-
if should_maybe_raise
-
# JRuby 1.7 includes __send__ before send and _perform.
-
trace = e.backtrace.dup
-
raise e if !Sass::Util.jruby1_6? && trace.shift !~ /:in `__send__'$/
-
-
# JRuby (as of 1.7.2) doesn't put the actual method
-
# for which the argument error was thrown in the backtrace, so we
-
# detect whether our send threw an argument error.
-
if !(trace[0] =~ /:in `send'$/ && trace[1] =~ /:in `_perform'$/)
-
raise e
-
elsif !Sass::Util.jruby1_6?
-
# JRuby 1.7 doesn't use standard formatting for its ArgumentErrors.
-
message = "wrong number of arguments (#{given} for #{expected})"
-
end
-
end
-
elsif e.message =~ /^wrong number of arguments \(\d+ for \d+\)/ &&
-
e.backtrace[0] !~ /:in `(block in )?#{ruby_name}'$/
-
raise e
-
end
-
raise Sass::SyntaxError.new("#{message} for `#{name}'")
-
end
-
-
# This method is factored out from `_perform` so that compass can override
-
# it with a cross-browser implementation for functions that require vendor prefixes
-
# in the generated css.
-
1
def to_literal(args)
-
Script::String.new("#{name}(#{args.join(', ')})")
-
end
-
-
1
private
-
-
1
def without_original(value)
-
return value unless value.is_a?(Number)
-
value = value.dup
-
value.original = nil
-
return value
-
end
-
-
1
def construct_ruby_args(name, args, splat, environment)
-
args += splat.to_a if splat
-
-
# If variable arguments were passed, there won't be any explicit keywords.
-
if splat.is_a?(Sass::Script::ArgList)
-
kwargs_size = splat.keywords.size
-
splat.keywords_accessed = false
-
else
-
kwargs_size = @keywords.size
-
end
-
-
unless signature = Functions.signature(name.to_sym, args.size, kwargs_size)
-
return args if @keywords.empty?
-
raise Sass::SyntaxError.new("Function #{name} doesn't support keyword arguments")
-
end
-
keywords = splat.is_a?(Sass::Script::ArgList) ? splat.keywords :
-
Sass::Util.map_hash(@keywords) {|k, v| [k, v.perform(environment)]}
-
-
# If the user passes more non-keyword args than the function expects,
-
# but it does expect keyword args, Ruby's arg handling won't raise an error.
-
# Since we don't want to make functions think about this,
-
# we'll handle it for them here.
-
if signature.var_kwargs && !signature.var_args && args.size > signature.args.size
-
raise Sass::SyntaxError.new(
-
"#{args[signature.args.size].inspect} is not a keyword argument for `#{name}'")
-
elsif keywords.empty?
-
return args
-
end
-
-
args = args + signature.args[args.size..-1].map do |argname|
-
if keywords.has_key?(argname)
-
keywords.delete(argname)
-
else
-
raise Sass::SyntaxError.new("Function #{name} requires an argument named $#{argname}")
-
end
-
end
-
-
if keywords.size > 0
-
if signature.var_kwargs
-
args << keywords
-
else
-
argname = keywords.keys.sort.first
-
if signature.args.include?(argname)
-
raise Sass::SyntaxError.new("Function #{name} was passed argument $#{argname} both by position and by name")
-
else
-
raise Sass::SyntaxError.new("Function #{name} doesn't have an argument named $#{argname}")
-
end
-
end
-
end
-
-
args
-
end
-
-
1
def perform_sass_fn(function, args, keywords, splat)
-
Sass::Tree::Visitors::Perform.perform_arguments(function, args, keywords, splat) do |env|
-
val = catch :_sass_return do
-
function.tree.each {|c| Sass::Tree::Visitors::Perform.visit(c, env)}
-
raise Sass::SyntaxError.new("Function #{@name} finished without @return")
-
end
-
val
-
end
-
end
-
end
-
end
-
end
-
1
module Sass::Script
-
# Methods in this module are accessible from the SassScript context.
-
# For example, you can write
-
#
-
# $color: hsl(120deg, 100%, 50%)
-
#
-
# and it will call {Sass::Script::Functions#hsl}.
-
#
-
# The following functions are provided:
-
#
-
# *Note: These functions are described in more detail below.*
-
#
-
# ## RGB Functions
-
#
-
# \{#rgb rgb($red, $green, $blue)}
-
# : Creates a {Color} from red, green, and blue values.
-
#
-
# \{#rgba rgba($red, $green, $blue, $alpha)}
-
# : Creates a {Color} from red, green, blue, and alpha values.
-
#
-
# \{#red red($color)}
-
# : Gets the red component of a color.
-
#
-
# \{#green green($color)}
-
# : Gets the green component of a color.
-
#
-
# \{#blue blue($color)}
-
# : Gets the blue component of a color.
-
#
-
# \{#mix mix($color-1, $color-2, \[$weight\])}
-
# : Mixes two colors together.
-
#
-
# ## HSL Functions
-
#
-
# \{#hsl hsl($hue, $saturation, $lightness)}
-
# : Creates a {Color} from hue, saturation, and lightness values.
-
#
-
# \{#hsla hsla($hue, $saturation, $lightness, $alpha)}
-
# : Creates a {Color} from hue, saturation, lightness, and alpha
-
# values.
-
#
-
# \{#hue hue($color)}
-
# : Gets the hue component of a color.
-
#
-
# \{#saturation saturation($color)}
-
# : Gets the saturation component of a color.
-
#
-
# \{#lightness lightness($color)}
-
# : Gets the lightness component of a color.
-
#
-
# \{#adjust_hue adjust-hue($color, $degrees)}
-
# : Changes the hue of a color.
-
#
-
# \{#lighten lighten($color, $amount)}
-
# : Makes a color lighter.
-
#
-
# \{#darken darken($color, $amount)}
-
# : Makes a color darker.
-
#
-
# \{#saturate saturate($color, $amount)}
-
# : Makes a color more saturated.
-
#
-
# \{#desaturate desaturate($color, $amount)}
-
# : Makes a color less saturated.
-
#
-
# \{#grayscale grayscale($color)}
-
# : Converts a color to grayscale.
-
#
-
# \{#complement complement($color)}
-
# : Returns the complement of a color.
-
#
-
# \{#invert invert($color)}
-
# : Returns the inverse of a color.
-
#
-
# ## Opacity Functions
-
#
-
# \{#alpha alpha($color)} / \{#opacity opacity($color)}
-
# : Gets the alpha component (opacity) of a color.
-
#
-
# \{#rgba rgba($color, $alpha)}
-
# : Changes the alpha component for a color.
-
#
-
# \{#opacify opacify($color, $amount)} / \{#fade_in fade-in($color, $amount)}
-
# : Makes a color more opaque.
-
#
-
# \{#transparentize transparentize($color, $amount)} / \{#fade_out fade-out($color, $amount)}
-
# : Makes a color more transparent.
-
#
-
# ## Other Color Functions
-
#
-
# \{#adjust_color adjust-color($color, \[$red\], \[$green\], \[$blue\], \[$hue\], \[$saturation\], \[$lightness\], \[$alpha\])}
-
# : Increases or decreases one or more components of a color.
-
#
-
# \{#scale_color scale-color($color, \[$red\], \[$green\], \[$blue\], \[$saturation\], \[$lightness\], \[$alpha\])}
-
# : Fluidly scales one or more properties of a color.
-
#
-
# \{#change_color change-color($color, \[$red\], \[$green\], \[$blue\], \[$hue\], \[$saturation\], \[$lightness\], \[$alpha\])}
-
# : Changes one or more properties of a color.
-
#
-
# \{#ie_hex_str ie-hex-str($color)}
-
# : Converts a color into the format understood by IE filters.
-
#
-
# ## String Functions
-
#
-
# \{#unquote unquote($string)}
-
# : Removes quotes from a string.
-
#
-
# \{#quote quote($string)}
-
# : Adds quotes to a string.
-
#
-
# ## Number Functions
-
#
-
# \{#percentage percentage($value)}
-
# : Converts a unitless number to a percentage.
-
#
-
# \{#round round($value)}
-
# : Rounds a number to the nearest whole number.
-
#
-
# \{#ceil ceil($value)}
-
# : Rounds a number up to the next whole number.
-
#
-
# \{#floor floor($value)}
-
# : Rounds a number down to the previous whole number.
-
#
-
# \{#abs abs($value)}
-
# : Returns the absolute value of a number.
-
#
-
# \{#min min($numbers...)\}
-
# : Finds the minimum of several numbers.
-
#
-
# \{#max max($numbers...)\}
-
# : Finds the maximum of several numbers.
-
#
-
# ## List Functions {#list-functions}
-
#
-
# \{#length length($list)}
-
# : Returns the length of a list.
-
#
-
# \{#nth nth($list, $n)}
-
# : Returns a specific item in a list.
-
#
-
# \{#join join($list1, $list2, \[$separator\])}
-
# : Joins together two lists into one.
-
#
-
# \{#append append($list1, $val, \[$separator\])}
-
# : Appends a single value onto the end of a list.
-
#
-
# \{#zip zip($lists...)}
-
# : Combines several lists into a single multidimensional list.
-
#
-
# \{#index index($list, $value)}
-
# : Returns the position of a value within a list.
-
#
-
# ## Introspection Functions
-
#
-
# \{#type_of type-of($value)}
-
# : Returns the type of a value.
-
#
-
# \{#unit unit($number)}
-
# : Returns the unit(s) associated with a number.
-
#
-
# \{#unitless unitless($number)}
-
# : Returns whether a number has units.
-
#
-
# \{#comparable comparable($number-1, $number-2)}
-
# : Returns whether two numbers can be added, subtracted, or compared.
-
#
-
# ## Miscellaneous Functions
-
#
-
# \{#if if($condition, $if-true, $if-false)}
-
# : Returns one of two values, depending on whether or not `$condition` is
-
# true.
-
#
-
# ## Adding Custom Functions
-
#
-
# New Sass functions can be added by adding Ruby methods to this module.
-
# For example:
-
#
-
# module Sass::Script::Functions
-
# def reverse(string)
-
# assert_type string, :String
-
# Sass::Script::String.new(string.value.reverse)
-
# end
-
# declare :reverse, :args => [:string]
-
# end
-
#
-
# Calling {declare} tells Sass the argument names for your function.
-
# If omitted, the function will still work, but will not be able to accept keyword arguments.
-
# {declare} can also allow your function to take arbitrary keyword arguments.
-
#
-
# There are a few things to keep in mind when modifying this module.
-
# First of all, the arguments passed are {Sass::Script::Literal} objects.
-
# Literal objects are also expected to be returned.
-
# This means that Ruby values must be unwrapped and wrapped.
-
#
-
# Most Literal objects support the {Sass::Script::Literal#value value} accessor
-
# for getting their Ruby values.
-
# Color objects, though, must be accessed using {Sass::Script::Color#rgb rgb},
-
# {Sass::Script::Color#red red}, {Sass::Script::Color#blue green}, or {Sass::Script::Color#blue blue}.
-
#
-
# Second, making Ruby functions accessible from Sass introduces the temptation
-
# to do things like database access within stylesheets.
-
# This is generally a bad idea;
-
# since Sass files are by default only compiled once,
-
# dynamic code is not a great fit.
-
#
-
# If you really, really need to compile Sass on each request,
-
# first make sure you have adequate caching set up.
-
# Then you can use {Sass::Engine} to render the code,
-
# using the {file:SASS_REFERENCE.md#custom-option `options` parameter}
-
# to pass in data that {EvaluationContext#options can be accessed}
-
# from your Sass functions.
-
#
-
# Within one of the functions in this module,
-
# methods of {EvaluationContext} can be used.
-
#
-
# ### Caveats
-
#
-
# When creating new {Literal} objects within functions,
-
# be aware that it's not safe to call {Literal#to_s #to_s}
-
# (or other methods that use the string representation)
-
# on those objects without first setting {Node#options= the #options attribute}.
-
1
module Functions
-
1
@signatures = {}
-
-
# A class representing a Sass function signature.
-
#
-
# @attr args [Array<Symbol>] The names of the arguments to the function.
-
# @attr var_args [Boolean] Whether the function takes a variable number of arguments.
-
# @attr var_kwargs [Boolean] Whether the function takes an arbitrary set of keyword arguments.
-
1
Signature = Struct.new(:args, :var_args, :var_kwargs)
-
-
# Declare a Sass signature for a Ruby-defined function.
-
# This includes the names of the arguments,
-
# whether the function takes a variable number of arguments,
-
# and whether the function takes an arbitrary set of keyword arguments.
-
#
-
# It's not necessary to declare a signature for a function.
-
# However, without a signature it won't support keyword arguments.
-
#
-
# A single function can have multiple signatures declared
-
# as long as each one takes a different number of arguments.
-
# It's also possible to declare multiple signatures
-
# that all take the same number of arguments,
-
# but none of them but the first will be used
-
# unless the user uses keyword arguments.
-
#
-
# @example
-
# declare :rgba, [:hex, :alpha]
-
# declare :rgba, [:red, :green, :blue, :alpha]
-
# declare :accepts_anything, [], :var_args => true, :var_kwargs => true
-
# declare :some_func, [:foo, :bar, :baz], :var_kwargs => true
-
#
-
# @param method_name [Symbol] The name of the method
-
# whose signature is being declared.
-
# @param args [Array<Symbol>] The names of the arguments for the function signature.
-
# @option options :var_args [Boolean] (false)
-
# Whether the function accepts a variable number of (unnamed) arguments
-
# in addition to the named arguments.
-
# @option options :var_kwargs [Boolean] (false)
-
# Whether the function accepts other keyword arguments
-
# in addition to those in `:args`.
-
# If this is true, the Ruby function will be passed a hash from strings
-
# to {Sass::Script::Literal}s as the last argument.
-
# In addition, if this is true and `:var_args` is not,
-
# Sass will ensure that the last argument passed is a hash.
-
1
def self.declare(method_name, args, options = {})
-
56
@signatures[method_name] ||= []
-
@signatures[method_name] << Signature.new(
-
85
args.map {|s| s.to_s},
-
options[:var_args],
-
56
options[:var_kwargs])
-
end
-
-
# Determine the correct signature for the number of arguments
-
# passed in for a given function.
-
# If no signatures match, the first signature is returned for error messaging.
-
#
-
# @param method_name [Symbol] The name of the Ruby function to be called.
-
# @param arg_arity [Number] The number of unnamed arguments the function was passed.
-
# @param kwarg_arity [Number] The number of keyword arguments the function was passed.
-
#
-
# @return [{Symbol => Object}, nil]
-
# The signature options for the matching signature,
-
# or nil if no signatures are declared for this function. See {declare}.
-
1
def self.signature(method_name, arg_arity, kwarg_arity)
-
return unless @signatures[method_name]
-
@signatures[method_name].each do |signature|
-
return signature if signature.args.size == arg_arity + kwarg_arity
-
next unless signature.args.size < arg_arity + kwarg_arity
-
-
# We have enough args.
-
# Now we need to figure out which args are varargs
-
# and if the signature allows them.
-
t_arg_arity, t_kwarg_arity = arg_arity, kwarg_arity
-
if signature.args.size > t_arg_arity
-
# we transfer some kwargs arity to args arity
-
# if it does not have enough args -- assuming the names will work out.
-
t_kwarg_arity -= (signature.args.size - t_arg_arity)
-
t_arg_arity = signature.args.size
-
end
-
-
if ( t_arg_arity == signature.args.size || t_arg_arity > signature.args.size && signature.var_args ) &&
-
(t_kwarg_arity == 0 || t_kwarg_arity > 0 && signature.var_kwargs)
-
return signature
-
end
-
end
-
@signatures[method_name].first
-
end
-
-
# The context in which methods in {Script::Functions} are evaluated.
-
# That means that all instance methods of {EvaluationContext}
-
# are available to use in functions.
-
1
class EvaluationContext
-
1
include Functions
-
-
# The options hash for the {Sass::Engine} that is processing the function call
-
#
-
# @return [{Symbol => Object}]
-
1
attr_reader :options
-
-
# @param options [{Symbol => Object}] See \{#options}
-
1
def initialize(options)
-
@options = options
-
end
-
-
# Asserts that the type of a given SassScript value
-
# is the expected type (designated by a symbol).
-
#
-
# Valid types are `:Bool`, `:Color`, `:Number`, and `:String`.
-
# Note that `:String` will match both double-quoted strings
-
# and unquoted identifiers.
-
#
-
# @example
-
# assert_type value, :String
-
# assert_type value, :Number
-
# @param value [Sass::Script::Literal] A SassScript value
-
# @param type [Symbol] The name of the type the value is expected to be
-
# @param name [String, Symbol, nil] The name of the argument.
-
1
def assert_type(value, type, name = nil)
-
return if value.is_a?(Sass::Script.const_get(type))
-
err = "#{value.inspect} is not a #{type.to_s.downcase}"
-
err = "$#{name.to_s.gsub('_', '-')}: " + err if name
-
raise ArgumentError.new(err)
-
end
-
end
-
-
1
class << self
-
# Returns whether user function with a given name exists.
-
#
-
# @param function_name [String]
-
# @return [Boolean]
-
1
alias_method :callable?, :public_method_defined?
-
-
1
private
-
1
def include(*args)
-
r = super
-
# We have to re-include ourselves into EvaluationContext to work around
-
# an icky Ruby restriction.
-
EvaluationContext.send :include, self
-
r
-
end
-
end
-
-
# Creates a {Color} object from red, green, and blue values.
-
#
-
# @see #rgba
-
# @overload rgb($red, $green, $blue)
-
# @param $red [Number] The amount of red in the color. Must be between 0 and
-
# 255 inclusive, or between `0%` and `100%` inclusive
-
# @param $green [Number] The amount of green in the color. Must be between 0
-
# and 255 inclusive, or between `0%` and `100%` inclusive
-
# @param $blue [Number] The amount of blue in the color. Must be between 0
-
# and 255 inclusive, or between `0%` and `100%` inclusive
-
# @return [Color]
-
# @raise [ArgumentError] if any parameter is the wrong type or out of bounds
-
1
def rgb(red, green, blue)
-
assert_type red, :Number, :red
-
assert_type green, :Number, :green
-
assert_type blue, :Number, :blue
-
-
Color.new([[red, :red], [green, :green], [blue, :blue]].map do |(c, name)|
-
v = c.value
-
if c.numerator_units == ["%"] && c.denominator_units.empty?
-
v = Sass::Util.check_range("$#{name}: Color value", 0..100, c, '%')
-
v * 255 / 100.0
-
else
-
Sass::Util.check_range("$#{name}: Color value", 0..255, c)
-
end
-
end)
-
end
-
1
declare :rgb, [:red, :green, :blue]
-
-
# Creates a {Color} from red, green, blue, and alpha values.
-
# @see #rgb
-
#
-
# @overload rgba($red, $green, $blue, $alpha)
-
# @param $red [Number] The amount of red in the color. Must be between 0
-
# and 255 inclusive
-
# @param $green [Number] The amount of green in the color. Must be between
-
# 0 and 255 inclusive
-
# @param $blue [Number] The amount of blue in the color. Must be between 0
-
# and 255 inclusive
-
# @param $alpha [Number] The opacity of the color. Must be between 0 and 1
-
# inclusive
-
# @return [Color]
-
# @raise [ArgumentError] if any parameter is the wrong type or out of
-
# bounds
-
#
-
# @overload rgba($color, $alpha)
-
# Sets the opacity of an existing color.
-
#
-
# @example
-
# rgba(#102030, 0.5) => rgba(16, 32, 48, 0.5)
-
# rgba(blue, 0.2) => rgba(0, 0, 255, 0.2)
-
#
-
# @param $color [Color] The color whose opacity will be changed.
-
# @param $alpha [Number] The new opacity of the color. Must be between 0
-
# and 1 inclusive
-
# @return [Color]
-
# @raise [ArgumentError] if `$alpha` is out of bounds or either parameter
-
# is the wrong type
-
1
def rgba(*args)
-
case args.size
-
when 2
-
color, alpha = args
-
-
assert_type color, :Color, :color
-
assert_type alpha, :Number, :alpha
-
-
Sass::Util.check_range('Alpha channel', 0..1, alpha)
-
color.with(:alpha => alpha.value)
-
when 4
-
red, green, blue, alpha = args
-
rgba(rgb(red, green, blue), alpha)
-
else
-
raise ArgumentError.new("wrong number of arguments (#{args.size} for 4)")
-
end
-
end
-
1
declare :rgba, [:red, :green, :blue, :alpha]
-
1
declare :rgba, [:color, :alpha]
-
-
# Creates a {Color} from hue, saturation, and lightness values. Uses the
-
# algorithm from the [CSS3 spec][].
-
#
-
# [CSS3 spec]: http://www.w3.org/TR/css3-color/#hsl-color
-
#
-
# @see #hsla
-
# @overload hsl($hue, $saturation, $lightness)
-
# @param $hue [Number] The hue of the color. Should be between 0 and 360
-
# degrees, inclusive
-
# @param $saturation [Number] The saturation of the color. Must be between
-
# `0%` and `100%`, inclusive
-
# @param $lightness [Number] The lightness of the color. Must be between
-
# `0%` and `100%`, inclusive
-
# @return [Color]
-
# @raise [ArgumentError] if `$saturation` or `$lightness` are out of bounds
-
# or any parameter is the wrong type
-
1
def hsl(hue, saturation, lightness)
-
hsla(hue, saturation, lightness, Number.new(1))
-
end
-
1
declare :hsl, [:hue, :saturation, :lightness]
-
-
# Creates a {Color} from hue, saturation, lightness, and alpha
-
# values. Uses the algorithm from the [CSS3 spec][].
-
#
-
# [CSS3 spec]: http://www.w3.org/TR/css3-color/#hsl-color
-
#
-
# @see #hsl
-
# @overload hsla($hue, $saturation, $lightness, $alpha)
-
# @param $hue [Number] The hue of the color. Should be between 0 and 360
-
# degrees, inclusive
-
# @param $saturation [Number] The saturation of the color. Must be between
-
# `0%` and `100%`, inclusive
-
# @param $lightness [Number] The lightness of the color. Must be between
-
# `0%` and `100%`, inclusive
-
# @param $alpha [Number] The opacity of the color. Must be between 0 and 1,
-
# inclusive
-
# @return [Color]
-
# @raise [ArgumentError] if `$saturation`, `$lightness`, or `$alpha` are out
-
# of bounds or any parameter is the wrong type
-
1
def hsla(hue, saturation, lightness, alpha)
-
assert_type hue, :Number, :hue
-
assert_type saturation, :Number, :saturation
-
assert_type lightness, :Number, :lightness
-
assert_type alpha, :Number, :alpha
-
-
Sass::Util.check_range('Alpha channel', 0..1, alpha)
-
-
h = hue.value
-
s = Sass::Util.check_range('Saturation', 0..100, saturation, '%')
-
l = Sass::Util.check_range('Lightness', 0..100, lightness, '%')
-
-
Color.new(:hue => h, :saturation => s, :lightness => l, :alpha => alpha.value)
-
end
-
1
declare :hsla, [:hue, :saturation, :lightness, :alpha]
-
-
# Gets the red component of a color. Calculated from HSL where necessary via
-
# [this algorithm][hsl-to-rgb].
-
#
-
# [hsl-to-rgb]: http://www.w3.org/TR/css3-color/#hsl-color
-
#
-
# @overload red($color)
-
# @param $color [Color]
-
# @return [Number] The red component, between 0 and 255 inclusive
-
# @raise [ArgumentError] if `$color` isn't a color
-
1
def red(color)
-
assert_type color, :Color, :color
-
Sass::Script::Number.new(color.red)
-
end
-
1
declare :red, [:color]
-
-
# Gets the green component of a color. Calculated from HSL where necessary
-
# via [this algorithm][hsl-to-rgb].
-
#
-
# [hsl-to-rgb]: http://www.w3.org/TR/css3-color/#hsl-color
-
#
-
# @overload green($color)
-
# @param $color [Color]
-
# @return [Number] The green component, between 0 and 255 inclusive
-
# @raise [ArgumentError] if `$color` isn't a color
-
1
def green(color)
-
assert_type color, :Color, :color
-
Sass::Script::Number.new(color.green)
-
end
-
1
declare :green, [:color]
-
-
# Gets the blue component of a color. Calculated from HSL where necessary
-
# via [this algorithm][hsl-to-rgb].
-
#
-
# [hsl-to-rgb]: http://www.w3.org/TR/css3-color/#hsl-color
-
#
-
# @overload blue($color)
-
# @param $color [Color]
-
# @return [Number] The blue component, between 0 and 255 inclusive
-
# @raise [ArgumentError] if `$color` isn't a color
-
1
def blue(color)
-
assert_type color, :Color, :color
-
Sass::Script::Number.new(color.blue)
-
end
-
1
declare :blue, [:color]
-
-
# Returns the hue component of a color. See [the CSS3 HSL
-
# specification][hsl]. Calculated from RGB where necessary via [this
-
# algorithm][rgb-to-hsl].
-
#
-
# [hsl]: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
-
# [rgb-to-hsl]: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
-
#
-
# @overload hue($color)
-
# @param $color [Color]
-
# @return [Number] The hue component, between 0deg and 360deg
-
# @raise [ArgumentError] if `$color` isn't a color
-
1
def hue(color)
-
assert_type color, :Color, :color
-
Sass::Script::Number.new(color.hue, ["deg"])
-
end
-
1
declare :hue, [:color]
-
-
# Returns the saturation component of a color. See [the CSS3 HSL
-
# specification][hsl]. Calculated from RGB where necessary via [this
-
# algorithm][rgb-to-hsl].
-
#
-
# [hsl]: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
-
# [rgb-to-hsl]: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
-
#
-
# @overload saturation($color)
-
# @param $color [Color]
-
# @return [Number] The saturation component, between 0% and 100%
-
# @raise [ArgumentError] if `$color` isn't a color
-
1
def saturation(color)
-
assert_type color, :Color, :color
-
Sass::Script::Number.new(color.saturation, ["%"])
-
end
-
1
declare :saturation, [:color]
-
-
# Returns the lightness component of a color. See [the CSS3 HSL
-
# specification][hsl]. Calculated from RGB where necessary via [this
-
# algorithm][rgb-to-hsl].
-
#
-
# [hsl]: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
-
# [rgb-to-hsl]: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
-
#
-
# @overload lightness($color)
-
# @param $color [Color]
-
# @return [Number] The lightness component, between 0% and 100%
-
# @raise [ArgumentError] if `$color` isn't a color
-
1
def lightness(color)
-
assert_type color, :Color, :color
-
Sass::Script::Number.new(color.lightness, ["%"])
-
end
-
1
declare :lightness, [:color]
-
-
# Returns the alpha component (opacity) of a color. This is 1 unless
-
# otherwise specified.
-
#
-
# This function also supports the proprietary Microsoft `alpha(opacity=20)`
-
# syntax as a special case.
-
#
-
# @overload alpha($color)
-
# @param $color [Color]
-
# @return [Number] The alpha component, between 0 and 1
-
# @raise [ArgumentError] if `$color` isn't a color
-
1
def alpha(*args)
-
if args.all? do |a|
-
a.is_a?(Sass::Script::String) && a.type == :identifier &&
-
a.value =~ /^[a-zA-Z]+\s*=/
-
end
-
# Support the proprietary MS alpha() function
-
return Sass::Script::String.new("alpha(#{args.map {|a| a.to_s}.join(", ")})")
-
end
-
-
raise ArgumentError.new("wrong number of arguments (#{args.size} for 1)") if args.size != 1
-
-
assert_type args.first, :Color, :color
-
Sass::Script::Number.new(args.first.alpha)
-
end
-
1
declare :alpha, [:color]
-
-
# Returns the alpha component (opacity) of a color. This is 1 unless
-
# otherwise specified.
-
#
-
# @overload opacity($color)
-
# @param $color [Color]
-
# @return [Number] The alpha component, between 0 and 1
-
# @raise [ArgumentError] if `$color` isn't a color
-
1
def opacity(color)
-
return Sass::Script::String.new("opacity(#{color})") if color.is_a?(Sass::Script::Number)
-
assert_type color, :Color, :color
-
Sass::Script::Number.new(color.alpha)
-
end
-
1
declare :opacity, [:color]
-
-
# Makes a color more opaque. Takes a color and a number between 0 and 1, and
-
# returns a color with the opacity increased by that amount.
-
#
-
# @see #transparentize
-
# @example
-
# opacify(rgba(0, 0, 0, 0.5), 0.1) => rgba(0, 0, 0, 0.6)
-
# opacify(rgba(0, 0, 17, 0.8), 0.2) => #001
-
# @overload opacify($color, $amount)
-
# @param $color [Color]
-
# @param $amount [Number] The amount to increase the opacity by, between 0
-
# and 1
-
# @return [Color]
-
# @raise [ArgumentError] if `$amount` is out of bounds, or either parameter
-
# is the wrong type
-
1
def opacify(color, amount)
-
_adjust(color, amount, :alpha, 0..1, :+)
-
end
-
1
declare :opacify, [:color, :amount]
-
-
1
alias_method :fade_in, :opacify
-
1
declare :fade_in, [:color, :amount]
-
-
# Makes a color more transparent. Takes a color and a number between 0 and
-
# 1, and returns a color with the opacity decreased by that amount.
-
#
-
# @see #opacify
-
# @example
-
# transparentize(rgba(0, 0, 0, 0.5), 0.1) => rgba(0, 0, 0, 0.4)
-
# transparentize(rgba(0, 0, 0, 0.8), 0.2) => rgba(0, 0, 0, 0.6)
-
# @overload transparentize($color, $amount)
-
# @param $color [Color]
-
# @param $amount [Number] The amount to decrease the opacity by, between 0
-
# and 1
-
# @return [Color]
-
# @raise [ArgumentError] if `$amount` is out of bounds, or either parameter
-
# is the wrong type
-
1
def transparentize(color, amount)
-
_adjust(color, amount, :alpha, 0..1, :-)
-
end
-
1
declare :transparentize, [:color, :amount]
-
-
1
alias_method :fade_out, :transparentize
-
1
declare :fade_out, [:color, :amount]
-
-
# Makes a color lighter. Takes a color and a number between `0%` and `100%`,
-
# and returns a color with the lightness increased by that amount.
-
#
-
# @see #darken
-
# @example
-
# lighten(hsl(0, 0%, 0%), 30%) => hsl(0, 0, 30)
-
# lighten(#800, 20%) => #e00
-
# @overload lighten($color, $amount)
-
# @param $color [Color]
-
# @param $amount [Number] The amount to increase the lightness by, between
-
# `0%` and `100%`
-
# @return [Color]
-
# @raise [ArgumentError] if `$amount` is out of bounds, or either parameter
-
# is the wrong type
-
1
def lighten(color, amount)
-
_adjust(color, amount, :lightness, 0..100, :+, "%")
-
end
-
1
declare :lighten, [:color, :amount]
-
-
# Makes a color darker. Takes a color and a number between 0% and 100%, and
-
# returns a color with the lightness decreased by that amount.
-
#
-
# @see #lighten
-
# @example
-
# darken(hsl(25, 100%, 80%), 30%) => hsl(25, 100%, 50%)
-
# darken(#800, 20%) => #200
-
# @overload darken($color, $amount)
-
# @param $color [Color]
-
# @param $amount [Number] The amount to dencrease the lightness by, between
-
# `0%` and `100%`
-
# @return [Color]
-
# @raise [ArgumentError] if `$amount` is out of bounds, or either parameter
-
# is the wrong type
-
1
def darken(color, amount)
-
_adjust(color, amount, :lightness, 0..100, :-, "%")
-
end
-
1
declare :darken, [:color, :amount]
-
-
# Makes a color more saturated. Takes a color and a number between 0% and
-
# 100%, and returns a color with the saturation increased by that amount.
-
#
-
# @see #desaturate
-
# @example
-
# saturate(hsl(120, 30%, 90%), 20%) => hsl(120, 50%, 90%)
-
# saturate(#855, 20%) => #9e3f3f
-
# @overload saturate($color, $amount)
-
# @param $color [Color]
-
# @param $amount [Number] The amount to increase the saturation by, between
-
# `0%` and `100%`
-
# @return [Color]
-
# @raise [ArgumentError] if `$amount` is out of bounds, or either parameter
-
# is the wrong type
-
1
def saturate(color, amount = nil)
-
# Support the filter effects definition of saturate.
-
# https://dvcs.w3.org/hg/FXTF/raw-file/tip/filters/index.html
-
return Sass::Script::String.new("saturate(#{color})") if amount.nil?
-
_adjust(color, amount, :saturation, 0..100, :+, "%")
-
end
-
1
declare :saturate, [:color, :amount]
-
1
declare :saturate, [:amount]
-
-
# Makes a color less saturated. Takes a color and a number between 0% and
-
# 100%, and returns a color with the saturation decreased by that value.
-
#
-
# @see #saturate
-
# @example
-
# desaturate(hsl(120, 30%, 90%), 20%) => hsl(120, 10%, 90%)
-
# desaturate(#855, 20%) => #726b6b
-
# @overload desaturate($color, $amount)
-
# @param $color [Color]
-
# @param $amount [Number] The amount to decrease the saturation by, between
-
# `0%` and `100%`
-
# @return [Color]
-
# @raise [ArgumentError] if `$amount` is out of bounds, or either parameter
-
# is the wrong type
-
1
def desaturate(color, amount)
-
_adjust(color, amount, :saturation, 0..100, :-, "%")
-
end
-
1
declare :desaturate, [:color, :amount]
-
-
# Changes the hue of a color. Takes a color and a number of degrees (usually
-
# between `-360deg` and `360deg`), and returns a color with the hue rotated
-
# along the color wheel by that amount.
-
#
-
# @example
-
# adjust-hue(hsl(120, 30%, 90%), 60deg) => hsl(180, 30%, 90%)
-
# adjust-hue(hsl(120, 30%, 90%), 060deg) => hsl(60, 30%, 90%)
-
# adjust-hue(#811, 45deg) => #886a11
-
# @overload adjust_hue($color, $degrees)
-
# @param $color [Color]
-
# @param $degrees [Number] The number of degrees to rotate the hue
-
# @return [Color]
-
# @raise [ArgumentError] if either parameter is the wrong type
-
1
def adjust_hue(color, degrees)
-
assert_type color, :Color, :color
-
assert_type degrees, :Number, :degrees
-
color.with(:hue => color.hue + degrees.value)
-
end
-
1
declare :adjust_hue, [:color, :degrees]
-
-
# Converts a color into the format understood by IE filters.
-
#
-
# @example
-
# ie-hex-str(#abc) => #FFAABBCC
-
# ie-hex-str(#3322BB) => #FF3322BB
-
# ie-hex-str(rgba(0, 255, 0, 0.5)) => #8000FF00
-
# @overload ie_hex_str($color)
-
# @param $color [Color]
-
# @return [String] The IE-formatted string representation of the color
-
# @raise [ArgumentError] if `$color` isn't a color
-
1
def ie_hex_str(color)
-
assert_type color, :Color, :color
-
alpha = (color.alpha * 255).round.to_s(16).rjust(2, '0')
-
Sass::Script::String.new("##{alpha}#{color.send(:hex_str)[1..-1]}".upcase)
-
end
-
1
declare :ie_hex_str, [:color]
-
-
# Increases or decreases one or more properties of a color. This can change
-
# the red, green, blue, hue, saturation, value, and alpha properties. The
-
# properties are specified as keyword arguments, and are added to or
-
# subtracted from the color's current value for that property.
-
#
-
# All properties are optional. You can't specify both RGB properties
-
# (`$red`, `$green`, `$blue`) and HSL properties (`$hue`, `$saturation`,
-
# `$value`) at the same time.
-
#
-
# @example
-
# adjust-color(#102030, $blue: 5) => #102035
-
# adjust-color(#102030, $red: -5, $blue: 5) => #0b2035
-
# adjust-color(hsl(25, 100%, 80%), $lightness: -30%, $alpha: -0.4) => hsla(25, 100%, 50%, 0.6)
-
# @overload adjust_color($color, [$red], [$green], [$blue], [$hue], [$saturation], [$lightness], [$alpha])
-
# @param $color [Color]
-
# @param $red [Number] The adjustment to make on the red component, between
-
# -255 and 255 inclusive
-
# @param $green [Number] The adjustment to make on the green component,
-
# between -255 and 255 inclusive
-
# @param $blue [Number] The adjustment to make on the blue component, between
-
# -255 and 255 inclusive
-
# @param $hue [Number] The adjustment to make on the hue component, in
-
# degrees
-
# @param $saturation [Number] The adjustment to make on the saturation
-
# component, between `-100%` and `100%` inclusive
-
# @param $lightness [Number] The adjustment to make on the lightness
-
# component, between `-100%` and `100%` inclusive
-
# @param $alpha [Number] The adjustment to make on the alpha component,
-
# between -1 and 1 inclusive
-
# @return [Color]
-
# @raise [ArgumentError] if any parameter is the wrong type or out-of
-
# bounds, or if RGB properties and HSL properties are adjusted at the
-
# same time
-
1
def adjust_color(color, kwargs)
-
assert_type color, :Color, :color
-
with = Sass::Util.map_hash({
-
"red" => [-255..255, ""],
-
"green" => [-255..255, ""],
-
"blue" => [-255..255, ""],
-
"hue" => nil,
-
"saturation" => [-100..100, "%"],
-
"lightness" => [-100..100, "%"],
-
"alpha" => [-1..1, ""]
-
}) do |name, (range, units)|
-
-
next unless val = kwargs.delete(name)
-
assert_type val, :Number, name
-
Sass::Util.check_range("$#{name}: Amount", range, val, units) if range
-
adjusted = color.send(name) + val.value
-
adjusted = [0, Sass::Util.restrict(adjusted, range)].max if range
-
[name.to_sym, adjusted]
-
end
-
-
unless kwargs.empty?
-
name, val = kwargs.to_a.first
-
raise ArgumentError.new("Unknown argument $#{name} (#{val})")
-
end
-
-
color.with(with)
-
end
-
1
declare :adjust_color, [:color], :var_kwargs => true
-
-
# Fluidly scales one or more properties of a color. Unlike
-
# \{#adjust_color adjust-color}, which changes a color's properties by fixed
-
# amounts, \{#scale_color scale-color} fluidly changes them based on how
-
# high or low they already are. That means that lightening an already-light
-
# color with \{#scale_color scale-color} won't change the lightness much,
-
# but lightening a dark color by the same amount will change it more
-
# dramatically. This has the benefit of making `scale-color($color, ...)`
-
# have a similar effect regardless of what `$color` is.
-
#
-
# For example, the lightness of a color can be anywhere between `0%` and
-
# `100%`. If `scale-color($color, $lightness: 40%)` is called, the resulting
-
# color's lightness will be 40% of the way between its original lightness
-
# and 100. If `scale-color($color, $lightness: -40%)` is called instead, the
-
# lightness will be 40% of the way between the original and 0.
-
#
-
# This can change the red, green, blue, saturation, value, and alpha
-
# properties. The properties are specified as keyword arguments. All
-
# arguments should be percentages between `0%` and `100%`.
-
#
-
# All properties are optional. You can't specify both RGB properties
-
# (`$red`, `$green`, `$blue`) and HSL properties (`$saturation`, `$value`)
-
# at the same time.
-
#
-
# @example
-
# scale-color(hsl(120, 70%, 80%), $lightness: 50%) => hsl(120, 70%, 90%)
-
# scale-color(rgb(200, 150%, 170%), $green: -40%, $blue: 70%) => rgb(200, 90, 229)
-
# scale-color(hsl(200, 70%, 80%), $saturation: -90%, $alpha: -30%) => hsla(200, 7%, 80%, 0.7)
-
# @overload scale_color($color, [$red], [$green], [$blue], [$saturation], [$lightness], [$alpha])
-
# @param $color [Color]
-
# @param $red [Number]
-
# @param $green [Number]
-
# @param $blue [Number]
-
# @param $saturation [Number]
-
# @param $lightness [Number]
-
# @param $alpha [Number]
-
# @return [Color]
-
# @raise [ArgumentError] if any parameter is the wrong type or out-of
-
# bounds, or if RGB properties and HSL properties are adjusted at the
-
# same time
-
1
def scale_color(color, kwargs)
-
assert_type color, :Color, :color
-
with = Sass::Util.map_hash({
-
"red" => 255,
-
"green" => 255,
-
"blue" => 255,
-
"saturation" => 100,
-
"lightness" => 100,
-
"alpha" => 1
-
}) do |name, max|
-
-
next unless val = kwargs.delete(name)
-
assert_type val, :Number, name
-
if !(val.numerator_units == ['%'] && val.denominator_units.empty?)
-
raise ArgumentError.new("$#{name}: Amount #{val} must be a % (e.g. #{val.value}%)")
-
else
-
Sass::Util.check_range("$#{name}: Amount", -100..100, val, '%')
-
end
-
-
current = color.send(name)
-
scale = val.value/100.0
-
diff = scale > 0 ? max - current : current
-
[name.to_sym, current + diff*scale]
-
end
-
-
unless kwargs.empty?
-
name, val = kwargs.to_a.first
-
raise ArgumentError.new("Unknown argument $#{name} (#{val})")
-
end
-
-
color.with(with)
-
end
-
1
declare :scale_color, [:color], :var_kwargs => true
-
-
# Changes one or more properties of a color. This can change the red, green,
-
# blue, hue, saturation, value, and alpha properties. The properties are
-
# specified as keyword arguments, and replace the color's current value for
-
# that property.
-
#
-
# All properties are optional. You can't specify both RGB properties
-
# (`$red`, `$green`, `$blue`) and HSL properties (`$hue`, `$saturation`,
-
# `$value`) at the same time.
-
#
-
# @example
-
# change-color(#102030, $blue: 5) => #102005
-
# change-color(#102030, $red: 120, $blue: 5) => #782005
-
# change-color(hsl(25, 100%, 80%), $lightness: 40%, $alpha: 0.8) => hsla(25, 100%, 40%, 0.8)
-
# @overload change_color($color, [$red], [$green], [$blue], [$hue], [$saturation], [$lightness], [$alpha])
-
# @param $color [Color]
-
# @param $red [Number] The new red component for the color, within 0 and 255
-
# inclusive
-
# @param $green [Number] The new green component for the color, within 0 and
-
# 255 inclusive
-
# @param $blue [Number] The new blue component for the color, within 0 and
-
# 255 inclusive
-
# @param $hue [Number] The new hue component for the color, in degrees
-
# @param $saturation [Number] The new saturation component for the color,
-
# between `0%` and `100%` inclusive
-
# @param $lightness [Number] The new lightness component for the color,
-
# within `0%` and `100%` inclusive
-
# @param $alpha [Number] The new alpha component for the color, within 0 and
-
# 1 inclusive
-
# @return [Color]
-
# @raise [ArgumentError] if any parameter is the wrong type or out-of
-
# bounds, or if RGB properties and HSL properties are adjusted at the
-
# same time
-
1
def change_color(color, kwargs)
-
assert_type color, :Color, :color
-
with = Sass::Util.map_hash(%w[red green blue hue saturation lightness alpha]) do |name, max|
-
next unless val = kwargs.delete(name)
-
assert_type val, :Number, name
-
[name.to_sym, val.value]
-
end
-
-
unless kwargs.empty?
-
name, val = kwargs.to_a.first
-
raise ArgumentError.new("Unknown argument $#{name} (#{val})")
-
end
-
-
color.with(with)
-
end
-
1
declare :change_color, [:color], :var_kwargs => true
-
-
# Mixes two colors together. Specifically, takes the average of each of the
-
# RGB components, optionally weighted by the given percentage. The opacity
-
# of the colors is also considered when weighting the components.
-
#
-
# The weight specifies the amount of the first color that should be included
-
# in the returned color. The default, `50%`, means that half the first color
-
# and half the second color should be used. `25%` means that a quarter of
-
# the first color and three quarters of the second color should be used.
-
#
-
# @example
-
# mix(#f00, #00f) => #7f007f
-
# mix(#f00, #00f, 25%) => #3f00bf
-
# mix(rgba(255, 0, 0, 0.5), #00f) => rgba(63, 0, 191, 0.75)
-
# @overload mix($color-1, $color-2, $weight: 50%)
-
# @param $color-1 [Color]
-
# @param $color-2 [Color]
-
# @param $weight [Number] The relative weight of each color. Closer to `0%`
-
# gives more weight to `$color`, closer to `100%` gives more weight to
-
# `$color2`
-
# @return [Color]
-
# @raise [ArgumentError] if `$weight` is out of bounds or any parameter is
-
# the wrong type
-
1
def mix(color_1, color_2, weight = Number.new(50))
-
assert_type color_1, :Color, :color_1
-
assert_type color_2, :Color, :color_2
-
assert_type weight, :Number, :weight
-
-
Sass::Util.check_range("Weight", 0..100, weight, '%')
-
-
# This algorithm factors in both the user-provided weight (w) and the
-
# difference between the alpha values of the two colors (a) to decide how
-
# to perform the weighted average of the two RGB values.
-
#
-
# It works by first normalizing both parameters to be within [-1, 1],
-
# where 1 indicates "only use color_1", -1 indicates "only use color_2", and
-
# all values in between indicated a proportionately weighted average.
-
#
-
# Once we have the normalized variables w and a, we apply the formula
-
# (w + a)/(1 + w*a) to get the combined weight (in [-1, 1]) of color_1.
-
# This formula has two especially nice properties:
-
#
-
# * When either w or a are -1 or 1, the combined weight is also that number
-
# (cases where w * a == -1 are undefined, and handled as a special case).
-
#
-
# * When a is 0, the combined weight is w, and vice versa.
-
#
-
# Finally, the weight of color_1 is renormalized to be within [0, 1]
-
# and the weight of color_2 is given by 1 minus the weight of color_1.
-
p = (weight.value/100.0).to_f
-
w = p*2 - 1
-
a = color_1.alpha - color_2.alpha
-
-
w1 = (((w * a == -1) ? w : (w + a)/(1 + w*a)) + 1)/2.0
-
w2 = 1 - w1
-
-
rgb = color_1.rgb.zip(color_2.rgb).map {|v1, v2| v1*w1 + v2*w2}
-
alpha = color_1.alpha*p + color_2.alpha*(1-p)
-
Color.new(rgb + [alpha])
-
end
-
1
declare :mix, [:color_1, :color_2]
-
1
declare :mix, [:color_1, :color_2, :weight]
-
-
# Converts a color to grayscale. This is identical to `desaturate(color,
-
# 100%)`.
-
#
-
# @see #desaturate
-
# @overload grayscale($color)
-
# @param $color [Color]
-
# @return [Color]
-
# @raise [ArgumentError] if `$color` isn't a color
-
1
def grayscale(color)
-
return Sass::Script::String.new("grayscale(#{color})") if color.is_a?(Sass::Script::Number)
-
desaturate color, Number.new(100)
-
end
-
1
declare :grayscale, [:color]
-
-
# Returns the complement of a color. This is identical to `adjust-hue(color,
-
# 180deg)`.
-
#
-
# @see #adjust_hue #adjust-hue
-
# @overload complement($color)
-
# @param $color [Color]
-
# @return [Color]
-
# @raise [ArgumentError] if `$color` isn't a color
-
1
def complement(color)
-
adjust_hue color, Number.new(180)
-
end
-
1
declare :complement, [:color]
-
-
# Returns the inverse (negative) of a color. The red, green, and blue values
-
# are inverted, while the opacity is left alone.
-
#
-
# @overload invert($color)
-
# @param $color [Color]
-
# @return [Color]
-
# @raise [ArgumentError] if `$color` isn't a color
-
1
def invert(color)
-
return Sass::Script::String.new("invert(#{color})") if color.is_a?(Sass::Script::Number)
-
-
assert_type color, :Color, :color
-
color.with(
-
:red => (255 - color.red),
-
:green => (255 - color.green),
-
:blue => (255 - color.blue))
-
end
-
1
declare :invert, [:color]
-
-
# Removes quotes from a string. If the string is already unquoted, this will
-
# return it unmodified.
-
#
-
# @see #quote
-
# @example
-
# unquote("foo") => foo
-
# unquote(foo) => foo
-
# @overload unquote($string)
-
# @param $string [String]
-
# @return [String]
-
# @raise [ArgumentError] if `$string` isn't a string
-
1
def unquote(string)
-
if string.is_a?(Sass::Script::String)
-
Sass::Script::String.new(string.value, :identifier)
-
else
-
string
-
end
-
end
-
1
declare :unquote, [:string]
-
-
# Add quotes to a string if the string isn't quoted,
-
# or returns the same string if it is.
-
#
-
# @see #unquote
-
# @example
-
# quote("foo") => "foo"
-
# quote(foo) => "foo"
-
# @overload quote($string)
-
# @param $string [String]
-
# @return [String]
-
# @raise [ArgumentError] if `$string` isn't a string
-
1
def quote(string)
-
assert_type string, :String, :string
-
Sass::Script::String.new(string.value, :string)
-
end
-
1
declare :quote, [:string]
-
-
# Returns the type of a value.
-
#
-
# @example
-
# type-of(100px) => number
-
# type-of(asdf) => string
-
# type-of("asdf") => string
-
# type-of(true) => bool
-
# type-of(#fff) => color
-
# type-of(blue) => color
-
# @overload type_of($value)
-
# @param $value [Literal] The value to inspect
-
# @return [String] The unquoted string name of the value's type
-
1
def type_of(value)
-
Sass::Script::String.new(value.class.name.gsub(/Sass::Script::/,'').downcase)
-
end
-
1
declare :type_of, [:value]
-
-
# Returns the unit(s) associated with a number. Complex units are sorted in
-
# alphabetical order by numerator and denominator.
-
#
-
# @example
-
# unit(100) => ""
-
# unit(100px) => "px"
-
# unit(3em) => "em"
-
# unit(10px * 5em) => "em*px"
-
# unit(10px * 5em / 30cm / 1rem) => "em*px/cm*rem"
-
# @overload unit($number)
-
# @param $number [Number]
-
# @return [String] The unit(s) of the number, as a quoted string
-
# @raise [ArgumentError] if `$number` isn't a number
-
1
def unit(number)
-
assert_type number, :Number, :number
-
Sass::Script::String.new(number.unit_str, :string)
-
end
-
1
declare :unit, [:number]
-
-
# Returns whether a number has units.
-
#
-
# @example
-
# unitless(100) => true
-
# unitless(100px) => false
-
# @overload unitless($number)
-
# @param $number [Number]
-
# @return [Bool]
-
# @raise [ArgumentError] if `$number` isn't a number
-
1
def unitless(number)
-
assert_type number, :Number, :number
-
Sass::Script::Bool.new(number.unitless?)
-
end
-
1
declare :unitless, [:number]
-
-
# Returns whether two numbers can added, subtracted, or compared.
-
#
-
# @example
-
# comparable(2px, 1px) => true
-
# comparable(100px, 3em) => false
-
# comparable(10cm, 3mm) => true
-
# @overload comparable($number-1, $number-2)
-
# @param $number-1 [Number]
-
# @param $number-2 [Number]
-
# @return [Bool]
-
# @raise [ArgumentError] if either parameter is the wrong type
-
1
def comparable(number_1, number_2)
-
assert_type number_1, :Number, :number_1
-
assert_type number_2, :Number, :number_2
-
Sass::Script::Bool.new(number_1.comparable_to?(number_2))
-
end
-
1
declare :comparable, [:number_1, :number_2]
-
-
# Converts a unitless number to a percentage.
-
#
-
# @example
-
# percentage(0.2) => 20%
-
# percentage(100px / 50px) => 200%
-
# @overload percentage($value)
-
# @param $value [Number]
-
# @return [Number]
-
# @raise [ArgumentError] if `$value` isn't a unitless number
-
1
def percentage(value)
-
unless value.is_a?(Sass::Script::Number) && value.unitless?
-
raise ArgumentError.new("$value: #{value.inspect} is not a unitless number")
-
end
-
Sass::Script::Number.new(value.value * 100, ['%'])
-
end
-
1
declare :percentage, [:value]
-
-
# Rounds a number to the nearest whole number.
-
#
-
# @example
-
# round(10.4px) => 10px
-
# round(10.6px) => 11px
-
# @overload round($value)
-
# @param $value [Number]
-
# @return [Number]
-
# @raise [ArgumentError] if `$value` isn't a number
-
1
def round(value)
-
numeric_transformation(value) {|n| n.round}
-
end
-
1
declare :round, [:value]
-
-
# Rounds a number up to the next whole number.
-
#
-
# @example
-
# ceil(10.4px) => 11px
-
# ceil(10.6px) => 11px
-
# @overload ceil($value)
-
# @param $value [Number]
-
# @return [Number]
-
# @raise [ArgumentError] if `$value` isn't a number
-
1
def ceil(value)
-
numeric_transformation(value) {|n| n.ceil}
-
end
-
1
declare :ceil, [:value]
-
-
# Rounds a number down to the previous whole number.
-
#
-
# @example
-
# floor(10.4px) => 10px
-
# floor(10.6px) => 10px
-
# @overload floor($value)
-
# @param $value [Number]
-
# @return [Number]
-
# @raise [ArgumentError] if `$value` isn't a number
-
1
def floor(value)
-
numeric_transformation(value) {|n| n.floor}
-
end
-
1
declare :floor, [:value]
-
-
# Returns the absolute value of a number.
-
#
-
# @example
-
# abs(10px) => 10px
-
# abs(-10px) => 10px
-
# @overload abs($value)
-
# @param $value [Number]
-
# @return [Number]
-
# @raise [ArgumentError] if `$value` isn't a number
-
1
def abs(value)
-
numeric_transformation(value) {|n| n.abs}
-
end
-
1
declare :abs, [:value]
-
-
# Finds the minimum of several numbers. This function takes any number of
-
# arguments.
-
#
-
# @example
-
# min(1px, 4px) => 1px
-
# min(5em, 3em, 4em) => 3em
-
# @overload min($numbers...)
-
# @param $numbers [[Number]]
-
# @return [Number]
-
# @raise [ArgumentError] if any argument isn't a number, or if not all of
-
# the arguments have comparable units
-
1
def min(*numbers)
-
numbers.each {|n| assert_type n, :Number}
-
numbers.inject {|min, num| min.lt(num).to_bool ? min : num}
-
end
-
1
declare :min, [], :var_args => :true
-
-
# Finds the maximum of several numbers. This function takes any number of
-
# arguments.
-
#
-
# @example
-
# max(1px, 4px) => 4px
-
# max(5em, 3em, 4em) => 5em
-
# @overload max($numbers...)
-
# @param $numbers [[Number]]
-
# @return [Number]
-
# @raise [ArgumentError] if any argument isn't a number, or if not all of
-
# the arguments have comparable units
-
1
def max(*values)
-
values.each {|v| assert_type v, :Number}
-
values.inject {|max, val| max.gt(val).to_bool ? max : val}
-
end
-
1
declare :max, [], :var_args => :true
-
-
# Return the length of a list.
-
#
-
# @example
-
# length(10px) => 1
-
# length(10px 20px 30px) => 3
-
# @overload length($list)
-
# @param $list [Literal]
-
# @return [Number]
-
1
def length(list)
-
Sass::Script::Number.new(list.to_a.size)
-
end
-
1
declare :length, [:list]
-
-
# Gets the nth item in a list.
-
#
-
# Note that unlike some languages, the first item in a Sass list is number
-
# 1, the second number 2, and so forth.
-
#
-
# @example
-
# nth(10px 20px 30px, 1) => 10px
-
# nth((Helvetica, Arial, sans-serif), 3) => sans-serif
-
# @overload nth($list, $n)
-
# @param $list [Literal]
-
# @param $n [Number] The index of the item to get
-
# @return [Literal]
-
# @raise [ArgumentError] if `$n` isn't an integer between 1 and the length
-
# of `$list`
-
1
def nth(list, n)
-
assert_type n, :Number, :n
-
if !n.int?
-
raise ArgumentError.new("List index #{n} must be an integer")
-
elsif n.to_i < 1
-
raise ArgumentError.new("List index #{n} must be greater than or equal to 1")
-
elsif list.to_a.size == 0
-
raise ArgumentError.new("List index is #{n} but list has no items")
-
elsif n.to_i > (size = list.to_a.size)
-
raise ArgumentError.new("List index is #{n} but list is only #{size} item#{'s' if size != 1} long")
-
end
-
-
list.to_a[n.to_i - 1]
-
end
-
1
declare :nth, [:list, :n]
-
-
# Joins together two lists into one.
-
#
-
# Unless `$separator` is passed, if one list is comma-separated and one is
-
# space-separated, the first parameter's separator is used for the resulting
-
# list. If both lists have fewer than two items, spaces are used for the
-
# resulting list.
-
#
-
# @example
-
# join(10px 20px, 30px 40px) => 10px 20px 30px 40px
-
# join((blue, red), (#abc, #def)) => blue, red, #abc, #def
-
# join(10px, 20px) => 10px 20px
-
# join(10px, 20px, comma) => 10px, 20px
-
# join((blue, red), (#abc, #def), space) => blue red #abc #def
-
# @overload join($list1, $list2, $separator: auto)
-
# @param $list1 [Literal]
-
# @param $list2 [Literal]
-
# @param $separator [String] The list separator to use. If this is `comma`
-
# or `space`, that separator will be used. If this is `auto` (the
-
# default), the separator is determined as explained above.
-
# @return [List]
-
1
def join(list1, list2, separator = Sass::Script::String.new("auto"))
-
assert_type separator, :String, :separator
-
unless %w[auto space comma].include?(separator.value)
-
raise ArgumentError.new("Separator name must be space, comma, or auto")
-
end
-
sep1 = list1.separator if list1.is_a?(Sass::Script::List) && !list1.value.empty?
-
sep2 = list2.separator if list2.is_a?(Sass::Script::List) && !list2.value.empty?
-
Sass::Script::List.new(
-
list1.to_a + list2.to_a,
-
if separator.value == 'auto'
-
sep1 || sep2 || :space
-
else
-
separator.value.to_sym
-
end)
-
end
-
1
declare :join, [:list1, :list2]
-
1
declare :join, [:list1, :list2, :separator]
-
-
# Appends a single value onto the end of a list.
-
#
-
# Unless the `$separator` argument is passed, if the list had only one item,
-
# the resulting list will be space-separated.
-
#
-
# @example
-
# append(10px 20px, 30px) => 10px 20px 30px
-
# append((blue, red), green) => blue, red, green
-
# append(10px 20px, 30px 40px) => 10px 20px (30px 40px)
-
# append(10px, 20px, comma) => 10px, 20px
-
# append((blue, red), green, space) => blue red green
-
# @overload append($list, $val, $separator: auto)
-
# @param $list [Literal]
-
# @param $val [Literal]
-
# @param $separator [String] The list separator to use. If this is `comma`
-
# or `space`, that separator will be used. If this is `auto` (the
-
# default), the separator is determined as explained above.
-
# @return [List]
-
1
def append(list, val, separator = Sass::Script::String.new("auto"))
-
assert_type separator, :String, :separator
-
unless %w[auto space comma].include?(separator.value)
-
raise ArgumentError.new("Separator name must be space, comma, or auto")
-
end
-
sep = list.separator if list.is_a?(Sass::Script::List)
-
Sass::Script::List.new(
-
list.to_a + [val],
-
if separator.value == 'auto'
-
sep || :space
-
else
-
separator.value.to_sym
-
end)
-
end
-
1
declare :append, [:list, :val]
-
1
declare :append, [:list, :val, :separator]
-
-
# Combines several lists into a single multidimensional list. The nth value
-
# of the resulting list is a space separated list of the source lists' nth
-
# values.
-
#
-
# The length of the resulting list is the length of the
-
# shortest list.
-
#
-
# @example
-
# zip(1px 1px 3px, solid dashed solid, red green blue)
-
# => 1px solid red, 1px dashed green, 3px solid blue
-
# @overload zip($lists...)
-
# @param $lists [[Literal]]
-
# @return [List]
-
1
def zip(*lists)
-
length = nil
-
values = []
-
lists.each do |list|
-
array = list.to_a
-
values << array.dup
-
length = length.nil? ? array.length : [length, array.length].min
-
end
-
values.each do |value|
-
value.slice!(length)
-
end
-
new_list_value = values.first.zip(*values[1..-1])
-
List.new(new_list_value.map{|list| List.new(list, :space)}, :comma)
-
end
-
1
declare :zip, [], :var_args => true
-
-
-
# Returns the position of a value within a list. If the value isn't found,
-
# returns false instead.
-
#
-
# Note that unlike some languages, the first item in a Sass list is number
-
# 1, the second number 2, and so forth.
-
#
-
# @example
-
# index(1px solid red, solid) => 2
-
# index(1px solid red, dashed) => false
-
# @overload index($list, $value)
-
# @param $list [Literal]
-
# @param $value [Literal]
-
# @return [Number, Bool] The 1-based index of `$value` in `$list`, or
-
# `false`
-
1
def index(list, value)
-
index = list.to_a.index {|e| e.eq(value).to_bool }
-
if index
-
Number.new(index + 1)
-
else
-
Bool.new(false)
-
end
-
end
-
1
declare :index, [:list, :value]
-
-
# Returns one of two values, depending on whether or not `$condition` is
-
# true. Just like in `@if`, all values other than `false` and `null` are
-
# considered to be true.
-
#
-
# @example
-
# if(true, 1px, 2px) => 1px
-
# if(false, 1px, 2px) => 2px
-
# @overload if($condition, $if-true, $if-false)
-
# @param $condition [Literal] Whether the `$if-true` or `$if-false` will be
-
# returned
-
# @param $if-true [Literal]
-
# @param $if-false [Literal]
-
# @return [Literal] `$if-true` or `$if-false`
-
1
def if(condition, if_true, if_false)
-
if condition.to_bool
-
if_true
-
else
-
if_false
-
end
-
end
-
1
declare :if, [:condition, :if_true, :if_false]
-
-
# This function only exists as a workaround for IE7's [`content: counter`
-
# bug][bug]. It works identically to any other plain-CSS function, except it
-
# avoids adding spaces between the argument commas.
-
#
-
# [bug]: http://jes.st/2013/ie7s-css-breaking-content-counter-bug/
-
#
-
# @example
-
# counter(item, ".") => counter(item,".")
-
# @overload counter($args...)
-
# @return [String]
-
1
def counter(*args)
-
Sass::Script::String.new("counter(#{args.map {|a| a.to_s(options)}.join(',')})")
-
end
-
1
declare :counter, [], :var_args => true
-
-
# This function only exists as a workaround for IE7's [`content: counters`
-
# bug][bug]. It works identically to any other plain-CSS function, except it
-
# avoids adding spaces between the argument commas.
-
#
-
# [bug]: http://jes.st/2013/ie7s-css-breaking-content-counter-bug/
-
#
-
# @example
-
# counters(item, ".") => counters(item,".")
-
# @overload counters($args...)
-
# @return [String]
-
1
def counters(*args)
-
Sass::Script::String.new("counters(#{args.map {|a| a.to_s(options)}.join(',')})")
-
end
-
1
declare :counters, [], :var_args => true
-
-
1
private
-
-
# This method implements the pattern of transforming a numeric value into
-
# another numeric value with the same units.
-
# It yields a number to a block to perform the operation and return a number
-
1
def numeric_transformation(value)
-
assert_type value, :Number, :value
-
Sass::Script::Number.new(yield(value.value), value.numerator_units, value.denominator_units)
-
end
-
-
1
def _adjust(color, amount, attr, range, op, units = "")
-
assert_type color, :Color, :color
-
assert_type amount, :Number, :amount
-
Sass::Util.check_range('Amount', range, amount, units)
-
-
# TODO: is it worth restricting here,
-
# or should we do so in the Color constructor itself,
-
# and allow clipping in rgb() et al?
-
color.with(attr => Sass::Util.restrict(
-
color.send(attr).send(op, amount.value), range))
-
end
-
end
-
end
-
1
module Sass::Script
-
# A SassScript object representing `#{}` interpolation outside a string.
-
#
-
# @see StringInterpolation
-
1
class Interpolation < Node
-
# Interpolation in a property is of the form `before #{mid} after`.
-
#
-
# @param before [Node] The SassScript before the interpolation
-
# @param mid [Node] The SassScript within the interpolation
-
# @param after [Node] The SassScript after the interpolation
-
# @param wb [Boolean] Whether there was whitespace between `before` and `#{`
-
# @param wa [Boolean] Whether there was whitespace between `}` and `after`
-
# @param originally_text [Boolean]
-
# Whether the original format of the interpolation was plain text,
-
# not an interpolation.
-
# This is used when converting back to SassScript.
-
1
def initialize(before, mid, after, wb, wa, originally_text = false)
-
@before = before
-
@mid = mid
-
@after = after
-
@whitespace_before = wb
-
@whitespace_after = wa
-
@originally_text = originally_text
-
end
-
-
# @return [String] A human-readable s-expression representation of the interpolation
-
1
def inspect
-
"(interpolation #{@before.inspect} #{@mid.inspect} #{@after.inspect})"
-
end
-
-
# @see Node#to_sass
-
1
def to_sass(opts = {})
-
res = ""
-
res << @before.to_sass(opts) if @before
-
res << ' ' if @before && @whitespace_before
-
res << '#{' unless @originally_text
-
res << @mid.to_sass(opts)
-
res << '}' unless @originally_text
-
res << ' ' if @after && @whitespace_after
-
res << @after.to_sass(opts) if @after
-
res
-
end
-
-
# Returns the three components of the interpolation, `before`, `mid`, and `after`.
-
#
-
# @return [Array<Node>]
-
# @see #initialize
-
# @see Node#children
-
1
def children
-
[@before, @mid, @after].compact
-
end
-
-
# @see Node#deep_copy
-
1
def deep_copy
-
node = dup
-
node.instance_variable_set('@before', @before.deep_copy) if @before
-
node.instance_variable_set('@mid', @mid.deep_copy)
-
node.instance_variable_set('@after', @after.deep_copy) if @after
-
node
-
end
-
-
1
protected
-
-
# Evaluates the interpolation.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Sass::Script::String] The SassScript string that is the value of the interpolation
-
1
def _perform(environment)
-
res = ""
-
res << @before.perform(environment).to_s if @before
-
res << " " if @before && @whitespace_before
-
val = @mid.perform(environment)
-
res << (val.is_a?(Sass::Script::String) ? val.value : val.to_s)
-
res << " " if @after && @whitespace_after
-
res << @after.perform(environment).to_s if @after
-
opts(Sass::Script::String.new(res))
-
end
-
end
-
end
-
1
require 'sass/scss/rx'
-
-
1
module Sass
-
1
module Script
-
# The lexical analyzer for SassScript.
-
# It takes a raw string and converts it to individual tokens
-
# that are easier to parse.
-
1
class Lexer
-
1
include Sass::SCSS::RX
-
-
# A struct containing information about an individual token.
-
#
-
# `type`: \[`Symbol`\]
-
# : The type of token.
-
#
-
# `value`: \[`Object`\]
-
# : The Ruby object corresponding to the value of the token.
-
#
-
# `line`: \[`Fixnum`\]
-
# : The line of the source file on which the token appears.
-
#
-
# `offset`: \[`Fixnum`\]
-
# : The number of bytes into the line the SassScript token appeared.
-
#
-
# `pos`: \[`Fixnum`\]
-
# : The scanner position at which the SassScript token appeared.
-
1
Token = Struct.new(:type, :value, :line, :offset, :pos)
-
-
# The line number of the lexer's current position.
-
#
-
# @return [Fixnum]
-
1
attr_reader :line
-
-
# The number of bytes into the current line
-
# of the lexer's current position.
-
#
-
# @return [Fixnum]
-
1
attr_reader :offset
-
-
# A hash from operator strings to the corresponding token types.
-
1
OPERATORS = {
-
'+' => :plus,
-
'-' => :minus,
-
'*' => :times,
-
'/' => :div,
-
'%' => :mod,
-
'=' => :single_eq,
-
':' => :colon,
-
'(' => :lparen,
-
')' => :rparen,
-
',' => :comma,
-
'and' => :and,
-
'or' => :or,
-
'not' => :not,
-
'==' => :eq,
-
'!=' => :neq,
-
'>=' => :gte,
-
'<=' => :lte,
-
'>' => :gt,
-
'<' => :lt,
-
'#{' => :begin_interpolation,
-
'}' => :end_interpolation,
-
';' => :semicolon,
-
'{' => :lcurly,
-
'...' => :splat,
-
}
-
-
25
OPERATORS_REVERSE = Sass::Util.map_hash(OPERATORS) {|k, v| [v, k]}
-
-
25
TOKEN_NAMES = Sass::Util.map_hash(OPERATORS_REVERSE) {|k, v| [k, v.inspect]}.merge({
-
:const => "variable (e.g. $foo)",
-
:ident => "identifier (e.g. middle)"
-
})
-
-
# A list of operator strings ordered with longer names first
-
# so that `>` and `<` don't clobber `>=` and `<=`.
-
25
OP_NAMES = OPERATORS.keys.sort_by {|o| -o.size}
-
-
# A sub-list of {OP_NAMES} that only includes operators
-
# with identifier names.
-
25
IDENT_OP_NAMES = OP_NAMES.select {|k, v| k =~ /^\w+/}
-
-
# A hash of regular expressions that are used for tokenizing.
-
1
REGULAR_EXPRESSIONS = {
-
:whitespace => /\s+/,
-
:comment => COMMENT,
-
:single_line_comment => SINGLE_LINE_COMMENT,
-
:variable => /(\$)(#{IDENT})/,
-
:ident => /(#{IDENT})(\()?/,
-
:number => /(-)?(?:(\d*\.\d+)|(\d+))([a-zA-Z%]+)?/,
-
:color => HEXCOLOR,
-
3
:ident_op => %r{(#{Regexp.union(*IDENT_OP_NAMES.map{|s| Regexp.new(Regexp.escape(s) + "(?!#{NMCHAR}|\Z)")})})},
-
:op => %r{(#{Regexp.union(*OP_NAMES)})},
-
}
-
-
1
class << self
-
1
private
-
1
def string_re(open, close)
-
4
/#{open}((?:\\.|\#(?!\{)|[^#{close}\\#])*)(#{close}|#\{)/
-
end
-
end
-
-
# A hash of regular expressions that are used for tokenizing strings.
-
#
-
# The key is a `[Symbol, Boolean]` pair.
-
# The symbol represents which style of quotation to use,
-
# while the boolean represents whether or not the string
-
# is following an interpolated segment.
-
1
STRING_REGULAR_EXPRESSIONS = {
-
:double => {
-
false => string_re('"', '"'),
-
true => string_re('', '"')
-
},
-
:single => {
-
false => string_re("'", "'"),
-
true => string_re('', "'")
-
},
-
:uri => {
-
false => /url\(#{W}(#{URLCHAR}*?)(#{W}\)|#\{)/,
-
true => /(#{URLCHAR}*?)(#{W}\)|#\{)/
-
},
-
# Defined in https://developer.mozilla.org/en/CSS/@-moz-document as a
-
# non-standard version of http://www.w3.org/TR/css3-conditional/
-
:url_prefix => {
-
false => /url-prefix\(#{W}(#{URLCHAR}*?)(#{W}\)|#\{)/,
-
true => /(#{URLCHAR}*?)(#{W}\)|#\{)/
-
},
-
:domain => {
-
false => /domain\(#{W}(#{URLCHAR}*?)(#{W}\)|#\{)/,
-
true => /(#{URLCHAR}*?)(#{W}\)|#\{)/
-
}
-
}
-
-
# @param str [String, StringScanner] The source text to lex
-
# @param line [Fixnum] The line on which the SassScript appears.
-
# Used for error reporting
-
# @param offset [Fixnum] The number of characters in on which the SassScript appears.
-
# Used for error reporting
-
# @param options [{Symbol => Object}] An options hash;
-
# see {file:SASS_REFERENCE.md#sass_options the Sass options documentation}
-
1
def initialize(str, line, offset, options)
-
@scanner = str.is_a?(StringScanner) ? str : Sass::Util::MultibyteStringScanner.new(str)
-
@line = line
-
@offset = offset
-
@options = options
-
@interpolation_stack = []
-
@prev = nil
-
end
-
-
# Moves the lexer forward one token.
-
#
-
# @return [Token] The token that was moved past
-
1
def next
-
@tok ||= read_token
-
@tok, tok = nil, @tok
-
@prev = tok
-
return tok
-
end
-
-
# Returns whether or not there's whitespace before the next token.
-
#
-
# @return [Boolean]
-
1
def whitespace?(tok = @tok)
-
if tok
-
@scanner.string[0...tok.pos] =~ /\s\Z/
-
else
-
@scanner.string[@scanner.pos, 1] =~ /^\s/ ||
-
@scanner.string[@scanner.pos - 1, 1] =~ /\s\Z/
-
end
-
end
-
-
# Returns the next token without moving the lexer forward.
-
#
-
# @return [Token] The next token
-
1
def peek
-
@tok ||= read_token
-
end
-
-
# Rewinds the underlying StringScanner
-
# to before the token returned by \{#peek}.
-
1
def unpeek!
-
@scanner.pos = @tok.pos if @tok
-
end
-
-
# @return [Boolean] Whether or not there's more source text to lex.
-
1
def done?
-
whitespace unless after_interpolation? && @interpolation_stack.last
-
@scanner.eos? && @tok.nil?
-
end
-
-
# @return [Boolean] Whether or not the last token lexed was `:end_interpolation`.
-
1
def after_interpolation?
-
@prev && @prev.type == :end_interpolation
-
end
-
-
# Raise an error to the effect that `name` was expected in the input stream
-
# and wasn't found.
-
#
-
# This calls \{#unpeek!} to rewind the scanner to immediately after
-
# the last returned token.
-
#
-
# @param name [String] The name of the entity that was expected but not found
-
# @raise [Sass::SyntaxError]
-
1
def expected!(name)
-
unpeek!
-
Sass::SCSS::Parser.expected(@scanner, name, @line)
-
end
-
-
# Records all non-comment text the lexer consumes within the block
-
# and returns it as a string.
-
#
-
# @yield A block in which text is recorded
-
# @return [String]
-
1
def str
-
old_pos = @tok ? @tok.pos : @scanner.pos
-
yield
-
new_pos = @tok ? @tok.pos : @scanner.pos
-
@scanner.string[old_pos...new_pos]
-
end
-
-
1
private
-
-
1
def read_token
-
return if done?
-
return unless value = token
-
type, val, size = value
-
size ||= @scanner.matched_size
-
-
val.line = @line if val.is_a?(Script::Node)
-
Token.new(type, val, @line,
-
current_position - size, @scanner.pos - size)
-
end
-
-
1
def whitespace
-
nil while scan(REGULAR_EXPRESSIONS[:whitespace]) ||
-
scan(REGULAR_EXPRESSIONS[:comment]) ||
-
scan(REGULAR_EXPRESSIONS[:single_line_comment])
-
end
-
-
1
def token
-
if after_interpolation? && (interp_type = @interpolation_stack.pop)
-
return string(interp_type, true)
-
end
-
-
variable || string(:double, false) || string(:single, false) || number || color ||
-
string(:uri, false) || raw(UNICODERANGE) || special_fun || special_val || ident_op ||
-
ident || op
-
end
-
-
1
def variable
-
_variable(REGULAR_EXPRESSIONS[:variable])
-
end
-
-
1
def _variable(rx)
-
return unless scan(rx)
-
-
[:const, @scanner[2]]
-
end
-
-
1
def ident
-
return unless scan(REGULAR_EXPRESSIONS[:ident])
-
[@scanner[2] ? :funcall : :ident, @scanner[1]]
-
end
-
-
1
def string(re, open)
-
return unless scan(STRING_REGULAR_EXPRESSIONS[re][open])
-
if @scanner[2] == '#{' #'
-
@scanner.pos -= 2 # Don't actually consume the #{
-
@interpolation_stack << re
-
end
-
str =
-
if re == :uri
-
Script::String.new("#{'url(' unless open}#{@scanner[1]}#{')' unless @scanner[2] == '#{'}")
-
else
-
Script::String.new(@scanner[1].gsub(/\\(['"]|\#\{)/, '\1'), :string)
-
end
-
[:string, str]
-
end
-
-
1
def number
-
return unless scan(REGULAR_EXPRESSIONS[:number])
-
value = @scanner[2] ? @scanner[2].to_f : @scanner[3].to_i
-
value = -value if @scanner[1]
-
[:number, Script::Number.new(value, Array(@scanner[4]))]
-
end
-
-
1
def color
-
return unless s = scan(REGULAR_EXPRESSIONS[:color])
-
raise Sass::SyntaxError.new(<<MESSAGE.rstrip) unless s.size == 4 || s.size == 7
-
Colors must have either three or six digits: '#{s}'
-
MESSAGE
-
value = s.scan(/^#(..?)(..?)(..?)$/).first.
-
map {|num| num.ljust(2, num).to_i(16)}
-
[:color, Script::Color.new(value)]
-
end
-
-
1
def special_fun
-
return unless str1 = scan(/((-[\w-]+-)?(calc|element)|expression|progid:[a-z\.]*)\(/i)
-
str2, _ = Sass::Shared.balance(@scanner, ?(, ?), 1)
-
c = str2.count("\n")
-
old_line = @line
-
old_offset = @offset
-
@line += c
-
@offset = (c == 0 ? @offset + str2.size : str2[/\n(.*)/, 1].size)
-
[:special_fun,
-
Sass::Util.merge_adjacent_strings(
-
[str1] + Sass::Engine.parse_interp(str2, old_line, old_offset, @options)),
-
str1.size + str2.size]
-
end
-
-
1
def special_val
-
return unless scan(/!important/i)
-
[:string, Script::String.new("!important")]
-
end
-
-
1
def ident_op
-
return unless op = scan(REGULAR_EXPRESSIONS[:ident_op])
-
[OPERATORS[op]]
-
end
-
-
1
def op
-
return unless op = scan(REGULAR_EXPRESSIONS[:op])
-
@interpolation_stack << nil if op == :begin_interpolation
-
[OPERATORS[op]]
-
end
-
-
1
def raw(rx)
-
return unless val = scan(rx)
-
[:raw, val]
-
end
-
-
1
def scan(re)
-
return unless str = @scanner.scan(re)
-
c = str.count("\n")
-
@line += c
-
@offset = (c == 0 ? @offset + str.size : str[/\n(.*)/, 1].size)
-
str
-
end
-
-
1
def current_position
-
@offset + 1
-
end
-
end
-
end
-
end
-
1
module Sass::Script
-
# A SassScript object representing a CSS list.
-
# This includes both comma-separated lists and space-separated lists.
-
1
class List < Literal
-
# The Ruby array containing the contents of the list.
-
#
-
# @return [Array<Literal>]
-
1
attr_reader :value
-
1
alias_method :children, :value
-
1
alias_method :to_a, :value
-
-
# The operator separating the values of the list.
-
# Either `:comma` or `:space`.
-
#
-
# @return [Symbol]
-
1
attr_reader :separator
-
-
# Creates a new list.
-
#
-
# @param value [Array<Literal>] See \{#value}
-
# @param separator [String] See \{#separator}
-
1
def initialize(value, separator)
-
super(value)
-
@separator = separator
-
end
-
-
# @see Node#deep_copy
-
1
def deep_copy
-
node = dup
-
node.instance_variable_set('@value', value.map {|c| c.deep_copy})
-
node
-
end
-
-
# @see Node#eq
-
1
def eq(other)
-
Sass::Script::Bool.new(
-
other.is_a?(List) && self.value == other.value &&
-
self.separator == other.separator)
-
end
-
-
# @see Node#to_s
-
1
def to_s(opts = {})
-
raise Sass::SyntaxError.new("() isn't a valid CSS value.") if value.empty?
-
return value.reject {|e| e.is_a?(Null) || e.is_a?(List) && e.value.empty?}.map {|e| e.to_s(opts)}.join(sep_str)
-
end
-
-
# @see Node#to_sass
-
1
def to_sass(opts = {})
-
return "()" if value.empty?
-
precedence = Sass::Script::Parser.precedence_of(separator)
-
value.reject {|e| e.is_a?(Null)}.map do |v|
-
if v.is_a?(List) && Sass::Script::Parser.precedence_of(v.separator) <= precedence ||
-
separator == :space && v.is_a?(UnaryOperation) && (v.operator == :minus || v.operator == :plus)
-
"(#{v.to_sass(opts)})"
-
else
-
v.to_sass(opts)
-
end
-
end.join(sep_str(nil))
-
end
-
-
# @see Node#inspect
-
1
def inspect
-
"(#{to_sass})"
-
end
-
-
1
protected
-
-
# @see Node#_perform
-
1
def _perform(environment)
-
list = Sass::Script::List.new(
-
value.map {|e| e.perform(environment)},
-
separator)
-
list.options = self.options
-
list
-
end
-
-
1
private
-
-
1
def sep_str(opts = self.options)
-
return ' ' if separator == :space
-
return ',' if opts && opts[:style] == :compressed
-
return ', '
-
end
-
end
-
end
-
1
module Sass::Script
-
# The abstract superclass for SassScript objects.
-
#
-
# Many of these methods, especially the ones that correspond to SassScript operations,
-
# are designed to be overridden by subclasses which may change the semantics somewhat.
-
# The operations listed here are just the defaults.
-
1
class Literal < Node
-
1
require 'sass/script/string'
-
1
require 'sass/script/number'
-
1
require 'sass/script/color'
-
1
require 'sass/script/bool'
-
1
require 'sass/script/null'
-
1
require 'sass/script/list'
-
1
require 'sass/script/arg_list'
-
-
# Returns the Ruby value of the literal.
-
# The type of this value varies based on the subclass.
-
#
-
# @return [Object]
-
1
attr_reader :value
-
-
# Creates a new literal.
-
#
-
# @param value [Object] The object for \{#value}
-
1
def initialize(value = nil)
-
@value = value
-
super()
-
end
-
-
# Returns an empty array.
-
#
-
# @return [Array<Node>] empty
-
# @see Node#children
-
1
def children
-
[]
-
end
-
-
# @see Node#deep_copy
-
1
def deep_copy
-
dup
-
end
-
-
# Returns the options hash for this node.
-
#
-
# @return [{Symbol => Object}]
-
# @raise [Sass::SyntaxError] if the options hash hasn't been set.
-
# This should only happen when the literal was created
-
# outside of the parser and \{#to\_s} was called on it
-
1
def options
-
opts = super
-
return opts if opts
-
raise Sass::SyntaxError.new(<<MSG)
-
The #options attribute is not set on this #{self.class}.
-
This error is probably occurring because #to_s was called
-
on this literal within a custom Sass function without first
-
setting the #option attribute.
-
MSG
-
end
-
-
# The SassScript `==` operation.
-
# **Note that this returns a {Sass::Script::Bool} object,
-
# not a Ruby boolean**.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Bool] True if this literal is the same as the other,
-
# false otherwise
-
1
def eq(other)
-
Sass::Script::Bool.new(self.class == other.class && self.value == other.value)
-
end
-
-
# The SassScript `!=` operation.
-
# **Note that this returns a {Sass::Script::Bool} object,
-
# not a Ruby boolean**.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Bool] False if this literal is the same as the other,
-
# true otherwise
-
1
def neq(other)
-
Sass::Script::Bool.new(!eq(other).to_bool)
-
end
-
-
# The SassScript `==` operation.
-
# **Note that this returns a {Sass::Script::Bool} object,
-
# not a Ruby boolean**.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Bool] True if this literal is the same as the other,
-
# false otherwise
-
1
def unary_not
-
Sass::Script::Bool.new(!to_bool)
-
end
-
-
# The SassScript `=` operation
-
# (used for proprietary MS syntax like `alpha(opacity=20)`).
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Script::String] A string containing both literals
-
# separated by `"="`
-
1
def single_eq(other)
-
Sass::Script::String.new("#{self.to_s}=#{other.to_s}")
-
end
-
-
# The SassScript `+` operation.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Script::String] A string containing both literals
-
# without any separation
-
1
def plus(other)
-
if other.is_a?(Sass::Script::String)
-
return Sass::Script::String.new(self.to_s + other.value, other.type)
-
end
-
Sass::Script::String.new(self.to_s + other.to_s)
-
end
-
-
# The SassScript `-` operation.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Script::String] A string containing both literals
-
# separated by `"-"`
-
1
def minus(other)
-
Sass::Script::String.new("#{self.to_s}-#{other.to_s}")
-
end
-
-
# The SassScript `/` operation.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Script::String] A string containing both literals
-
# separated by `"/"`
-
1
def div(other)
-
Sass::Script::String.new("#{self.to_s}/#{other.to_s}")
-
end
-
-
# The SassScript unary `+` operation (e.g. `+$a`).
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Script::String] A string containing the literal
-
# preceded by `"+"`
-
1
def unary_plus
-
Sass::Script::String.new("+#{self.to_s}")
-
end
-
-
# The SassScript unary `-` operation (e.g. `-$a`).
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Script::String] A string containing the literal
-
# preceded by `"-"`
-
1
def unary_minus
-
Sass::Script::String.new("-#{self.to_s}")
-
end
-
-
# The SassScript unary `/` operation (e.g. `/$a`).
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Script::String] A string containing the literal
-
# preceded by `"/"`
-
1
def unary_div
-
Sass::Script::String.new("/#{self.to_s}")
-
end
-
-
# @return [String] A readable representation of the literal
-
1
def inspect
-
value.inspect
-
end
-
-
# @return [Boolean] `true` (the Ruby boolean value)
-
1
def to_bool
-
true
-
end
-
-
# Compares this object with another.
-
#
-
# @param other [Object] The object to compare with
-
# @return [Boolean] Whether or not this literal is equivalent to `other`
-
1
def ==(other)
-
eq(other).to_bool
-
end
-
-
# @return [Fixnum] The integer value of this literal
-
# @raise [Sass::SyntaxError] if this literal isn't an integer
-
1
def to_i
-
raise Sass::SyntaxError.new("#{self.inspect} is not an integer.")
-
end
-
-
# @raise [Sass::SyntaxError] if this literal isn't an integer
-
1
def assert_int!; to_i; end
-
-
# Returns the value of this literal as a list.
-
# Single literals are considered the same as single-element lists.
-
#
-
# @return [Array<Literal>] The of this literal as a list
-
1
def to_a
-
[self]
-
end
-
-
# Returns the string representation of this literal
-
# as it would be output to the CSS document.
-
#
-
# @return [String]
-
1
def to_s(opts = {})
-
raise Sass::SyntaxError.new("[BUG] All subclasses of Sass::Literal must implement #to_s.")
-
end
-
1
alias_method :to_sass, :to_s
-
-
# Returns whether or not this object is null.
-
#
-
# @return [Boolean] `false`
-
1
def null?
-
false
-
end
-
-
1
protected
-
-
# Evaluates the literal.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Literal] This literal
-
1
def _perform(environment)
-
self
-
end
-
end
-
end
-
1
module Sass::Script
-
# The abstract superclass for SassScript parse tree nodes.
-
#
-
# Use \{#perform} to evaluate a parse tree.
-
1
class Node
-
# The options hash for this node.
-
#
-
# @return [{Symbol => Object}]
-
1
attr_reader :options
-
-
# The line of the document on which this node appeared.
-
#
-
# @return [Fixnum]
-
1
attr_accessor :line
-
-
# Sets the options hash for this node,
-
# as well as for all child nodes.
-
# See {file:SASS_REFERENCE.md#sass_options the Sass options documentation}.
-
#
-
# @param options [{Symbol => Object}] The options
-
1
def options=(options)
-
@options = options
-
children.each do |c|
-
if c.is_a? Hash
-
c.values.each {|v| v.options = options }
-
else
-
c.options = options
-
end
-
end
-
end
-
-
# Evaluates the node.
-
#
-
# \{#perform} shouldn't be overridden directly;
-
# instead, override \{#\_perform}.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Literal] The SassScript object that is the value of the SassScript
-
1
def perform(environment)
-
_perform(environment)
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:line => line)
-
raise e
-
end
-
-
# Returns all child nodes of this node.
-
#
-
# @return [Array<Node>]
-
1
def children
-
Sass::Util.abstract(self)
-
end
-
-
# Returns the text of this SassScript expression.
-
#
-
# @return [String]
-
1
def to_sass(opts = {})
-
Sass::Util.abstract(self)
-
end
-
-
# Returns a deep clone of this node.
-
# The child nodes are cloned, but options are not.
-
#
-
# @return [Node]
-
1
def deep_copy
-
Sass::Util.abstract(self)
-
end
-
-
1
protected
-
-
# Converts underscores to dashes if the :dasherize option is set.
-
1
def dasherize(s, opts)
-
if opts[:dasherize]
-
s.gsub(/_/,'-')
-
else
-
s
-
end
-
end
-
-
# Evaluates this node.
-
# Note that all {Literal} objects created within this method
-
# should have their \{#options} attribute set, probably via \{#opts}.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Literal] The SassScript object that is the value of the SassScript
-
# @see #perform
-
1
def _perform(environment)
-
Sass::Util.abstract(self)
-
end
-
-
# Sets the \{#options} field on the given literal and returns it
-
#
-
# @param literal [Literal]
-
# @return [Literal]
-
1
def opts(literal)
-
literal.options = options
-
literal
-
end
-
end
-
end
-
1
require 'sass/script/literal'
-
-
1
module Sass::Script
-
# A SassScript object representing a null value.
-
1
class Null < Literal
-
# Creates a new null literal.
-
1
def initialize
-
super nil
-
end
-
-
# @return [Boolean] `false` (the Ruby boolean value)
-
1
def to_bool
-
false
-
end
-
-
# @return [Boolean] `true`
-
1
def null?
-
true
-
end
-
-
# @return [String] '' (An empty string)
-
1
def to_s(opts = {})
-
''
-
end
-
-
1
def to_sass(opts = {})
-
'null'
-
end
-
-
# Returns a string representing a null value.
-
#
-
# @return [String]
-
1
def inspect
-
'null'
-
end
-
end
-
end
-
1
require 'sass/script/literal'
-
-
1
module Sass::Script
-
# A SassScript object representing a number.
-
# SassScript numbers can have decimal values,
-
# and can also have units.
-
# For example, `12`, `1px`, and `10.45em`
-
# are all valid values.
-
#
-
# Numbers can also have more complex units, such as `1px*em/in`.
-
# These cannot be inputted directly in Sass code at the moment.
-
1
class Number < Literal
-
# The Ruby value of the number.
-
#
-
# @return [Numeric]
-
1
attr_reader :value
-
-
# A list of units in the numerator of the number.
-
# For example, `1px*em/in*cm` would return `["px", "em"]`
-
# @return [Array<String>]
-
1
attr_reader :numerator_units
-
-
# A list of units in the denominator of the number.
-
# For example, `1px*em/in*cm` would return `["in", "cm"]`
-
# @return [Array<String>]
-
1
attr_reader :denominator_units
-
-
# The original representation of this number.
-
# For example, although the result of `1px/2px` is `0.5`,
-
# the value of `#original` is `"1px/2px"`.
-
#
-
# This is only non-nil when the original value should be used as the CSS value,
-
# as in `font: 1px/2px`.
-
#
-
# @return [Boolean, nil]
-
1
attr_accessor :original
-
-
1
def self.precision
-
@precision ||= 5
-
end
-
-
# Sets the number of digits of precision
-
# For example, if this is `3`,
-
# `3.1415926` will be printed as `3.142`.
-
1
def self.precision=(digits)
-
@precision = digits.round
-
@precision_factor = 10.0**@precision
-
end
-
-
# the precision factor used in numeric output
-
# it is derived from the `precision` method.
-
1
def self.precision_factor
-
@precision_factor ||= 10.0**precision
-
end
-
-
# Handles the deprecation warning for the PRECISION constant
-
# This can be removed in 3.2.
-
1
def self.const_missing(const)
-
if const == :PRECISION
-
Sass::Util.sass_warn("Sass::Script::Number::PRECISION is deprecated and will be removed in a future release. Use Sass::Script::Number.precision_factor instead.")
-
const_set(:PRECISION, self.precision_factor)
-
else
-
super
-
end
-
end
-
-
# Used so we don't allocate two new arrays for each new number.
-
1
NO_UNITS = []
-
-
# @param value [Numeric] The value of the number
-
# @param numerator_units [Array<String>] See \{#numerator\_units}
-
# @param denominator_units [Array<String>] See \{#denominator\_units}
-
1
def initialize(value, numerator_units = NO_UNITS, denominator_units = NO_UNITS)
-
super(value)
-
@numerator_units = numerator_units
-
@denominator_units = denominator_units
-
normalize!
-
end
-
-
# The SassScript `+` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Adds the two numbers together, converting units if possible.
-
#
-
# {Color}
-
# : Adds this number to each of the RGB color channels.
-
#
-
# {Literal}
-
# : See {Literal#plus}.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Literal] The result of the operation
-
# @raise [Sass::UnitConversionError] if `other` is a number with incompatible units
-
1
def plus(other)
-
if other.is_a? Number
-
operate(other, :+)
-
elsif other.is_a?(Color)
-
other.plus(self)
-
else
-
super
-
end
-
end
-
-
# The SassScript binary `-` operation (e.g. `$a - $b`).
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Subtracts this number from the other, converting units if possible.
-
#
-
# {Literal}
-
# : See {Literal#minus}.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Literal] The result of the operation
-
# @raise [Sass::UnitConversionError] if `other` is a number with incompatible units
-
1
def minus(other)
-
if other.is_a? Number
-
operate(other, :-)
-
else
-
super
-
end
-
end
-
-
# The SassScript unary `+` operation (e.g. `+$a`).
-
#
-
# @return [Number] The value of this number
-
1
def unary_plus
-
self
-
end
-
-
# The SassScript unary `-` operation (e.g. `-$a`).
-
#
-
# @return [Number] The negative value of this number
-
1
def unary_minus
-
Number.new(-value, @numerator_units, @denominator_units)
-
end
-
-
# The SassScript `*` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Multiplies the two numbers together, converting units appropriately.
-
#
-
# {Color}
-
# : Multiplies each of the RGB color channels by this number.
-
#
-
# @param other [Number, Color] The right-hand side of the operator
-
# @return [Number, Color] The result of the operation
-
# @raise [NoMethodError] if `other` is an invalid type
-
1
def times(other)
-
if other.is_a? Number
-
operate(other, :*)
-
elsif other.is_a? Color
-
other.times(self)
-
else
-
raise NoMethodError.new(nil, :times)
-
end
-
end
-
-
# The SassScript `/` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Divides this number by the other, converting units appropriately.
-
#
-
# {Literal}
-
# : See {Literal#div}.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Literal] The result of the operation
-
1
def div(other)
-
if other.is_a? Number
-
res = operate(other, :/)
-
if self.original && other.original
-
res.original = "#{self.original}/#{other.original}"
-
end
-
res
-
else
-
super
-
end
-
end
-
-
# The SassScript `%` operation.
-
#
-
# @param other [Number] The right-hand side of the operator
-
# @return [Number] This number modulo the other
-
# @raise [NoMethodError] if `other` is an invalid type
-
# @raise [Sass::UnitConversionError] if `other` has any units
-
1
def mod(other)
-
if other.is_a?(Number)
-
unless other.unitless?
-
raise Sass::UnitConversionError.new("Cannot modulo by a number with units: #{other.inspect}.")
-
end
-
operate(other, :%)
-
else
-
raise NoMethodError.new(nil, :mod)
-
end
-
end
-
-
# The SassScript `==` operation.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Boolean] Whether this number is equal to the other object
-
1
def eq(other)
-
return Sass::Script::Bool.new(false) unless other.is_a?(Sass::Script::Number)
-
this = self
-
begin
-
if unitless?
-
this = this.coerce(other.numerator_units, other.denominator_units)
-
else
-
other = other.coerce(@numerator_units, @denominator_units)
-
end
-
rescue Sass::UnitConversionError
-
return Sass::Script::Bool.new(false)
-
end
-
-
Sass::Script::Bool.new(this.value == other.value)
-
end
-
-
# The SassScript `>` operation.
-
#
-
# @param other [Number] The right-hand side of the operator
-
# @return [Boolean] Whether this number is greater than the other
-
# @raise [NoMethodError] if `other` is an invalid type
-
1
def gt(other)
-
raise NoMethodError.new(nil, :gt) unless other.is_a?(Number)
-
operate(other, :>)
-
end
-
-
# The SassScript `>=` operation.
-
#
-
# @param other [Number] The right-hand side of the operator
-
# @return [Boolean] Whether this number is greater than or equal to the other
-
# @raise [NoMethodError] if `other` is an invalid type
-
1
def gte(other)
-
raise NoMethodError.new(nil, :gte) unless other.is_a?(Number)
-
operate(other, :>=)
-
end
-
-
# The SassScript `<` operation.
-
#
-
# @param other [Number] The right-hand side of the operator
-
# @return [Boolean] Whether this number is less than the other
-
# @raise [NoMethodError] if `other` is an invalid type
-
1
def lt(other)
-
raise NoMethodError.new(nil, :lt) unless other.is_a?(Number)
-
operate(other, :<)
-
end
-
-
# The SassScript `<=` operation.
-
#
-
# @param other [Number] The right-hand side of the operator
-
# @return [Boolean] Whether this number is less than or equal to the other
-
# @raise [NoMethodError] if `other` is an invalid type
-
1
def lte(other)
-
raise NoMethodError.new(nil, :lte) unless other.is_a?(Number)
-
operate(other, :<=)
-
end
-
-
# @return [String] The CSS representation of this number
-
# @raise [Sass::SyntaxError] if this number has units that can't be used in CSS
-
# (e.g. `px*in`)
-
1
def to_s(opts = {})
-
return original if original
-
raise Sass::SyntaxError.new("#{inspect} isn't a valid CSS value.") unless legal_units?
-
inspect
-
end
-
-
# Returns a readable representation of this number.
-
#
-
# This representation is valid CSS (and valid SassScript)
-
# as long as there is only one unit.
-
#
-
# @return [String] The representation
-
1
def inspect(opts = {})
-
value = self.class.round(self.value)
-
unitless? ? value.to_s : "#{value}#{unit_str}"
-
end
-
1
alias_method :to_sass, :inspect
-
-
# @return [Fixnum] The integer value of the number
-
# @raise [Sass::SyntaxError] if the number isn't an integer
-
1
def to_i
-
super unless int?
-
return value
-
end
-
-
# @return [Boolean] Whether or not this number is an integer.
-
1
def int?
-
value % 1 == 0.0
-
end
-
-
# @return [Boolean] Whether or not this number has no units.
-
1
def unitless?
-
@numerator_units.empty? && @denominator_units.empty?
-
end
-
-
# @return [Boolean] Whether or not this number has units that can be represented in CSS
-
# (that is, zero or one \{#numerator\_units}).
-
1
def legal_units?
-
(@numerator_units.empty? || @numerator_units.size == 1) && @denominator_units.empty?
-
end
-
-
# Returns this number converted to other units.
-
# The conversion takes into account the relationship between e.g. mm and cm,
-
# as well as between e.g. in and cm.
-
#
-
# If this number has no units, it will simply return itself
-
# with the given units.
-
#
-
# An incompatible coercion, e.g. between px and cm, will raise an error.
-
#
-
# @param num_units [Array<String>] The numerator units to coerce this number into.
-
# See {\#numerator\_units}
-
# @param den_units [Array<String>] The denominator units to coerce this number into.
-
# See {\#denominator\_units}
-
# @return [Number] The number with the new units
-
# @raise [Sass::UnitConversionError] if the given units are incompatible with the number's
-
# current units
-
1
def coerce(num_units, den_units)
-
Number.new(if unitless?
-
self.value
-
else
-
self.value * coercion_factor(@numerator_units, num_units) /
-
coercion_factor(@denominator_units, den_units)
-
end, num_units, den_units)
-
end
-
-
# @param other [Number] A number to decide if it can be compared with this number.
-
# @return [Boolean] Whether or not this number can be compared with the other.
-
1
def comparable_to?(other)
-
begin
-
operate(other, :+)
-
true
-
rescue Sass::UnitConversionError
-
false
-
end
-
end
-
-
# Returns a human readable representation of the units in this number.
-
# For complex units this takes the form of:
-
# numerator_unit1 * numerator_unit2 / denominator_unit1 * denominator_unit2
-
# @return [String] a string that represents the units in this number
-
1
def unit_str
-
rv = @numerator_units.sort.join("*")
-
if @denominator_units.any?
-
rv << "/"
-
rv << @denominator_units.sort.join("*")
-
end
-
rv
-
end
-
-
1
private
-
-
# @private
-
1
def self.round(num)
-
if num.is_a?(Float) && (num.infinite? || num.nan?)
-
num
-
elsif num % 1 == 0.0
-
num.to_i
-
else
-
((num * self.precision_factor).round / self.precision_factor).to_f
-
end
-
end
-
-
1
OPERATIONS = [:+, :-, :<=, :<, :>, :>=]
-
-
1
def operate(other, operation)
-
this = self
-
if OPERATIONS.include?(operation)
-
if unitless?
-
this = this.coerce(other.numerator_units, other.denominator_units)
-
else
-
other = other.coerce(@numerator_units, @denominator_units)
-
end
-
end
-
# avoid integer division
-
value = (:/ == operation) ? this.value.to_f : this.value
-
result = value.send(operation, other.value)
-
-
if result.is_a?(Numeric)
-
Number.new(result, *compute_units(this, other, operation))
-
else # Boolean op
-
Bool.new(result)
-
end
-
end
-
-
1
def coercion_factor(from_units, to_units)
-
# get a list of unmatched units
-
from_units, to_units = sans_common_units(from_units, to_units)
-
-
if from_units.size != to_units.size || !convertable?(from_units | to_units)
-
raise Sass::UnitConversionError.new("Incompatible units: '#{from_units.join('*')}' and '#{to_units.join('*')}'.")
-
end
-
-
from_units.zip(to_units).inject(1) {|m,p| m * conversion_factor(p[0], p[1]) }
-
end
-
-
1
def compute_units(this, other, operation)
-
case operation
-
when :*
-
[this.numerator_units + other.numerator_units, this.denominator_units + other.denominator_units]
-
when :/
-
[this.numerator_units + other.denominator_units, this.denominator_units + other.numerator_units]
-
else
-
[this.numerator_units, this.denominator_units]
-
end
-
end
-
-
1
def normalize!
-
return if unitless?
-
@numerator_units, @denominator_units = sans_common_units(@numerator_units, @denominator_units)
-
-
@denominator_units.each_with_index do |d, i|
-
if convertable?(d) && (u = @numerator_units.detect(&method(:convertable?)))
-
@value /= conversion_factor(d, u)
-
@denominator_units.delete_at(i)
-
@numerator_units.delete_at(@numerator_units.index(u))
-
end
-
end
-
end
-
-
# A hash of unit names to their index in the conversion table
-
1
CONVERTABLE_UNITS = {"in" => 0, "cm" => 1, "pc" => 2, "mm" => 3, "pt" => 4, "px" => 5 }
-
1
CONVERSION_TABLE = [[ 1, 2.54, 6, 25.4, 72 , 96 ], # in
-
[ nil, 1, 2.36220473, 10, 28.3464567, 37.795275591], # cm
-
[ nil, nil, 1, 4.23333333, 12 , 16 ], # pc
-
[ nil, nil, nil, 1, 2.83464567, 3.7795275591], # mm
-
[ nil, nil, nil, nil, 1 , 1.3333333333], # pt
-
[ nil, nil, nil, nil, nil , 1 ]] # px
-
-
1
def conversion_factor(from_unit, to_unit)
-
res = CONVERSION_TABLE[CONVERTABLE_UNITS[from_unit]][CONVERTABLE_UNITS[to_unit]]
-
return 1.0 / conversion_factor(to_unit, from_unit) if res.nil?
-
res
-
end
-
-
1
def convertable?(units)
-
Array(units).all? {|u| CONVERTABLE_UNITS.include?(u)}
-
end
-
-
1
def sans_common_units(units1, units2)
-
units2 = units2.dup
-
# Can't just use -, because we want px*px to coerce properly to px*mm
-
return units1.map do |u|
-
next u unless j = units2.index(u)
-
units2.delete_at(j)
-
nil
-
end.compact, units2
-
end
-
end
-
end
-
1
require 'set'
-
1
require 'sass/script/string'
-
1
require 'sass/script/number'
-
1
require 'sass/script/color'
-
1
require 'sass/script/functions'
-
1
require 'sass/script/unary_operation'
-
1
require 'sass/script/interpolation'
-
1
require 'sass/script/string_interpolation'
-
-
1
module Sass::Script
-
# A SassScript parse node representing a binary operation,
-
# such as `$a + $b` or `"foo" + 1`.
-
1
class Operation < Node
-
1
attr_reader :operand1
-
1
attr_reader :operand2
-
1
attr_reader :operator
-
-
# @param operand1 [Script::Node] The parse-tree node
-
# for the right-hand side of the operator
-
# @param operand2 [Script::Node] The parse-tree node
-
# for the left-hand side of the operator
-
# @param operator [Symbol] The operator to perform.
-
# This should be one of the binary operator names in {Lexer::OPERATORS}
-
1
def initialize(operand1, operand2, operator)
-
@operand1 = operand1
-
@operand2 = operand2
-
@operator = operator
-
super()
-
end
-
-
# @return [String] A human-readable s-expression representation of the operation
-
1
def inspect
-
"(#{@operator.inspect} #{@operand1.inspect} #{@operand2.inspect})"
-
end
-
-
# @see Node#to_sass
-
1
def to_sass(opts = {})
-
o1 = operand_to_sass @operand1, :left, opts
-
o2 = operand_to_sass @operand2, :right, opts
-
sep =
-
case @operator
-
when :comma; ", "
-
when :space; " "
-
else; " #{Lexer::OPERATORS_REVERSE[@operator]} "
-
end
-
"#{o1}#{sep}#{o2}"
-
end
-
-
# Returns the operands for this operation.
-
#
-
# @return [Array<Node>]
-
# @see Node#children
-
1
def children
-
[@operand1, @operand2]
-
end
-
-
# @see Node#deep_copy
-
1
def deep_copy
-
node = dup
-
node.instance_variable_set('@operand1', @operand1.deep_copy)
-
node.instance_variable_set('@operand2', @operand2.deep_copy)
-
node
-
end
-
-
1
protected
-
-
# Evaluates the operation.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Literal] The SassScript object that is the value of the operation
-
# @raise [Sass::SyntaxError] if the operation is undefined for the operands
-
1
def _perform(environment)
-
literal1 = @operand1.perform(environment)
-
-
# Special-case :and and :or to support short-circuiting.
-
if @operator == :and
-
return literal1.to_bool ? @operand2.perform(environment) : literal1
-
elsif @operator == :or
-
return literal1.to_bool ? literal1 : @operand2.perform(environment)
-
end
-
-
literal2 = @operand2.perform(environment)
-
-
if (literal1.is_a?(Null) || literal2.is_a?(Null)) && @operator != :eq && @operator != :neq
-
raise Sass::SyntaxError.new("Invalid null operation: \"#{literal1.inspect} #{@operator} #{literal2.inspect}\".")
-
end
-
-
begin
-
opts(literal1.send(@operator, literal2))
-
rescue NoMethodError => e
-
raise e unless e.name.to_s == @operator.to_s
-
raise Sass::SyntaxError.new("Undefined operation: \"#{literal1} #{@operator} #{literal2}\".")
-
end
-
end
-
-
1
private
-
-
1
def operand_to_sass(op, side, opts)
-
return "(#{op.to_sass(opts)})" if op.is_a?(List)
-
return op.to_sass(opts) unless op.is_a?(Operation)
-
-
pred = Sass::Script::Parser.precedence_of(@operator)
-
sub_pred = Sass::Script::Parser.precedence_of(op.operator)
-
assoc = Sass::Script::Parser.associative?(@operator)
-
return "(#{op.to_sass(opts)})" if sub_pred < pred ||
-
(side == :right && sub_pred == pred && !assoc)
-
op.to_sass(opts)
-
end
-
end
-
end
-
1
require 'sass/script/lexer'
-
-
1
module Sass
-
1
module Script
-
# The parser for SassScript.
-
# It parses a string of code into a tree of {Script::Node}s.
-
1
class Parser
-
# The line number of the parser's current position.
-
#
-
# @return [Fixnum]
-
1
def line
-
@lexer.line
-
end
-
-
# @param str [String, StringScanner] The source text to parse
-
# @param line [Fixnum] The line on which the SassScript appears.
-
# Used for error reporting
-
# @param offset [Fixnum] The number of characters in on which the SassScript appears.
-
# Used for error reporting
-
# @param options [{Symbol => Object}] An options hash;
-
# see {file:SASS_REFERENCE.md#sass_options the Sass options documentation}
-
1
def initialize(str, line, offset, options = {})
-
@options = options
-
@lexer = lexer_class.new(str, line, offset, options)
-
end
-
-
# Parses a SassScript expression within an interpolated segment (`#{}`).
-
# This means that it stops when it comes across an unmatched `}`,
-
# which signals the end of an interpolated segment,
-
# it returns rather than throwing an error.
-
#
-
# @return [Script::Node] The root node of the parse tree
-
# @raise [Sass::SyntaxError] if the expression isn't valid SassScript
-
1
def parse_interpolated
-
expr = assert_expr :expr
-
assert_tok :end_interpolation
-
expr.options = @options
-
expr
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
-
raise e
-
end
-
-
# Parses a SassScript expression.
-
#
-
# @return [Script::Node] The root node of the parse tree
-
# @raise [Sass::SyntaxError] if the expression isn't valid SassScript
-
1
def parse
-
expr = assert_expr :expr
-
assert_done
-
expr.options = @options
-
expr
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
-
raise e
-
end
-
-
# Parses a SassScript expression,
-
# ending it when it encounters one of the given identifier tokens.
-
#
-
# @param [#include?(String)] A set of strings that delimit the expression.
-
# @return [Script::Node] The root node of the parse tree
-
# @raise [Sass::SyntaxError] if the expression isn't valid SassScript
-
1
def parse_until(tokens)
-
@stop_at = tokens
-
expr = assert_expr :expr
-
assert_done
-
expr.options = @options
-
expr
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
-
raise e
-
end
-
-
# Parses the argument list for a mixin include.
-
#
-
# @return [(Array<Script::Node>, {String => Script::Node}, Script::Node)]
-
# The root nodes of the positional arguments, keyword arguments, and
-
# splat argument. Keyword arguments are in a hash from names to values.
-
# @raise [Sass::SyntaxError] if the argument list isn't valid SassScript
-
1
def parse_mixin_include_arglist
-
args, keywords = [], {}
-
if try_tok(:lparen)
-
args, keywords, splat = mixin_arglist || [[], {}]
-
assert_tok(:rparen)
-
end
-
assert_done
-
-
args.each {|a| a.options = @options}
-
keywords.each {|k, v| v.options = @options}
-
splat.options = @options if splat
-
return args, keywords, splat
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
-
raise e
-
end
-
-
# Parses the argument list for a mixin definition.
-
#
-
# @return [(Array<Script::Node>, Script::Node)]
-
# The root nodes of the arguments, and the splat argument.
-
# @raise [Sass::SyntaxError] if the argument list isn't valid SassScript
-
1
def parse_mixin_definition_arglist
-
args, splat = defn_arglist!(false)
-
assert_done
-
-
args.each do |k, v|
-
k.options = @options
-
v.options = @options if v
-
end
-
splat.options = @options if splat
-
return args, splat
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
-
raise e
-
end
-
-
# Parses the argument list for a function definition.
-
#
-
# @return [(Array<Script::Node>, Script::Node)]
-
# The root nodes of the arguments, and the splat argument.
-
# @raise [Sass::SyntaxError] if the argument list isn't valid SassScript
-
1
def parse_function_definition_arglist
-
args, splat = defn_arglist!(true)
-
assert_done
-
-
args.each do |k, v|
-
k.options = @options
-
v.options = @options if v
-
end
-
splat.options = @options if splat
-
return args, splat
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
-
raise e
-
end
-
-
# Parse a single string value, possibly containing interpolation.
-
# Doesn't assert that the scanner is finished after parsing.
-
#
-
# @return [Script::Node] The root node of the parse tree.
-
# @raise [Sass::SyntaxError] if the string isn't valid SassScript
-
1
def parse_string
-
unless (peek = @lexer.peek) &&
-
(peek.type == :string ||
-
(peek.type == :funcall && peek.value.downcase == 'url'))
-
lexer.expected!("string")
-
end
-
-
expr = assert_expr :funcall
-
expr.options = @options
-
@lexer.unpeek!
-
expr
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
-
raise e
-
end
-
-
# Parses a SassScript expression.
-
#
-
# @overload parse(str, line, offset, filename = nil)
-
# @return [Script::Node] The root node of the parse tree
-
# @see Parser#initialize
-
# @see Parser#parse
-
1
def self.parse(*args)
-
new(*args).parse
-
end
-
-
1
PRECEDENCE = [
-
:comma, :single_eq, :space, :or, :and,
-
[:eq, :neq],
-
[:gt, :gte, :lt, :lte],
-
[:plus, :minus],
-
[:times, :div, :mod],
-
]
-
-
1
ASSOCIATIVE = [:plus, :times]
-
-
1
class << self
-
# Returns an integer representing the precedence
-
# of the given operator.
-
# A lower integer indicates a looser binding.
-
#
-
# @private
-
1
def precedence_of(op)
-
PRECEDENCE.each_with_index do |e, i|
-
return i if Array(e).include?(op)
-
end
-
raise "[BUG] Unknown operator #{op}"
-
end
-
-
# Returns whether or not the given operation is associative.
-
#
-
# @private
-
1
def associative?(op)
-
ASSOCIATIVE.include?(op)
-
end
-
-
1
private
-
-
# Defines a simple left-associative production.
-
# name is the name of the production,
-
# sub is the name of the production beneath it,
-
# and ops is a list of operators for this precedence level
-
1
def production(name, sub, *ops)
-
8
class_eval <<RUBY, __FILE__, __LINE__ + 1
-
def #{name}
-
interp = try_ops_after_interp(#{ops.inspect}, #{name.inspect}) and return interp
-
return unless e = #{sub}
-
15
while tok = try_tok(#{ops.map {|o| o.inspect}.join(', ')})
-
if interp = try_op_before_interp(tok, e)
-
return interp unless other_interp = try_ops_after_interp(#{ops.inspect}, #{name.inspect}, interp)
-
return other_interp
-
end
-
-
line = @lexer.line
-
e = Operation.new(e, assert_expr(#{sub.inspect}), tok.type)
-
e.line = line
-
end
-
e
-
end
-
RUBY
-
end
-
-
1
def unary(op, sub)
-
4
class_eval <<RUBY, __FILE__, __LINE__ + 1
-
def unary_#{op}
-
return #{sub} unless tok = try_tok(:#{op})
-
interp = try_op_before_interp(tok) and return interp
-
line = @lexer.line
-
op = UnaryOperation.new(assert_expr(:unary_#{op}), :#{op})
-
op.line = line
-
op
-
end
-
RUBY
-
end
-
end
-
-
1
private
-
-
# @private
-
1
def lexer_class; Lexer; end
-
-
1
def expr
-
line = @lexer.line
-
return unless e = interpolation
-
list = node(List.new([e], :comma), line)
-
while tok = try_tok(:comma)
-
if interp = try_op_before_interp(tok, list)
-
return interp unless other_interp = try_ops_after_interp([:comma], :expr, interp)
-
return other_interp
-
end
-
list.value << assert_expr(:interpolation)
-
end
-
list.value.size == 1 ? list.value.first : list
-
end
-
-
1
production :equals, :interpolation, :single_eq
-
-
1
def try_op_before_interp(op, prev = nil)
-
return unless @lexer.peek && @lexer.peek.type == :begin_interpolation
-
wb = @lexer.whitespace?(op)
-
str = Script::String.new(Lexer::OPERATORS_REVERSE[op.type])
-
str.line = @lexer.line
-
interp = Script::Interpolation.new(prev, str, nil, wb, !:wa, :originally_text)
-
interp.line = @lexer.line
-
interpolation(interp)
-
end
-
-
1
def try_ops_after_interp(ops, name, prev = nil)
-
return unless @lexer.after_interpolation?
-
return unless op = try_tok(*ops)
-
interp = try_op_before_interp(op, prev) and return interp
-
-
wa = @lexer.whitespace?
-
str = Script::String.new(Lexer::OPERATORS_REVERSE[op.type])
-
str.line = @lexer.line
-
interp = Script::Interpolation.new(prev, str, assert_expr(name), !:wb, wa, :originally_text)
-
interp.line = @lexer.line
-
return interp
-
end
-
-
1
def interpolation(first = space)
-
e = first
-
while interp = try_tok(:begin_interpolation)
-
wb = @lexer.whitespace?(interp)
-
line = @lexer.line
-
mid = parse_interpolated
-
wa = @lexer.whitespace?
-
e = Script::Interpolation.new(e, mid, space, wb, wa)
-
e.line = line
-
end
-
e
-
end
-
-
1
def space
-
line = @lexer.line
-
return unless e = or_expr
-
arr = [e]
-
while e = or_expr
-
arr << e
-
end
-
arr.size == 1 ? arr.first : node(List.new(arr, :space), line)
-
end
-
-
1
production :or_expr, :and_expr, :or
-
1
production :and_expr, :eq_or_neq, :and
-
1
production :eq_or_neq, :relational, :eq, :neq
-
1
production :relational, :plus_or_minus, :gt, :gte, :lt, :lte
-
1
production :plus_or_minus, :times_div_or_mod, :plus, :minus
-
1
production :times_div_or_mod, :unary_plus, :times, :div, :mod
-
-
1
unary :plus, :unary_minus
-
1
unary :minus, :unary_div
-
1
unary :div, :unary_not # For strings, so /foo/bar works
-
1
unary :not, :ident
-
-
1
def ident
-
return funcall unless @lexer.peek && @lexer.peek.type == :ident
-
return if @stop_at && @stop_at.include?(@lexer.peek.value)
-
-
name = @lexer.next
-
if color = Color::COLOR_NAMES[name.value.downcase]
-
node(Color.new(color))
-
elsif name.value == "true"
-
node(Script::Bool.new(true))
-
elsif name.value == "false"
-
node(Script::Bool.new(false))
-
elsif name.value == "null"
-
node(Script::Null.new)
-
else
-
node(Script::String.new(name.value, :identifier))
-
end
-
end
-
-
1
def funcall
-
return raw unless tok = try_tok(:funcall)
-
args, keywords, splat = fn_arglist || [[], {}]
-
assert_tok(:rparen)
-
node(Script::Funcall.new(tok.value, args, keywords, splat))
-
end
-
-
1
def defn_arglist!(must_have_parens)
-
if must_have_parens
-
assert_tok(:lparen)
-
else
-
return [], nil unless try_tok(:lparen)
-
end
-
return [], nil if try_tok(:rparen)
-
-
res = []
-
splat = nil
-
must_have_default = false
-
loop do
-
c = assert_tok(:const)
-
var = Script::Variable.new(c.value)
-
if try_tok(:colon)
-
val = assert_expr(:space)
-
must_have_default = true
-
elsif must_have_default
-
raise SyntaxError.new("Required argument #{var.inspect} must come before any optional arguments.")
-
elsif try_tok(:splat)
-
splat = var
-
break
-
end
-
res << [var, val]
-
break unless try_tok(:comma)
-
end
-
assert_tok(:rparen)
-
return res, splat
-
end
-
-
1
def fn_arglist
-
arglist(:equals, "function argument")
-
end
-
-
1
def mixin_arglist
-
arglist(:interpolation, "mixin argument")
-
end
-
-
1
def arglist(subexpr, description)
-
return unless e = send(subexpr)
-
-
args = []
-
keywords = {}
-
loop do
-
if @lexer.peek && @lexer.peek.type == :colon
-
name = e
-
@lexer.expected!("comma") unless name.is_a?(Variable)
-
assert_tok(:colon)
-
value = assert_expr(subexpr, description)
-
-
if keywords[name.underscored_name]
-
raise SyntaxError.new("Keyword argument \"#{name.to_sass}\" passed more than once")
-
end
-
-
keywords[name.underscored_name] = value
-
else
-
if !keywords.empty?
-
raise SyntaxError.new("Positional arguments must come before keyword arguments.")
-
end
-
-
return args, keywords, e if try_tok(:splat)
-
args << e
-
end
-
-
return args, keywords unless try_tok(:comma)
-
e = assert_expr(subexpr, description)
-
end
-
end
-
-
1
def raw
-
return special_fun unless tok = try_tok(:raw)
-
node(Script::String.new(tok.value))
-
end
-
-
1
def special_fun
-
return paren unless tok = try_tok(:special_fun)
-
first = node(Script::String.new(tok.value.first))
-
Sass::Util.enum_slice(tok.value[1..-1], 2).inject(first) do |l, (i, r)|
-
Script::Interpolation.new(
-
l, i, r && node(Script::String.new(r)),
-
false, false)
-
end
-
end
-
-
1
def paren
-
return variable unless try_tok(:lparen)
-
was_in_parens = @in_parens
-
@in_parens = true
-
line = @lexer.line
-
e = expr
-
assert_tok(:rparen)
-
return e || node(List.new([], :space), line)
-
ensure
-
@in_parens = was_in_parens
-
end
-
-
1
def variable
-
return string unless c = try_tok(:const)
-
node(Variable.new(*c.value))
-
end
-
-
1
def string
-
return number unless first = try_tok(:string)
-
return first.value unless try_tok(:begin_interpolation)
-
line = @lexer.line
-
mid = parse_interpolated
-
last = assert_expr(:string)
-
interp = StringInterpolation.new(first.value, mid, last)
-
interp.line = line
-
interp
-
end
-
-
1
def number
-
return literal unless tok = try_tok(:number)
-
num = tok.value
-
num.original = num.to_s unless @in_parens
-
num
-
end
-
-
1
def literal
-
(t = try_tok(:color)) && (return t.value)
-
end
-
-
# It would be possible to have unified #assert and #try methods,
-
# but detecting the method/token difference turns out to be quite expensive.
-
-
1
EXPR_NAMES = {
-
:string => "string",
-
:default => "expression (e.g. 1px, bold)",
-
:mixin_arglist => "mixin argument",
-
:fn_arglist => "function argument",
-
}
-
-
1
def assert_expr(name, expected = nil)
-
(e = send(name)) && (return e)
-
@lexer.expected!(expected || EXPR_NAMES[name] || EXPR_NAMES[:default])
-
end
-
-
1
def assert_tok(*names)
-
(t = try_tok(*names)) && (return t)
-
@lexer.expected!(names.map {|tok| Lexer::TOKEN_NAMES[tok] || tok}.join(" or "))
-
end
-
-
1
def try_tok(*names)
-
peeked = @lexer.peek
-
peeked && names.include?(peeked.type) && @lexer.next
-
end
-
-
1
def assert_done
-
return if @lexer.done?
-
@lexer.expected!(EXPR_NAMES[:default])
-
end
-
-
1
def node(node, line = @lexer.line)
-
node.line = line
-
node
-
end
-
end
-
end
-
end
-
1
require 'sass/script/literal'
-
-
1
module Sass::Script
-
# A SassScript object representing a CSS string *or* a CSS identifier.
-
1
class String < Literal
-
# The Ruby value of the string.
-
#
-
# @return [String]
-
1
attr_reader :value
-
-
# Whether this is a CSS string or a CSS identifier.
-
# The difference is that strings are written with double-quotes,
-
# while identifiers aren't.
-
#
-
# @return [Symbol] `:string` or `:identifier`
-
1
attr_reader :type
-
-
# Creates a new string.
-
#
-
# @param value [String] See \{#value}
-
# @param type [Symbol] See \{#type}
-
1
def initialize(value, type = :identifier)
-
super(value)
-
@type = type
-
end
-
-
# @see Literal#plus
-
1
def plus(other)
-
other_str = other.is_a?(Sass::Script::String) ? other.value : other.to_s
-
Sass::Script::String.new(self.value + other_str, self.type)
-
end
-
-
# @see Node#to_s
-
1
def to_s(opts = {})
-
if @type == :identifier
-
return @value.gsub(/\n\s*/, " ")
-
end
-
-
return "\"#{value.gsub('"', "\\\"")}\"" if opts[:quote] == %q{"}
-
return "'#{value.gsub("'", "\\'")}'" if opts[:quote] == %q{'}
-
return "\"#{value}\"" unless value.include?('"')
-
return "'#{value}'" unless value.include?("'")
-
"\"#{value.gsub('"', "\\\"")}\"" #'
-
end
-
-
# @see Node#to_sass
-
1
def to_sass(opts = {})
-
to_s
-
end
-
end
-
end
-
1
module Sass::Script
-
# A SassScript object representing `#{}` interpolation within a string.
-
#
-
# @see Interpolation
-
1
class StringInterpolation < Node
-
# Interpolation in a string is of the form `"before #{mid} after"`,
-
# where `before` and `after` may include more interpolation.
-
#
-
# @param before [Node] The string before the interpolation
-
# @param mid [Node] The SassScript within the interpolation
-
# @param after [Node] The string after the interpolation
-
1
def initialize(before, mid, after)
-
@before = before
-
@mid = mid
-
@after = after
-
end
-
-
# @return [String] A human-readable s-expression representation of the interpolation
-
1
def inspect
-
"(string_interpolation #{@before.inspect} #{@mid.inspect} #{@after.inspect})"
-
end
-
-
# @see Node#to_sass
-
1
def to_sass(opts = {})
-
# We can get rid of all of this when we remove the deprecated :equals context
-
# XXX CE: It's gone now but I'm not sure what can be removed now.
-
before_unquote, before_quote_char, before_str = parse_str(@before.to_sass(opts))
-
after_unquote, after_quote_char, after_str = parse_str(@after.to_sass(opts))
-
unquote = before_unquote || after_unquote ||
-
(before_quote_char && !after_quote_char && !after_str.empty?) ||
-
(!before_quote_char && after_quote_char && !before_str.empty?)
-
quote_char =
-
if before_quote_char && after_quote_char && before_quote_char != after_quote_char
-
before_str.gsub!("\\'", "'")
-
before_str.gsub!('"', "\\\"")
-
after_str.gsub!("\\'", "'")
-
after_str.gsub!('"', "\\\"")
-
'"'
-
else
-
before_quote_char || after_quote_char
-
end
-
-
res = ""
-
res << 'unquote(' if unquote
-
res << quote_char if quote_char
-
res << before_str
-
res << '#{' << @mid.to_sass(opts) << '}'
-
res << after_str
-
res << quote_char if quote_char
-
res << ')' if unquote
-
res
-
end
-
-
# Returns the three components of the interpolation, `before`, `mid`, and `after`.
-
#
-
# @return [Array<Node>]
-
# @see #initialize
-
# @see Node#children
-
1
def children
-
[@before, @mid, @after].compact
-
end
-
-
# @see Node#deep_copy
-
1
def deep_copy
-
node = dup
-
node.instance_variable_set('@before', @before.deep_copy) if @before
-
node.instance_variable_set('@mid', @mid.deep_copy)
-
node.instance_variable_set('@after', @after.deep_copy) if @after
-
node
-
end
-
-
1
protected
-
-
# Evaluates the interpolation.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Sass::Script::String] The SassScript string that is the value of the interpolation
-
1
def _perform(environment)
-
res = ""
-
before = @before.perform(environment)
-
res << before.value
-
mid = @mid.perform(environment)
-
res << (mid.is_a?(Sass::Script::String) ? mid.value : mid.to_s)
-
res << @after.perform(environment).value
-
opts(Sass::Script::String.new(res, before.type))
-
end
-
-
1
private
-
-
1
def parse_str(str)
-
case str
-
when /^unquote\((["'])(.*)\1\)$/
-
return true, $1, $2
-
when '""'
-
return false, nil, ""
-
when /^(["'])(.*)\1$/
-
return false, $1, $2
-
else
-
return false, nil, str
-
end
-
end
-
end
-
end
-
1
module Sass::Script
-
# A SassScript parse node representing a unary operation,
-
# such as `-$b` or `not true`.
-
#
-
# Currently only `-`, `/`, and `not` are unary operators.
-
1
class UnaryOperation < Node
-
# @return [Symbol] The operation to perform
-
1
attr_reader :operator
-
-
# @return [Script::Node] The parse-tree node for the object of the operator
-
1
attr_reader :operand
-
-
# @param operand [Script::Node] See \{#operand}
-
# @param operator [Symbol] See \{#operator}
-
1
def initialize(operand, operator)
-
@operand = operand
-
@operator = operator
-
super()
-
end
-
-
# @return [String] A human-readable s-expression representation of the operation
-
1
def inspect
-
"(#{@operator.inspect} #{@operand.inspect})"
-
end
-
-
# @see Node#to_sass
-
1
def to_sass(opts = {})
-
operand = @operand.to_sass(opts)
-
if @operand.is_a?(Operation) ||
-
(@operator == :minus &&
-
(operand =~ Sass::SCSS::RX::IDENT) == 0)
-
operand = "(#{@operand.to_sass(opts)})"
-
end
-
op = Lexer::OPERATORS_REVERSE[@operator]
-
op + (op =~ /[a-z]/ ? " " : "") + operand
-
end
-
-
# Returns the operand of the operation.
-
#
-
# @return [Array<Node>]
-
# @see Node#children
-
1
def children
-
[@operand]
-
end
-
-
# @see Node#deep_copy
-
1
def deep_copy
-
node = dup
-
node.instance_variable_set('@operand', @operand.deep_copy)
-
node
-
end
-
-
1
protected
-
-
# Evaluates the operation.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Literal] The SassScript object that is the value of the operation
-
# @raise [Sass::SyntaxError] if the operation is undefined for the operand
-
1
def _perform(environment)
-
operator = "unary_#{@operator}"
-
literal = @operand.perform(environment)
-
literal.send(operator)
-
rescue NoMethodError => e
-
raise e unless e.name.to_s == operator.to_s
-
raise Sass::SyntaxError.new("Undefined unary operation: \"#{@operator} #{literal}\".")
-
end
-
end
-
end
-
1
module Sass
-
1
module Script
-
# A SassScript parse node representing a variable.
-
1
class Variable < Node
-
# The name of the variable.
-
#
-
# @return [String]
-
1
attr_reader :name
-
-
# The underscored name of the variable.
-
#
-
# @return [String]
-
1
attr_reader :underscored_name
-
-
# @param name [String] See \{#name}
-
1
def initialize(name)
-
@name = name
-
@underscored_name = name.gsub(/-/,"_")
-
super()
-
end
-
-
# @return [String] A string representation of the variable
-
1
def inspect(opts = {})
-
"$#{dasherize(name, opts)}"
-
end
-
1
alias_method :to_sass, :inspect
-
-
# Returns an empty array.
-
#
-
# @return [Array<Node>] empty
-
# @see Node#children
-
1
def children
-
[]
-
end
-
-
# @see Node#deep_copy
-
1
def deep_copy
-
dup
-
end
-
-
1
protected
-
-
# Evaluates the variable.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Literal] The SassScript object that is the value of the variable
-
# @raise [Sass::SyntaxError] if the variable is undefined
-
1
def _perform(environment)
-
raise SyntaxError.new("Undefined variable: \"$#{name}\".") unless val = environment.var(name)
-
if val.is_a?(Number)
-
val = val.dup
-
val.original = nil
-
end
-
return val
-
end
-
end
-
end
-
end
-
1
require 'sass/scss/rx'
-
1
require 'sass/scss/script_lexer'
-
1
require 'sass/scss/script_parser'
-
1
require 'sass/scss/parser'
-
1
require 'sass/scss/static_parser'
-
1
require 'sass/scss/css_parser'
-
-
1
module Sass
-
# SCSS is the CSS syntax for Sass.
-
# It parses into the same syntax tree as Sass,
-
# and generates the same sort of output CSS.
-
#
-
# This module contains code for the parsing of SCSS.
-
# The evaluation is handled by the broader {Sass} module.
-
1
module SCSS; end
-
end
-
1
require 'sass/script/css_parser'
-
-
1
module Sass
-
1
module SCSS
-
# This is a subclass of {Parser} which only parses plain CSS.
-
# It doesn't support any Sass extensions, such as interpolation,
-
# parent references, nested selectors, and so forth.
-
# It does support all the same CSS hacks as the SCSS parser, though.
-
1
class CssParser < StaticParser
-
1
private
-
-
1
def placeholder_selector; nil; end
-
1
def parent_selector; nil; end
-
1
def interpolation; nil; end
-
1
def use_css_import?; true; end
-
-
1
def block_child(context)
-
case context
-
when :ruleset
-
declaration
-
when :stylesheet
-
directive || ruleset
-
when :directive
-
directive || declaration_or_ruleset
-
end
-
end
-
-
1
def nested_properties!(node, space)
-
expected('expression (e.g. 1px, bold)');
-
end
-
-
1
@sass_script_parser = Class.new(Sass::Script::CssParser)
-
1
@sass_script_parser.send(:include, ScriptParser)
-
end
-
end
-
end
-
1
require 'set'
-
-
1
module Sass
-
1
module SCSS
-
# The parser for SCSS.
-
# It parses a string of code into a tree of {Sass::Tree::Node}s.
-
1
class Parser
-
# @param str [String, StringScanner] The source document to parse.
-
# Note that `Parser` *won't* raise a nice error message if this isn't properly parsed;
-
# for that, you should use the higher-level {Sass::Engine} or {Sass::CSS}.
-
# @param filename [String] The name of the file being parsed. Used for warnings.
-
# @param line [Fixnum] The line on which the source string appeared,
-
# if it's part of another document.
-
1
def initialize(str, filename, line = 1)
-
@template = str
-
@filename = filename
-
@line = line
-
@strs = []
-
end
-
-
# Parses an SCSS document.
-
#
-
# @return [Sass::Tree::RootNode] The root node of the document tree
-
# @raise [Sass::SyntaxError] if there's a syntax error in the document
-
1
def parse
-
init_scanner!
-
root = stylesheet
-
expected("selector or at-rule") unless @scanner.eos?
-
root
-
end
-
-
# Parses an identifier with interpolation.
-
# Note that this won't assert that the identifier takes up the entire input string;
-
# it's meant to be used with `StringScanner`s as part of other parsers.
-
#
-
# @return [Array<String, Sass::Script::Node>, nil]
-
# The interpolated identifier, or nil if none could be parsed
-
1
def parse_interp_ident
-
init_scanner!
-
interp_ident
-
end
-
-
# Parses a media query list.
-
#
-
# @return [Sass::Media::QueryList] The parsed query list
-
# @raise [Sass::SyntaxError] if there's a syntax error in the query list,
-
# or if it doesn't take up the entire input string.
-
1
def parse_media_query_list
-
init_scanner!
-
ql = media_query_list
-
expected("media query list") unless @scanner.eos?
-
ql
-
end
-
-
# Parses a supports query condition.
-
#
-
# @return [Sass::Supports::Condition] The parsed condition
-
# @raise [Sass::SyntaxError] if there's a syntax error in the condition,
-
# or if it doesn't take up the entire input string.
-
1
def parse_supports_condition
-
init_scanner!
-
condition = supports_condition
-
expected("supports condition") unless @scanner.eos?
-
condition
-
end
-
-
1
private
-
-
1
include Sass::SCSS::RX
-
-
1
def init_scanner!
-
@scanner =
-
if @template.is_a?(StringScanner)
-
@template
-
else
-
Sass::Util::MultibyteStringScanner.new(@template.gsub("\r", ""))
-
end
-
end
-
-
1
def stylesheet
-
node = node(Sass::Tree::RootNode.new(@scanner.string))
-
block_contents(node, :stylesheet) {s(node)}
-
end
-
-
1
def s(node)
-
while tok(S) || tok(CDC) || tok(CDO) || (c = tok(SINGLE_LINE_COMMENT)) || (c = tok(COMMENT))
-
next unless c
-
process_comment c, node
-
c = nil
-
end
-
true
-
end
-
-
1
def ss
-
nil while tok(S) || tok(SINGLE_LINE_COMMENT) || tok(COMMENT)
-
true
-
end
-
-
1
def ss_comments(node)
-
while tok(S) || (c = tok(SINGLE_LINE_COMMENT)) || (c = tok(COMMENT))
-
next unless c
-
process_comment c, node
-
c = nil
-
end
-
-
true
-
end
-
-
1
def whitespace
-
return unless tok(S) || tok(SINGLE_LINE_COMMENT) || tok(COMMENT)
-
ss
-
end
-
-
1
def process_comment(text, node)
-
silent = text =~ /^\/\//
-
loud = !silent && text =~ %r{^/[/*]!}
-
line = @line - text.count("\n")
-
-
if silent
-
value = [text.sub(/^\s*\/\//, '/*').gsub(/^\s*\/\//, ' *') + ' */']
-
else
-
value = Sass::Engine.parse_interp(text, line, @scanner.pos - text.size, :filename => @filename)
-
value.unshift(@scanner.
-
string[0...@scanner.pos].
-
reverse[/.*?\*\/(.*?)($|\Z)/, 1].
-
reverse.gsub(/[^\s]/, ' '))
-
end
-
-
type = if silent then :silent elsif loud then :loud else :normal end
-
comment = Sass::Tree::CommentNode.new(value, type)
-
comment.line = line
-
node << comment
-
end
-
-
1
DIRECTIVES = Set[:mixin, :include, :function, :return, :debug, :warn, :for,
-
:each, :while, :if, :else, :extend, :import, :media, :charset, :content,
-
:_moz_document]
-
-
1
PREFIXED_DIRECTIVES = Set[:supports]
-
-
1
def directive
-
return unless tok(/@/)
-
name = tok!(IDENT)
-
ss
-
-
if dir = special_directive(name)
-
return dir
-
elsif dir = prefixed_directive(name)
-
return dir
-
end
-
-
# Most at-rules take expressions (e.g. @import),
-
# but some (e.g. @page) take selector-like arguments.
-
# Some take no arguments at all.
-
val = expr || selector
-
val = val ? ["@#{name} "] + Sass::Util.strip_string_array(val) : ["@#{name}"]
-
directive_body(val)
-
end
-
-
1
def directive_body(value)
-
node = node(Sass::Tree::DirectiveNode.new(value))
-
-
if tok(/\{/)
-
node.has_children = true
-
block_contents(node, :directive)
-
tok!(/\}/)
-
end
-
-
node
-
end
-
-
1
def special_directive(name)
-
sym = name.gsub('-', '_').to_sym
-
DIRECTIVES.include?(sym) && send("#{sym}_directive")
-
end
-
-
1
def prefixed_directive(name)
-
sym = name.gsub(/^-[a-z0-9]+-/i, '').gsub('-', '_').to_sym
-
PREFIXED_DIRECTIVES.include?(sym) && send("#{sym}_directive", name)
-
end
-
-
1
def mixin_directive
-
name = tok! IDENT
-
args, splat = sass_script(:parse_mixin_definition_arglist)
-
ss
-
block(node(Sass::Tree::MixinDefNode.new(name, args, splat)), :directive)
-
end
-
-
1
def include_directive
-
name = tok! IDENT
-
args, keywords, splat = sass_script(:parse_mixin_include_arglist)
-
ss
-
include_node = node(Sass::Tree::MixinNode.new(name, args, keywords, splat))
-
if tok?(/\{/)
-
include_node.has_children = true
-
block(include_node, :directive)
-
else
-
include_node
-
end
-
end
-
-
1
def content_directive
-
ss
-
node(Sass::Tree::ContentNode.new)
-
end
-
-
1
def function_directive
-
name = tok! IDENT
-
args, splat = sass_script(:parse_function_definition_arglist)
-
ss
-
block(node(Sass::Tree::FunctionNode.new(name, args, splat)), :function)
-
end
-
-
1
def return_directive
-
node(Sass::Tree::ReturnNode.new(sass_script(:parse)))
-
end
-
-
1
def debug_directive
-
node(Sass::Tree::DebugNode.new(sass_script(:parse)))
-
end
-
-
1
def warn_directive
-
node(Sass::Tree::WarnNode.new(sass_script(:parse)))
-
end
-
-
1
def for_directive
-
tok!(/\$/)
-
var = tok! IDENT
-
ss
-
-
tok!(/from/)
-
from = sass_script(:parse_until, Set["to", "through"])
-
ss
-
-
@expected = '"to" or "through"'
-
exclusive = (tok(/to/) || tok!(/through/)) == 'to'
-
to = sass_script(:parse)
-
ss
-
-
block(node(Sass::Tree::ForNode.new(var, from, to, exclusive)), :directive)
-
end
-
-
1
def each_directive
-
tok!(/\$/)
-
var = tok! IDENT
-
ss
-
-
tok!(/in/)
-
list = sass_script(:parse)
-
ss
-
-
block(node(Sass::Tree::EachNode.new(var, list)), :directive)
-
end
-
-
1
def while_directive
-
expr = sass_script(:parse)
-
ss
-
block(node(Sass::Tree::WhileNode.new(expr)), :directive)
-
end
-
-
1
def if_directive
-
expr = sass_script(:parse)
-
ss
-
node = block(node(Sass::Tree::IfNode.new(expr)), :directive)
-
pos = @scanner.pos
-
line = @line
-
ss
-
-
else_block(node) ||
-
begin
-
# Backtrack in case there are any comments we want to parse
-
@scanner.pos = pos
-
@line = line
-
node
-
end
-
end
-
-
1
def else_block(node)
-
return unless tok(/@else/)
-
ss
-
else_node = block(
-
Sass::Tree::IfNode.new((sass_script(:parse) if tok(/if/))),
-
:directive)
-
node.add_else(else_node)
-
pos = @scanner.pos
-
line = @line
-
ss
-
-
else_block(node) ||
-
begin
-
# Backtrack in case there are any comments we want to parse
-
@scanner.pos = pos
-
@line = line
-
node
-
end
-
end
-
-
1
def else_directive
-
err("Invalid CSS: @else must come after @if")
-
end
-
-
1
def extend_directive
-
selector = expr!(:selector_sequence)
-
optional = tok(OPTIONAL)
-
ss
-
node(Sass::Tree::ExtendNode.new(selector, !!optional))
-
end
-
-
1
def import_directive
-
values = []
-
-
loop do
-
values << expr!(:import_arg)
-
break if use_css_import?
-
break unless tok(/,/)
-
ss
-
end
-
-
return values
-
end
-
-
1
def import_arg
-
line = @line
-
return unless (str = tok(STRING)) || (uri = tok?(/url\(/i))
-
if uri
-
str = sass_script(:parse_string)
-
ss
-
media = media_query_list
-
ss
-
return node(Tree::CssImportNode.new(str, media.to_a))
-
end
-
-
path = @scanner[1] || @scanner[2]
-
ss
-
-
media = media_query_list
-
if path =~ /^(https?:)?\/\// || media || use_css_import?
-
node = Sass::Tree::CssImportNode.new(str, media.to_a)
-
else
-
node = Sass::Tree::ImportNode.new(path.strip)
-
end
-
node.line = line
-
node
-
end
-
-
1
def use_css_import?; false; end
-
-
1
def media_directive
-
block(node(Sass::Tree::MediaNode.new(expr!(:media_query_list).to_a)), :directive)
-
end
-
-
# http://www.w3.org/TR/css3-mediaqueries/#syntax
-
1
def media_query_list
-
return unless query = media_query
-
queries = [query]
-
-
ss
-
while tok(/,/)
-
ss; queries << expr!(:media_query)
-
end
-
ss
-
-
Sass::Media::QueryList.new(queries)
-
end
-
-
1
def media_query
-
if ident1 = interp_ident
-
ss
-
ident2 = interp_ident
-
ss
-
if ident2 && ident2.length == 1 && ident2[0].is_a?(String) && ident2[0].downcase == 'and'
-
query = Sass::Media::Query.new([], ident1, [])
-
else
-
if ident2
-
query = Sass::Media::Query.new(ident1, ident2, [])
-
else
-
query = Sass::Media::Query.new([], ident1, [])
-
end
-
return query unless tok(/and/i)
-
ss
-
end
-
end
-
-
if query
-
expr = expr!(:media_expr)
-
else
-
return unless expr = media_expr
-
end
-
query ||= Sass::Media::Query.new([], [], [])
-
query.expressions << expr
-
-
ss
-
while tok(/and/i)
-
ss; query.expressions << expr!(:media_expr)
-
end
-
-
query
-
end
-
-
1
def media_expr
-
interp = interpolation and return interp
-
return unless tok(/\(/)
-
res = ['(']
-
ss
-
res << sass_script(:parse)
-
-
if tok(/:/)
-
res << ': '
-
ss
-
res << sass_script(:parse)
-
end
-
res << tok!(/\)/)
-
ss
-
res
-
end
-
-
1
def charset_directive
-
tok! STRING
-
name = @scanner[1] || @scanner[2]
-
ss
-
node(Sass::Tree::CharsetNode.new(name))
-
end
-
-
# The document directive is specified in
-
# http://www.w3.org/TR/css3-conditional/, but Gecko allows the
-
# `url-prefix` and `domain` functions to omit quotation marks, contrary to
-
# the standard.
-
#
-
# We could parse all document directives according to Mozilla's syntax,
-
# but if someone's using e.g. @-webkit-document we don't want them to
-
# think WebKit works sans quotes.
-
1
def _moz_document_directive
-
res = ["@-moz-document "]
-
loop do
-
res << str{ss} << expr!(:moz_document_function)
-
break unless c = tok(/,/)
-
res << c
-
end
-
directive_body(res.flatten)
-
end
-
-
1
def moz_document_function
-
return unless val = interp_uri || _interp_string(:url_prefix) ||
-
_interp_string(:domain) || function(!:allow_var) || interpolation
-
ss
-
val
-
end
-
-
# http://www.w3.org/TR/css3-conditional/
-
1
def supports_directive(name)
-
condition = expr!(:supports_condition)
-
node = node(Sass::Tree::SupportsNode.new(name, condition))
-
-
tok!(/\{/)
-
node.has_children = true
-
block_contents(node, :directive)
-
tok!(/\}/)
-
-
node
-
end
-
-
1
def supports_condition
-
supports_negation || supports_operator || supports_interpolation
-
end
-
-
1
def supports_negation
-
return unless tok(/not/i)
-
ss
-
Sass::Supports::Negation.new(expr!(:supports_condition_in_parens))
-
end
-
-
1
def supports_operator
-
return unless cond = supports_condition_in_parens
-
return cond unless op = tok(/and|or/i)
-
begin
-
ss
-
cond = Sass::Supports::Operator.new(
-
cond, expr!(:supports_condition_in_parens), op)
-
end while op = tok(/and|or/i)
-
cond
-
end
-
-
1
def supports_condition_in_parens
-
interp = supports_interpolation and return interp
-
return unless tok(/\(/); ss
-
if cond = supports_condition
-
tok!(/\)/); ss
-
cond
-
else
-
name = sass_script(:parse)
-
tok!(/:/); ss
-
value = sass_script(:parse)
-
tok!(/\)/); ss
-
Sass::Supports::Declaration.new(name, value)
-
end
-
end
-
-
1
def supports_declaration_condition
-
return unless tok(/\(/); ss
-
supports_declaration_body
-
end
-
-
1
def supports_interpolation
-
return unless interp = interpolation
-
ss
-
Sass::Supports::Interpolation.new(interp)
-
end
-
-
1
def variable
-
return unless tok(/\$/)
-
name = tok!(IDENT)
-
ss; tok!(/:/); ss
-
-
expr = sass_script(:parse)
-
guarded = tok(DEFAULT)
-
node(Sass::Tree::VariableNode.new(name, expr, guarded))
-
end
-
-
1
def operator
-
# Many of these operators (all except / and ,)
-
# are disallowed by the CSS spec,
-
# but they're included here for compatibility
-
# with some proprietary MS properties
-
str {ss if tok(/[\/,:.=]/)}
-
end
-
-
1
def ruleset
-
return unless rules = selector_sequence
-
block(node(Sass::Tree::RuleNode.new(rules.flatten.compact)), :ruleset)
-
end
-
-
1
def block(node, context)
-
node.has_children = true
-
tok!(/\{/)
-
block_contents(node, context)
-
tok!(/\}/)
-
node
-
end
-
-
# A block may contain declarations and/or rulesets
-
1
def block_contents(node, context)
-
block_given? ? yield : ss_comments(node)
-
node << (child = block_child(context))
-
while tok(/;/) || has_children?(child)
-
block_given? ? yield : ss_comments(node)
-
node << (child = block_child(context))
-
end
-
node
-
end
-
-
1
def block_child(context)
-
return variable || directive if context == :function
-
return variable || directive || ruleset if context == :stylesheet
-
variable || directive || declaration_or_ruleset
-
end
-
-
1
def has_children?(child_or_array)
-
return false unless child_or_array
-
return child_or_array.last.has_children if child_or_array.is_a?(Array)
-
return child_or_array.has_children
-
end
-
-
# This is a nasty hack, and the only place in the parser
-
# that requires a large amount of backtracking.
-
# The reason is that we can't figure out if certain strings
-
# are declarations or rulesets with fixed finite lookahead.
-
# For example, "foo:bar baz baz baz..." could be either a property
-
# or a selector.
-
#
-
# To handle this, we simply check if it works as a property
-
# (which is the most common case)
-
# and, if it doesn't, try it as a ruleset.
-
#
-
# We could eke some more efficiency out of this
-
# by handling some easy cases (first token isn't an identifier,
-
# no colon after the identifier, whitespace after the colon),
-
# but I'm not sure the gains would be worth the added complexity.
-
1
def declaration_or_ruleset
-
old_use_property_exception, @use_property_exception =
-
@use_property_exception, false
-
decl_err = catch_error do
-
decl = declaration
-
unless decl && decl.has_children
-
# We want an exception if it's not there,
-
# but we don't want to consume if it is
-
tok!(/[;}]/) unless tok?(/[;}]/)
-
end
-
return decl
-
end
-
-
ruleset_err = catch_error {return ruleset}
-
rethrow(@use_property_exception ? decl_err : ruleset_err)
-
ensure
-
@use_property_exception = old_use_property_exception
-
end
-
-
1
def selector_sequence
-
if sel = tok(STATIC_SELECTOR, true)
-
return [sel]
-
end
-
-
rules = []
-
return unless v = selector
-
rules.concat v
-
-
ws = ''
-
while tok(/,/)
-
ws << str {ss}
-
if v = selector
-
rules << ',' << ws
-
rules.concat v
-
ws = ''
-
end
-
end
-
rules
-
end
-
-
1
def selector
-
return unless sel = _selector
-
sel.to_a
-
end
-
-
1
def selector_comma_sequence
-
return unless sel = _selector
-
selectors = [sel]
-
ws = ''
-
while tok(/,/)
-
ws << str{ss}
-
if sel = _selector
-
selectors << sel
-
selectors[-1] = Selector::Sequence.new(["\n"] + selectors.last.members) if ws.include?("\n")
-
ws = ''
-
end
-
end
-
Selector::CommaSequence.new(selectors)
-
end
-
-
1
def _selector
-
# The combinator here allows the "> E" hack
-
return unless val = combinator || simple_selector_sequence
-
nl = str{ss}.include?("\n")
-
res = []
-
res << val
-
res << "\n" if nl
-
-
while val = combinator || simple_selector_sequence
-
res << val
-
res << "\n" if str{ss}.include?("\n")
-
end
-
Selector::Sequence.new(res.compact)
-
end
-
-
1
def combinator
-
tok(PLUS) || tok(GREATER) || tok(TILDE) || reference_combinator
-
end
-
-
1
def reference_combinator
-
return unless tok(/\//)
-
res = ['/']
-
ns, name = expr!(:qualified_name)
-
res << ns << '|' if ns
-
res << name << tok!(/\//)
-
res = res.flatten
-
res = res.join '' if res.all? {|e| e.is_a?(String)}
-
res
-
end
-
-
1
def simple_selector_sequence
-
# Returning expr by default allows for stuff like
-
# http://www.w3.org/TR/css3-animations/#keyframes-
-
return expr(!:allow_var) unless e = element_name || id_selector ||
-
class_selector || placeholder_selector || attrib || pseudo ||
-
parent_selector || interpolation_selector
-
res = [e]
-
-
# The tok(/\*/) allows the "E*" hack
-
while v = id_selector || class_selector || placeholder_selector || attrib ||
-
pseudo || interpolation_selector ||
-
(tok(/\*/) && Selector::Universal.new(nil))
-
res << v
-
end
-
-
pos = @scanner.pos
-
line = @line
-
if sel = str? {simple_selector_sequence}
-
@scanner.pos = pos
-
@line = line
-
begin
-
# If we see "*E", don't force a throw because this could be the
-
# "*prop: val" hack.
-
expected('"{"') if res.length == 1 && res[0].is_a?(Selector::Universal)
-
throw_error {expected('"{"')}
-
rescue Sass::SyntaxError => e
-
e.message << "\n\n\"#{sel}\" may only be used at the beginning of a compound selector."
-
raise e
-
end
-
end
-
-
Selector::SimpleSequence.new(res, tok(/!/))
-
end
-
-
1
def parent_selector
-
return unless tok(/&/)
-
Selector::Parent.new
-
end
-
-
1
def class_selector
-
return unless tok(/\./)
-
@expected = "class name"
-
Selector::Class.new(merge(expr!(:interp_ident)))
-
end
-
-
1
def id_selector
-
return unless tok(/#(?!\{)/)
-
@expected = "id name"
-
Selector::Id.new(merge(expr!(:interp_name)))
-
end
-
-
1
def placeholder_selector
-
return unless tok(/%/)
-
@expected = "placeholder name"
-
Selector::Placeholder.new(merge(expr!(:interp_ident)))
-
end
-
-
1
def element_name
-
ns, name = Sass::Util.destructure(qualified_name(:allow_star_name))
-
return unless ns || name
-
-
if name == '*'
-
Selector::Universal.new(merge(ns))
-
else
-
Selector::Element.new(merge(name), merge(ns))
-
end
-
end
-
-
1
def qualified_name(allow_star_name=false)
-
return unless name = interp_ident || tok(/\*/) || (tok?(/\|/) && "")
-
return nil, name unless tok(/\|/)
-
-
return name, expr!(:interp_ident) unless allow_star_name
-
@expected = "identifier or *"
-
return name, interp_ident || tok!(/\*/)
-
end
-
-
1
def interpolation_selector
-
return unless script = interpolation
-
Selector::Interpolation.new(script)
-
end
-
-
1
def attrib
-
return unless tok(/\[/)
-
ss
-
ns, name = attrib_name!
-
ss
-
-
if op = tok(/=/) ||
-
tok(INCLUDES) ||
-
tok(DASHMATCH) ||
-
tok(PREFIXMATCH) ||
-
tok(SUFFIXMATCH) ||
-
tok(SUBSTRINGMATCH)
-
@expected = "identifier or string"
-
ss
-
val = interp_ident || expr!(:interp_string)
-
ss
-
end
-
flags = interp_ident || interp_string
-
tok!(/\]/)
-
-
Selector::Attribute.new(merge(name), merge(ns), op, merge(val), merge(flags))
-
end
-
-
1
def attrib_name!
-
if name_or_ns = interp_ident
-
# E, E|E
-
if tok(/\|(?!=)/)
-
ns = name_or_ns
-
name = interp_ident
-
else
-
name = name_or_ns
-
end
-
else
-
# *|E or |E
-
ns = [tok(/\*/) || ""]
-
tok!(/\|/)
-
name = expr!(:interp_ident)
-
end
-
return ns, name
-
end
-
-
1
def pseudo
-
return unless s = tok(/::?/)
-
@expected = "pseudoclass or pseudoelement"
-
name = expr!(:interp_ident)
-
if tok(/\(/)
-
ss
-
arg = expr!(:pseudo_arg)
-
while tok(/,/)
-
arg << ',' << str{ss}
-
arg.concat expr!(:pseudo_arg)
-
end
-
tok!(/\)/)
-
end
-
Selector::Pseudo.new(s == ':' ? :class : :element, merge(name), merge(arg))
-
end
-
-
1
def pseudo_arg
-
# In the CSS spec, every pseudo-class/element either takes a pseudo
-
# expression or a selector comma sequence as an argument. However, we
-
# don't want to have to know which takes which, so we handle both at
-
# once.
-
#
-
# However, there are some ambiguities between the two. For instance, "n"
-
# could start a pseudo expression like "n+1", or it could start a
-
# selector like "n|m". In order to handle this, we must regrettably
-
# backtrack.
-
expr, sel = nil, nil
-
pseudo_err = catch_error do
-
expr = pseudo_expr
-
next if tok?(/[,)]/)
-
expr = nil
-
expected '")"'
-
end
-
-
return expr if expr
-
sel_err = catch_error {sel = selector}
-
return sel if sel
-
rethrow pseudo_err if pseudo_err
-
rethrow sel_err if sel_err
-
return
-
end
-
-
1
def pseudo_expr
-
return unless e = tok(PLUS) || tok(/[-*]/) || tok(NUMBER) ||
-
interp_string || tok(IDENT) || interpolation
-
res = [e, str{ss}]
-
while e = tok(PLUS) || tok(/[-*]/) || tok(NUMBER) ||
-
interp_string || tok(IDENT) || interpolation
-
res << e << str{ss}
-
end
-
res
-
end
-
-
1
def declaration
-
# This allows the "*prop: val", ":prop: val", and ".prop: val" hacks
-
if s = tok(/[:\*\.]|\#(?!\{)/)
-
@use_property_exception = s !~ /[\.\#]/
-
name = [s, str{ss}, *expr!(:interp_ident)]
-
else
-
return unless name = interp_ident
-
name = [name] if name.is_a?(String)
-
end
-
if comment = tok(COMMENT)
-
name << comment
-
end
-
ss
-
-
tok!(/:/)
-
space, value = value!
-
ss
-
require_block = tok?(/\{/)
-
-
node = node(Sass::Tree::PropNode.new(name.flatten.compact, value, :new))
-
-
return node unless require_block
-
nested_properties! node, space
-
end
-
-
1
def value!
-
space = !str {ss}.empty?
-
@use_property_exception ||= space || !tok?(IDENT)
-
-
return true, Sass::Script::String.new("") if tok?(/\{/)
-
# This is a bit of a dirty trick:
-
# if the value is completely static,
-
# we don't parse it at all, and instead return a plain old string
-
# containing the value.
-
# This results in a dramatic speed increase.
-
if val = tok(STATIC_VALUE, true)
-
return space, Sass::Script::String.new(val.strip)
-
end
-
return space, sass_script(:parse)
-
end
-
-
1
def nested_properties!(node, space)
-
err(<<MESSAGE) unless space
-
Invalid CSS: a space is required between a property and its definition
-
when it has other properties nested beneath it.
-
MESSAGE
-
-
@use_property_exception = true
-
@expected = 'expression (e.g. 1px, bold) or "{"'
-
block(node, :property)
-
end
-
-
1
def expr(allow_var = true)
-
return unless t = term(allow_var)
-
res = [t, str{ss}]
-
-
while (o = operator) && (t = term(allow_var))
-
res << o << t << str{ss}
-
end
-
-
res.flatten
-
end
-
-
1
def term(allow_var)
-
if e = tok(NUMBER) ||
-
interp_uri ||
-
function(allow_var) ||
-
interp_string ||
-
tok(UNICODERANGE) ||
-
interp_ident ||
-
tok(HEXCOLOR) ||
-
(allow_var && var_expr)
-
return e
-
end
-
-
return unless op = tok(/[+-]/)
-
@expected = "number or function"
-
return [op, tok(NUMBER) || function(allow_var) ||
-
(allow_var && var_expr) || expr!(:interpolation)]
-
end
-
-
1
def function(allow_var)
-
return unless name = tok(FUNCTION)
-
if name == "expression(" || name == "calc("
-
str, _ = Sass::Shared.balance(@scanner, ?(, ?), 1)
-
[name, str]
-
else
-
[name, str{ss}, expr(allow_var), tok!(/\)/)]
-
end
-
end
-
-
1
def var_expr
-
return unless tok(/\$/)
-
line = @line
-
var = Sass::Script::Variable.new(tok!(IDENT))
-
var.line = line
-
var
-
end
-
-
1
def interpolation
-
return unless tok(INTERP_START)
-
sass_script(:parse_interpolated)
-
end
-
-
1
def interp_string
-
_interp_string(:double) || _interp_string(:single)
-
end
-
-
1
def interp_uri
-
_interp_string(:uri)
-
end
-
-
1
def _interp_string(type)
-
return unless start = tok(Sass::Script::Lexer::STRING_REGULAR_EXPRESSIONS[type][false])
-
res = [start]
-
-
mid_re = Sass::Script::Lexer::STRING_REGULAR_EXPRESSIONS[type][true]
-
# @scanner[2].empty? means we've started an interpolated section
-
while @scanner[2] == '#{'
-
@scanner.pos -= 2 # Don't consume the #{
-
res.last.slice!(-2..-1)
-
res << expr!(:interpolation) << tok(mid_re)
-
end
-
res
-
end
-
-
1
def interp_ident(start = IDENT)
-
return unless val = tok(start) || interpolation || tok(IDENT_HYPHEN_INTERP, true)
-
res = [val]
-
while val = tok(NAME) || interpolation
-
res << val
-
end
-
res
-
end
-
-
1
def interp_ident_or_var
-
(id = interp_ident) and return id
-
(var = var_expr) and return [var]
-
end
-
-
1
def interp_name
-
interp_ident NAME
-
end
-
-
1
def str
-
@strs.push ""
-
yield
-
@strs.last
-
ensure
-
@strs.pop
-
end
-
-
1
def str?
-
pos = @scanner.pos
-
line = @line
-
@strs.push ""
-
throw_error {yield} && @strs.last
-
rescue Sass::SyntaxError
-
@scanner.pos = pos
-
@line = line
-
nil
-
ensure
-
@strs.pop
-
end
-
-
1
def node(node)
-
node.line = @line
-
node
-
end
-
-
1
@sass_script_parser = Class.new(Sass::Script::Parser)
-
1
@sass_script_parser.send(:include, ScriptParser)
-
# @private
-
1
def self.sass_script_parser; @sass_script_parser; end
-
-
1
def sass_script(*args)
-
parser = self.class.sass_script_parser.new(@scanner, @line,
-
@scanner.pos - (@scanner.string[0...@scanner.pos].rindex("\n") || 0))
-
result = parser.send(*args)
-
unless @strs.empty?
-
# Convert to CSS manually so that comments are ignored.
-
src = result.to_sass
-
@strs.each {|s| s << src}
-
end
-
@line = parser.line
-
result
-
rescue Sass::SyntaxError => e
-
throw(:_sass_parser_error, true) if @throw_error
-
raise e
-
end
-
-
1
def merge(arr)
-
arr && Sass::Util.merge_adjacent_strings([arr].flatten)
-
end
-
-
1
EXPR_NAMES = {
-
:media_query => "media query (e.g. print, screen, print and screen)",
-
:media_query_list => "media query (e.g. print, screen, print and screen)",
-
:media_expr => "media expression (e.g. (min-device-width: 800px))",
-
:pseudo_arg => "expression (e.g. fr, 2n+1)",
-
:interp_ident => "identifier",
-
:interp_name => "identifier",
-
:qualified_name => "identifier",
-
:expr => "expression (e.g. 1px, bold)",
-
:_selector => "selector",
-
:selector_comma_sequence => "selector",
-
:simple_selector_sequence => "selector",
-
:import_arg => "file to import (string or url())",
-
:moz_document_function => "matching function (e.g. url-prefix(), domain())",
-
:supports_condition => "@supports condition (e.g. (display: flexbox))",
-
:supports_condition_in_parens => "@supports condition (e.g. (display: flexbox))",
-
}
-
-
1
TOK_NAMES = Sass::Util.to_hash(
-
52
Sass::SCSS::RX.constants.map {|c| [Sass::SCSS::RX.const_get(c), c.downcase]}).
-
merge(IDENT => "identifier", /[;}]/ => '";"')
-
-
1
def tok?(rx)
-
@scanner.match?(rx)
-
end
-
-
1
def expr!(name)
-
(e = send(name)) && (return e)
-
expected(EXPR_NAMES[name] || name.to_s)
-
end
-
-
1
def tok!(rx)
-
(t = tok(rx)) && (return t)
-
name = TOK_NAMES[rx]
-
-
unless name
-
# Display basic regexps as plain old strings
-
string = rx.source.gsub(/\\(.)/, '\1')
-
name = rx.source == Regexp.escape(string) ? string.inspect : rx.inspect
-
end
-
-
expected(name)
-
end
-
-
1
def expected(name)
-
throw(:_sass_parser_error, true) if @throw_error
-
self.class.expected(@scanner, @expected || name, @line)
-
end
-
-
1
def err(msg)
-
throw(:_sass_parser_error, true) if @throw_error
-
raise Sass::SyntaxError.new(msg, :line => @line)
-
end
-
-
1
def throw_error
-
old_throw_error, @throw_error = @throw_error, false
-
yield
-
ensure
-
@throw_error = old_throw_error
-
end
-
-
1
def catch_error(&block)
-
old_throw_error, @throw_error = @throw_error, true
-
pos = @scanner.pos
-
line = @line
-
expected = @expected
-
if catch(:_sass_parser_error) {yield; false}
-
@scanner.pos = pos
-
@line = line
-
@expected = expected
-
{:pos => pos, :line => line, :expected => @expected, :block => block}
-
end
-
ensure
-
@throw_error = old_throw_error
-
end
-
-
1
def rethrow(err)
-
if @throw_error
-
throw :_sass_parser_error, err
-
else
-
@scanner = Sass::Util::MultibyteStringScanner.new(@scanner.string)
-
@scanner.pos = err[:pos]
-
@line = err[:line]
-
@expected = err[:expected]
-
err[:block].call
-
end
-
end
-
-
# @private
-
1
def self.expected(scanner, expected, line)
-
pos = scanner.pos
-
-
after = scanner.string[0...pos]
-
# Get rid of whitespace between pos and the last token,
-
# but only if there's a newline in there
-
after.gsub!(/\s*\n\s*$/, '')
-
# Also get rid of stuff before the last newline
-
after.gsub!(/.*\n/, '')
-
after = "..." + after[-15..-1] if after.size > 18
-
-
was = scanner.rest.dup
-
# Get rid of whitespace between pos and the next token,
-
# but only if there's a newline in there
-
was.gsub!(/^\s*\n\s*/, '')
-
# Also get rid of stuff after the next newline
-
was.gsub!(/\n.*/, '')
-
was = was[0...15] + "..." if was.size > 18
-
-
raise Sass::SyntaxError.new(
-
"Invalid CSS after \"#{after}\": expected #{expected}, was \"#{was}\"",
-
:line => line)
-
end
-
-
# Avoid allocating lots of new strings for `#tok`.
-
# This is important because `#tok` is called all the time.
-
1
NEWLINE = "\n"
-
-
1
def tok(rx, last_group_lookahead = false)
-
res = @scanner.scan(rx)
-
if res
-
# This fixes https://github.com/nex3/sass/issues/104, which affects
-
# Ruby 1.8.7 and REE. This fix is to replace the ?= zero-width
-
# positive lookahead operator in the Regexp (which matches without
-
# consuming the matched group), with a match that does consume the
-
# group, but then rewinds the scanner and removes the group from the
-
# end of the matched string. This fix makes the assumption that the
-
# matched group will always occur at the end of the match.
-
if last_group_lookahead && @scanner[-1]
-
@scanner.pos -= @scanner[-1].length
-
res.slice!(-@scanner[-1].length..-1)
-
end
-
@line += res.count(NEWLINE)
-
@expected = nil
-
if !@strs.empty? && rx != COMMENT && rx != SINGLE_LINE_COMMENT
-
@strs.each {|s| s << res}
-
end
-
res
-
end
-
end
-
end
-
end
-
end
-
1
module Sass
-
1
module SCSS
-
# A module containing regular expressions used
-
# for lexing tokens in an SCSS document.
-
# Most of these are taken from [the CSS3 spec](http://www.w3.org/TR/css3-syntax/#lexical),
-
# although some have been modified for various reasons.
-
1
module RX
-
# Takes a string and returns a CSS identifier
-
# that will have the value of the given string.
-
#
-
# @param str [String] The string to escape
-
# @return [String] The escaped string
-
1
def self.escape_ident(str)
-
return "" if str.empty?
-
return "\\#{str}" if str == '-' || str == '_'
-
out = ""
-
value = str.dup
-
out << value.slice!(0...1) if value =~ /^[-_]/
-
if value[0...1] =~ NMSTART
-
out << value.slice!(0...1)
-
else
-
out << escape_char(value.slice!(0...1))
-
end
-
out << value.gsub(/[^a-zA-Z0-9_-]/) {|c| escape_char c}
-
return out
-
end
-
-
# Escapes a single character for a CSS identifier.
-
#
-
# @param c [String] The character to escape. Should have length 1
-
# @return [String] The escaped character
-
# @private
-
1
def self.escape_char(c)
-
return "\\%06x" % Sass::Util.ord(c) unless c =~ /[ -\/:-~]/
-
return "\\#{c}"
-
end
-
-
# Creates a Regexp from a plain text string,
-
# escaping all significant characters.
-
#
-
# @param str [String] The text of the regexp
-
# @param flags [Fixnum] Flags for the created regular expression
-
# @return [Regexp]
-
# @private
-
1
def self.quote(str, flags = 0)
-
8
Regexp.new(Regexp.quote(str), flags)
-
end
-
-
1
H = /[0-9a-fA-F]/
-
1
NL = /\n|\r\n|\r|\f/
-
1
UNICODE = /\\#{H}{1,6}[ \t\r\n\f]?/
-
1
s = if Sass::Util.ruby1_8?
-
'\200-\377'
-
elsif Sass::Util.macruby?
-
'\u0080-\uD7FF\uE000-\uFFFD\U00010000-\U0010FFFF'
-
else
-
1
'\u{80}-\u{D7FF}\u{E000}-\u{FFFD}\u{10000}-\u{10FFFF}'
-
end
-
1
NONASCII = /[#{s}]/
-
1
ESCAPE = /#{UNICODE}|\\[ -~#{s}]/
-
1
NMSTART = /[_a-zA-Z]|#{NONASCII}|#{ESCAPE}/
-
1
NMCHAR = /[a-zA-Z0-9_-]|#{NONASCII}|#{ESCAPE}/
-
1
STRING1 = /\"((?:[^\n\r\f\\"]|\\#{NL}|#{ESCAPE})*)\"/
-
1
STRING2 = /\'((?:[^\n\r\f\\']|\\#{NL}|#{ESCAPE})*)\'/
-
-
1
IDENT = /-?#{NMSTART}#{NMCHAR}*/
-
1
NAME = /#{NMCHAR}+/
-
1
NUM = /[0-9]+|[0-9]*\.[0-9]+/
-
1
STRING = /#{STRING1}|#{STRING2}/
-
1
URLCHAR = /[#%&*-~]|#{NONASCII}|#{ESCAPE}/
-
1
URL = /(#{URLCHAR}*)/
-
1
W = /[ \t\r\n\f]*/
-
1
VARIABLE = /(\$)(#{Sass::SCSS::RX::IDENT})/
-
-
# This is more liberal than the spec's definition,
-
# but that definition didn't work well with the greediness rules
-
1
RANGE = /(?:#{H}|\?){1,6}/
-
-
##
-
-
1
S = /[ \t\r\n\f]+/
-
-
1
COMMENT = /\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\//
-
1
SINGLE_LINE_COMMENT = /\/\/.*(\n[ \t]*\/\/.*)*/
-
-
1
CDO = quote("<!--")
-
1
CDC = quote("-->")
-
1
INCLUDES = quote("~=")
-
1
DASHMATCH = quote("|=")
-
1
PREFIXMATCH = quote("^=")
-
1
SUFFIXMATCH = quote("$=")
-
1
SUBSTRINGMATCH = quote("*=")
-
-
1
HASH = /##{NAME}/
-
-
1
IMPORTANT = /!#{W}important/i
-
1
DEFAULT = /!#{W}default/i
-
-
1
NUMBER = /#{NUM}(?:#{IDENT}|%)?/
-
-
1
URI = /url\(#{W}(?:#{STRING}|#{URL})#{W}\)/i
-
1
FUNCTION = /#{IDENT}\(/
-
-
1
UNICODERANGE = /u\+(?:#{H}{1,6}-#{H}{1,6}|#{RANGE})/i
-
-
# Defined in http://www.w3.org/TR/css3-selectors/#lex
-
1
PLUS = /#{W}\+/
-
1
GREATER = /#{W}>/
-
1
TILDE = /#{W}~/
-
1
NOT = quote(":not(", Regexp::IGNORECASE)
-
-
# Defined in https://developer.mozilla.org/en/CSS/@-moz-document as a
-
# non-standard version of http://www.w3.org/TR/css3-conditional/
-
1
URL_PREFIX = /url-prefix\(#{W}(?:#{STRING}|#{URL})#{W}\)/i
-
1
DOMAIN = /domain\(#{W}(?:#{STRING}|#{URL})#{W}\)/i
-
-
# Custom
-
1
HEXCOLOR = /\#[0-9a-fA-F]+/
-
1
INTERP_START = /#\{/
-
1
ANY = /:(-[-\w]+-)?any\(/i
-
1
OPTIONAL = /!#{W}optional/i
-
-
1
IDENT_HYPHEN_INTERP = /-(#\{)/
-
1
STRING1_NOINTERP = /\"((?:[^\n\r\f\\"#]|#(?!\{)|\\#{NL}|#{ESCAPE})*)\"/
-
1
STRING2_NOINTERP = /\'((?:[^\n\r\f\\'#]|#(?!\{)|\\#{NL}|#{ESCAPE})*)\'/
-
1
STRING_NOINTERP = /#{STRING1_NOINTERP}|#{STRING2_NOINTERP}/
-
-
1
STATIC_COMPONENT = /#{IDENT}|#{STRING_NOINTERP}|#{HEXCOLOR}|[+-]?#{NUMBER}|\!important/i
-
1
STATIC_VALUE = /#{STATIC_COMPONENT}(\s*[\s,\/]\s*#{STATIC_COMPONENT})*([;}])/i
-
1
STATIC_SELECTOR = /(#{NMCHAR}|[ \t]|[,>+*]|[:#.]#{NMSTART}){0,50}([{])/i
-
end
-
end
-
end
-
1
module Sass
-
1
module SCSS
-
# A mixin for subclasses of {Sass::Script::Lexer}
-
# that makes them usable by {SCSS::Parser} to parse SassScript.
-
# In particular, the lexer doesn't support `!` for a variable prefix.
-
1
module ScriptLexer
-
1
private
-
-
1
def variable
-
return [:raw, "!important"] if scan(Sass::SCSS::RX::IMPORTANT)
-
_variable(Sass::SCSS::RX::VARIABLE)
-
end
-
end
-
end
-
end
-
1
module Sass
-
1
module SCSS
-
# A mixin for subclasses of {Sass::Script::Parser}
-
# that makes them usable by {SCSS::Parser} to parse SassScript.
-
# In particular, the parser won't raise an error
-
# when there's more content in the lexer once lexing is done.
-
# In addition, the parser doesn't support `!` for a variable prefix.
-
1
module ScriptParser
-
1
private
-
-
# @private
-
1
def lexer_class
-
klass = Class.new(super)
-
klass.send(:include, ScriptLexer)
-
klass
-
end
-
-
# Instead of raising an error when the parser is done,
-
# rewind the StringScanner so that it hasn't consumed the final token.
-
1
def assert_done
-
@lexer.unpeek!
-
end
-
end
-
end
-
end
-
1
require 'sass/script/css_parser'
-
-
1
module Sass
-
1
module SCSS
-
# A parser for a static SCSS tree.
-
# Parses with SCSS extensions, like nested rules and parent selectors,
-
# but without dynamic SassScript.
-
# This is useful for e.g. \{#parse\_selector parsing selectors}
-
# after resolving the interpolation.
-
1
class StaticParser < Parser
-
# Parses the text as a selector.
-
#
-
# @param filename [String, nil] The file in which the selector appears,
-
# or nil if there is no such file.
-
# Used for error reporting.
-
# @return [Selector::CommaSequence] The parsed selector
-
# @raise [Sass::SyntaxError] if there's a syntax error in the selector
-
1
def parse_selector
-
init_scanner!
-
seq = expr!(:selector_comma_sequence)
-
expected("selector") unless @scanner.eos?
-
seq.line = @line
-
seq.filename = @filename
-
seq
-
end
-
-
1
private
-
-
1
def moz_document_function
-
return unless val = tok(URI) || tok(URL_PREFIX) || tok(DOMAIN) ||
-
function(!:allow_var)
-
ss
-
[val]
-
end
-
-
1
def variable; nil; end
-
1
def script_value; nil; end
-
1
def interpolation; nil; end
-
1
def var_expr; nil; end
-
1
def interp_string; s = tok(STRING) and [s]; end
-
1
def interp_uri; s = tok(URI) and [s]; end
-
1
def interp_ident(ident = IDENT); s = tok(ident) and [s]; end
-
1
def use_css_import?; true; end
-
-
1
def special_directive(name)
-
return unless %w[media import charset -moz-document].include?(name)
-
super
-
end
-
-
1
@sass_script_parser = Class.new(Sass::Script::CssParser)
-
1
@sass_script_parser.send(:include, ScriptParser)
-
end
-
end
-
end
-
1
require 'sass/selector/simple'
-
1
require 'sass/selector/abstract_sequence'
-
1
require 'sass/selector/comma_sequence'
-
1
require 'sass/selector/sequence'
-
1
require 'sass/selector/simple_sequence'
-
-
1
module Sass
-
# A namespace for nodes in the parse tree for selectors.
-
#
-
# {CommaSequence} is the toplevel seelctor,
-
# representing a comma-separated sequence of {Sequence}s,
-
# such as `foo bar, baz bang`.
-
# {Sequence} is the next level,
-
# representing {SimpleSequence}s separated by combinators (e.g. descendant or child),
-
# such as `foo bar` or `foo > bar baz`.
-
# {SimpleSequence} is a sequence of selectors that all apply to a single element,
-
# such as `foo.bar[attr=val]`.
-
# Finally, {Simple} is the superclass of the simplest selectors,
-
# such as `.foo` or `#bar`.
-
1
module Selector
-
# The base used for calculating selector specificity. The spec says this
-
# should be "sufficiently high"; it's extremely unlikely that any single
-
# selector sequence will contain 1,000 simple selectors.
-
#
-
# @type [Fixnum]
-
1
SPECIFICITY_BASE = 1_000
-
-
# A parent-referencing selector (`&` in Sass).
-
# The function of this is to be replaced by the parent selector
-
# in the nested hierarchy.
-
1
class Parent < Simple
-
# @see Selector#to_a
-
1
def to_a
-
["&"]
-
end
-
-
# Always raises an exception.
-
#
-
# @raise [Sass::SyntaxError] Parent selectors should be resolved before unification
-
# @see Selector#unify
-
1
def unify(sels)
-
raise Sass::SyntaxError.new("[BUG] Cannot unify parent selectors.")
-
end
-
end
-
-
# A class selector (e.g. `.foo`).
-
1
class Class < Simple
-
# The class name.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
1
attr_reader :name
-
-
# @param name [Array<String, Sass::Script::Node>] The class name
-
1
def initialize(name)
-
@name = name
-
end
-
-
# @see Selector#to_a
-
1
def to_a
-
[".", *@name]
-
end
-
-
# @see AbstractSequence#specificity
-
1
def specificity
-
SPECIFICITY_BASE
-
end
-
end
-
-
# An id selector (e.g. `#foo`).
-
1
class Id < Simple
-
# The id name.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
1
attr_reader :name
-
-
# @param name [Array<String, Sass::Script::Node>] The id name
-
1
def initialize(name)
-
@name = name
-
end
-
-
# @see Selector#to_a
-
1
def to_a
-
["#", *@name]
-
end
-
-
# Returns `nil` if `sels` contains an {Id} selector
-
# with a different name than this one.
-
#
-
# @see Selector#unify
-
1
def unify(sels)
-
return if sels.any? {|sel2| sel2.is_a?(Id) && self.name != sel2.name}
-
super
-
end
-
-
# @see AbstractSequence#specificity
-
1
def specificity
-
SPECIFICITY_BASE**2
-
end
-
end
-
-
# A placeholder selector (e.g. `%foo`).
-
# This exists to be replaced via `@extend`.
-
# Rulesets using this selector will not be printed, but can be extended.
-
# Otherwise, this acts just like a class selector.
-
1
class Placeholder < Simple
-
# The placeholder name.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
1
attr_reader :name
-
-
# @param name [Array<String, Sass::Script::Node>] The placeholder name
-
1
def initialize(name)
-
@name = name
-
end
-
-
# @see Selector#to_a
-
1
def to_a
-
["%", *@name]
-
end
-
-
# @see AbstractSequence#specificity
-
1
def specificity
-
SPECIFICITY_BASE
-
end
-
end
-
-
# A universal selector (`*` in CSS).
-
1
class Universal < Simple
-
# The selector namespace.
-
# `nil` means the default namespace,
-
# `[""]` means no namespace,
-
# `["*"]` means any namespace.
-
#
-
# @return [Array<String, Sass::Script::Node>, nil]
-
1
attr_reader :namespace
-
-
# @param namespace [Array<String, Sass::Script::Node>, nil] See \{#namespace}
-
1
def initialize(namespace)
-
@namespace = namespace
-
end
-
-
# @see Selector#to_a
-
1
def to_a
-
@namespace ? @namespace + ["|*"] : ["*"]
-
end
-
-
# Unification of a universal selector is somewhat complicated,
-
# especially when a namespace is specified.
-
# If there is no namespace specified
-
# or any namespace is specified (namespace `"*"`),
-
# then `sel` is returned without change
-
# (unless it's empty, in which case `"*"` is required).
-
#
-
# If a namespace is specified
-
# but `sel` does not specify a namespace,
-
# then the given namespace is applied to `sel`,
-
# either by adding this {Universal} selector
-
# or applying this namespace to an existing {Element} selector.
-
#
-
# If both this selector *and* `sel` specify namespaces,
-
# those namespaces are unified via {Simple#unify_namespaces}
-
# and the unified namespace is used, if possible.
-
#
-
# @todo There are lots of cases that this documentation specifies;
-
# make sure we thoroughly test **all of them**.
-
# @todo Keep track of whether a default namespace has been declared
-
# and handle namespace-unspecified selectors accordingly.
-
# @todo If any branch of a CommaSequence ends up being just `"*"`,
-
# then all other branches should be eliminated
-
#
-
# @see Selector#unify
-
1
def unify(sels)
-
name =
-
case sels.first
-
when Universal; :universal
-
when Element; sels.first.name
-
else
-
return [self] + sels unless namespace.nil? || namespace == ['*']
-
return sels unless sels.empty?
-
return [self]
-
end
-
-
ns, accept = unify_namespaces(namespace, sels.first.namespace)
-
return unless accept
-
[name == :universal ? Universal.new(ns) : Element.new(name, ns)] + sels[1..-1]
-
end
-
-
# @see AbstractSequence#specificity
-
1
def specificity
-
0
-
end
-
end
-
-
# An element selector (e.g. `h1`).
-
1
class Element < Simple
-
# The element name.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
1
attr_reader :name
-
-
# The selector namespace.
-
# `nil` means the default namespace,
-
# `[""]` means no namespace,
-
# `["*"]` means any namespace.
-
#
-
# @return [Array<String, Sass::Script::Node>, nil]
-
1
attr_reader :namespace
-
-
# @param name [Array<String, Sass::Script::Node>] The element name
-
# @param namespace [Array<String, Sass::Script::Node>, nil] See \{#namespace}
-
1
def initialize(name, namespace)
-
@name = name
-
@namespace = namespace
-
end
-
-
# @see Selector#to_a
-
1
def to_a
-
@namespace ? @namespace + ["|"] + @name : @name
-
end
-
-
# Unification of an element selector is somewhat complicated,
-
# especially when a namespace is specified.
-
# First, if `sel` contains another {Element} with a different \{#name},
-
# then the selectors can't be unified and `nil` is returned.
-
#
-
# Otherwise, if `sel` doesn't specify a namespace,
-
# or it specifies any namespace (via `"*"`),
-
# then it's returned with this element selector
-
# (e.g. `.foo` becomes `a.foo` or `svg|a.foo`).
-
# Similarly, if this selector doesn't specify a namespace,
-
# the namespace from `sel` is used.
-
#
-
# If both this selector *and* `sel` specify namespaces,
-
# those namespaces are unified via {Simple#unify_namespaces}
-
# and the unified namespace is used, if possible.
-
#
-
# @todo There are lots of cases that this documentation specifies;
-
# make sure we thoroughly test **all of them**.
-
# @todo Keep track of whether a default namespace has been declared
-
# and handle namespace-unspecified selectors accordingly.
-
#
-
# @see Selector#unify
-
1
def unify(sels)
-
case sels.first
-
when Universal;
-
when Element; return unless name == sels.first.name
-
else return [self] + sels
-
end
-
-
ns, accept = unify_namespaces(namespace, sels.first.namespace)
-
return unless accept
-
[Element.new(name, ns)] + sels[1..-1]
-
end
-
-
# @see AbstractSequence#specificity
-
1
def specificity
-
1
-
end
-
end
-
-
# Selector interpolation (`#{}` in Sass).
-
1
class Interpolation < Simple
-
# The script to run.
-
#
-
# @return [Sass::Script::Node]
-
1
attr_reader :script
-
-
# @param script [Sass::Script::Node] The script to run
-
1
def initialize(script)
-
@script = script
-
end
-
-
# @see Selector#to_a
-
1
def to_a
-
[@script]
-
end
-
-
# Always raises an exception.
-
#
-
# @raise [Sass::SyntaxError] Interpolation selectors should be resolved before unification
-
# @see Selector#unify
-
1
def unify(sels)
-
raise Sass::SyntaxError.new("[BUG] Cannot unify interpolation selectors.")
-
end
-
end
-
-
# An attribute selector (e.g. `[href^="http://"]`).
-
1
class Attribute < Simple
-
# The attribute name.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
1
attr_reader :name
-
-
# The attribute namespace.
-
# `nil` means the default namespace,
-
# `[""]` means no namespace,
-
# `["*"]` means any namespace.
-
#
-
# @return [Array<String, Sass::Script::Node>, nil]
-
1
attr_reader :namespace
-
-
# The matching operator, e.g. `"="` or `"^="`.
-
#
-
# @return [String]
-
1
attr_reader :operator
-
-
# The right-hand side of the operator.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
1
attr_reader :value
-
-
# Flags for the attribute selector (e.g. `i`).
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
1
attr_reader :flags
-
-
# @param name [Array<String, Sass::Script::Node>] The attribute name
-
# @param namespace [Array<String, Sass::Script::Node>, nil] See \{#namespace}
-
# @param operator [String] The matching operator, e.g. `"="` or `"^="`
-
# @param value [Array<String, Sass::Script::Node>] See \{#value}
-
# @param value [Array<String, Sass::Script::Node>] See \{#flags}
-
1
def initialize(name, namespace, operator, value, flags)
-
@name = name
-
@namespace = namespace
-
@operator = operator
-
@value = value
-
@flags = flags
-
end
-
-
# @see Selector#to_a
-
1
def to_a
-
res = ["["]
-
res.concat(@namespace) << "|" if @namespace
-
res.concat @name
-
(res << @operator).concat @value if @value
-
(res << " ").concat @flags if @flags
-
res << "]"
-
end
-
-
# @see AbstractSequence#specificity
-
1
def specificity
-
SPECIFICITY_BASE
-
end
-
end
-
-
# A pseudoclass (e.g. `:visited`) or pseudoelement (e.g. `::first-line`) selector.
-
# It can have arguments (e.g. `:nth-child(2n+1)`).
-
1
class Pseudo < Simple
-
# Some psuedo-class-syntax selectors are actually considered
-
# pseudo-elements and must be treated differently. This is a list of such
-
# selectors
-
#
-
# @return [Array<String>]
-
1
ACTUALLY_ELEMENTS = %w[after before first-line first-letter]
-
-
# Like \{#type}, but returns the type of selector this looks like, rather
-
# than the type it is semantically. This only differs from type for
-
# selectors in \{ACTUALLY\_ELEMENTS}.
-
#
-
# @return [Symbol]
-
1
attr_reader :syntactic_type
-
-
# The name of the selector.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
1
attr_reader :name
-
-
# The argument to the selector,
-
# or `nil` if no argument was given.
-
#
-
# This may include SassScript nodes that will be run during resolution.
-
# Note that this should not include SassScript nodes
-
# after resolution has taken place.
-
#
-
# @return [Array<String, Sass::Script::Node>, nil]
-
1
attr_reader :arg
-
-
# @param type [Symbol] See \{#type}
-
# @param name [Array<String, Sass::Script::Node>] The name of the selector
-
# @param arg [nil, Array<String, Sass::Script::Node>] The argument to the selector,
-
# or nil if no argument was given
-
1
def initialize(type, name, arg)
-
@syntactic_type = type
-
@name = name
-
@arg = arg
-
end
-
-
# The type of the selector. `:class` if this is a pseudoclass selector,
-
# `:element` if it's a pseudoelement.
-
#
-
# @return [Symbol]
-
1
def type
-
ACTUALLY_ELEMENTS.include?(name.first) ? :element : syntactic_type
-
end
-
-
# @see Selector#to_a
-
1
def to_a
-
res = [syntactic_type == :class ? ":" : "::"] + @name
-
(res << "(").concat(Sass::Util.strip_string_array(@arg)) << ")" if @arg
-
res
-
end
-
-
# Returns `nil` if this is a pseudoelement selector
-
# and `sels` contains a pseudoelement selector different than this one.
-
#
-
# @see Selector#unify
-
1
def unify(sels)
-
return if type == :element && sels.any? do |sel|
-
sel.is_a?(Pseudo) && sel.type == :element &&
-
(sel.name != self.name || sel.arg != self.arg)
-
end
-
super
-
end
-
-
# @see AbstractSequence#specificity
-
1
def specificity
-
type == :class ? SPECIFICITY_BASE : 1
-
end
-
end
-
-
# A pseudoclass selector whose argument is itself a selector
-
# (e.g. `:not(.foo)` or `:-moz-all(.foo, .bar)`).
-
1
class SelectorPseudoClass < Simple
-
# The name of the pseudoclass.
-
#
-
# @return [String]
-
1
attr_reader :name
-
-
# The selector argument.
-
#
-
# @return [Selector::Sequence]
-
1
attr_reader :selector
-
-
# @param [String] The name of the pseudoclass
-
# @param [Selector::CommaSequence] The selector argument
-
1
def initialize(name, selector)
-
@name = name
-
@selector = selector
-
end
-
-
# @see Selector#to_a
-
1
def to_a
-
[":", @name, "("] + @selector.to_a + [")"]
-
end
-
-
# @see AbstractSequence#specificity
-
1
def specificity
-
SPECIFICITY_BASE
-
end
-
end
-
end
-
end
-
1
module Sass
-
1
module Selector
-
# The abstract parent class of the various selector sequence classes.
-
#
-
# All subclasses should implement a `members` method that returns an array
-
# of object that respond to `#line=` and `#filename=`, as well as a `to_a`
-
# method that returns an array of strings and script nodes.
-
1
class AbstractSequence
-
# The line of the Sass template on which this selector was declared.
-
#
-
# @return [Fixnum]
-
1
attr_reader :line
-
-
# The name of the file in which this selector was declared.
-
#
-
# @return [String, nil]
-
1
attr_reader :filename
-
-
# Sets the line of the Sass template on which this selector was declared.
-
# This also sets the line for all child selectors.
-
#
-
# @param line [Fixnum]
-
# @return [Fixnum]
-
1
def line=(line)
-
members.each {|m| m.line = line}
-
@line = line
-
end
-
-
# Sets the name of the file in which this selector was declared,
-
# or `nil` if it was not declared in a file (e.g. on stdin).
-
# This also sets the filename for all child selectors.
-
#
-
# @param filename [String, nil]
-
# @return [String, nil]
-
1
def filename=(filename)
-
members.each {|m| m.filename = filename}
-
@filename = filename
-
end
-
-
# Returns a hash code for this sequence.
-
#
-
# Subclasses should define `#_hash` rather than overriding this method,
-
# which automatically handles memoizing the result.
-
#
-
# @return [Fixnum]
-
1
def hash
-
@_hash ||= _hash
-
end
-
-
# Checks equality between this and another object.
-
#
-
# Subclasses should define `#_eql?` rather than overriding this method,
-
# which handles checking class equality and hash equality.
-
#
-
# @param other [Object] The object to test equality against
-
# @return [Boolean] Whether or not this is equal to `other`
-
1
def eql?(other)
-
other.class == self.class && other.hash == self.hash && _eql?(other)
-
end
-
1
alias_method :==, :eql?
-
-
# Whether or not this selector sequence contains a placeholder selector.
-
# Checks recursively.
-
1
def has_placeholder?
-
@has_placeholder ||=
-
members.any? {|m| m.is_a?(AbstractSequence) ? m.has_placeholder? : m.is_a?(Placeholder)}
-
end
-
-
# Converts the selector into a string. This is the standard selector
-
# string, along with any SassScript interpolation that may exist.
-
#
-
# @return [String]
-
1
def to_s
-
to_a.map {|e| e.is_a?(Sass::Script::Node) ? "\#{#{e.to_sass}}" : e}.join
-
end
-
-
# Returns the specificity of the selector as an integer. The base is given
-
# by {Sass::Selector::SPECIFICITY_BASE}.
-
#
-
# @return [Fixnum]
-
1
def specificity
-
_specificity(members)
-
end
-
-
1
protected
-
-
1
def _specificity(arr)
-
spec = 0
-
arr.map {|m| spec += m.is_a?(String) ? 0 : m.specificity}
-
spec
-
end
-
end
-
end
-
end
-
1
module Sass
-
1
module Selector
-
# A comma-separated sequence of selectors.
-
1
class CommaSequence < AbstractSequence
-
# The comma-separated selector sequences
-
# represented by this class.
-
#
-
# @return [Array<Sequence>]
-
1
attr_reader :members
-
-
# @param seqs [Array<Sequence>] See \{#members}
-
1
def initialize(seqs)
-
@members = seqs
-
end
-
-
# Resolves the {Parent} selectors within this selector
-
# by replacing them with the given parent selector,
-
# handling commas appropriately.
-
#
-
# @param super_cseq [CommaSequence] The parent selector
-
# @return [CommaSequence] This selector, with parent references resolved
-
# @raise [Sass::SyntaxError] If a parent selector is invalid
-
1
def resolve_parent_refs(super_cseq)
-
if super_cseq.nil?
-
if @members.any? do |sel|
-
sel.members.any? do |sel_or_op|
-
sel_or_op.is_a?(SimpleSequence) && sel_or_op.members.any? {|ssel| ssel.is_a?(Parent)}
-
end
-
end
-
raise Sass::SyntaxError.new("Base-level rules cannot contain the parent-selector-referencing character '&'.")
-
end
-
return self
-
end
-
-
CommaSequence.new(
-
super_cseq.members.map do |super_seq|
-
@members.map {|seq| seq.resolve_parent_refs(super_seq)}
-
end.flatten)
-
end
-
-
# Non-destrucively extends this selector with the extensions specified in a hash
-
# (which should come from {Sass::Tree::Visitors::Cssize}).
-
#
-
# @todo Link this to the reference documentation on `@extend`
-
# when such a thing exists.
-
#
-
# @param extends [Sass::Util::SubsetMap{Selector::Simple =>
-
# Sass::Tree::Visitors::Cssize::Extend}]
-
# The extensions to perform on this selector
-
# @param parent_directives [Array<Sass::Tree::DirectiveNode>]
-
# The directives containing this selector.
-
# @return [CommaSequence] A copy of this selector,
-
# with extensions made according to `extends`
-
1
def do_extend(extends, parent_directives)
-
CommaSequence.new(members.map do |seq|
-
extended = seq.do_extend(extends, parent_directives)
-
# First Law of Extend: the result of extending a selector should
-
# always contain the base selector.
-
#
-
# See https://github.com/nex3/sass/issues/324.
-
extended.unshift seq unless seq.has_placeholder? || extended.include?(seq)
-
extended
-
end.flatten)
-
end
-
-
# Returns a string representation of the sequence.
-
# This is basically the selector string.
-
#
-
# @return [String]
-
1
def inspect
-
members.map {|m| m.inspect}.join(", ")
-
end
-
-
# @see Simple#to_a
-
1
def to_a
-
arr = Sass::Util.intersperse(@members.map {|m| m.to_a}, ", ").flatten
-
arr.delete("\n")
-
arr
-
end
-
-
1
private
-
-
1
def _hash
-
members.hash
-
end
-
-
1
def _eql?(other)
-
other.class == self.class && other.members.eql?(self.members)
-
end
-
end
-
end
-
end
-
1
module Sass
-
1
module Selector
-
# An operator-separated sequence of
-
# {SimpleSequence simple selector sequences}.
-
1
class Sequence < AbstractSequence
-
# Sets the line of the Sass template on which this selector was declared.
-
# This also sets the line for all child selectors.
-
#
-
# @param line [Fixnum]
-
# @return [Fixnum]
-
1
def line=(line)
-
members.each {|m| m.line = line if m.is_a?(SimpleSequence)}
-
line
-
end
-
-
# Sets the name of the file in which this selector was declared,
-
# or `nil` if it was not declared in a file (e.g. on stdin).
-
# This also sets the filename for all child selectors.
-
#
-
# @param filename [String, nil]
-
# @return [String, nil]
-
1
def filename=(filename)
-
members.each {|m| m.filename = filename if m.is_a?(SimpleSequence)}
-
filename
-
end
-
-
# The array of {SimpleSequence simple selector sequences}, operators, and
-
# newlines. The operators are strings such as `"+"` and `">"` representing
-
# the corresponding CSS operators, or interpolated SassScript. Newlines
-
# are also newline strings; these aren't semantically relevant, but they
-
# do affect formatting.
-
#
-
# @return [Array<SimpleSequence, String|Array<Sass::Tree::Node, String>>]
-
1
attr_reader :members
-
-
# @param seqs_and_ops [Array<SimpleSequence, String|Array<Sass::Tree::Node, String>>] See \{#members}
-
1
def initialize(seqs_and_ops)
-
@members = seqs_and_ops
-
end
-
-
# Resolves the {Parent} selectors within this selector
-
# by replacing them with the given parent selector,
-
# handling commas appropriately.
-
#
-
# @param super_seq [Sequence] The parent selector sequence
-
# @return [Sequence] This selector, with parent references resolved
-
# @raise [Sass::SyntaxError] If a parent selector is invalid
-
1
def resolve_parent_refs(super_seq)
-
members = @members.dup
-
nl = (members.first == "\n" && members.shift)
-
unless members.any? do |seq_or_op|
-
seq_or_op.is_a?(SimpleSequence) && seq_or_op.members.first.is_a?(Parent)
-
end
-
old_members, members = members, []
-
members << nl if nl
-
members << SimpleSequence.new([Parent.new], false)
-
members += old_members
-
end
-
-
Sequence.new(
-
members.map do |seq_or_op|
-
next seq_or_op unless seq_or_op.is_a?(SimpleSequence)
-
seq_or_op.resolve_parent_refs(super_seq)
-
end.flatten)
-
end
-
-
# Non-destructively extends this selector with the extensions specified in a hash
-
# (which should come from {Sass::Tree::Visitors::Cssize}).
-
#
-
# @overload def do_extend(extends, parent_directives)
-
# @param extends [Sass::Util::SubsetMap{Selector::Simple =>
-
# Sass::Tree::Visitors::Cssize::Extend}]
-
# The extensions to perform on this selector
-
# @param parent_directives [Array<Sass::Tree::DirectiveNode>]
-
# The directives containing this selector.
-
# @return [Array<Sequence>] A list of selectors generated
-
# by extending this selector with `extends`.
-
# These correspond to a {CommaSequence}'s {CommaSequence#members members array}.
-
# @see CommaSequence#do_extend
-
1
def do_extend(extends, parent_directives, seen = Set.new)
-
extended_not_expanded = members.map do |sseq_or_op|
-
next [[sseq_or_op]] unless sseq_or_op.is_a?(SimpleSequence)
-
extended = sseq_or_op.do_extend(extends, parent_directives, seen)
-
choices = extended.map {|seq| seq.members}
-
choices.unshift([sseq_or_op]) unless extended.any? {|seq| seq.superselector?(sseq_or_op)}
-
choices
-
end
-
weaves = Sass::Util.paths(extended_not_expanded).map {|path| weave(path)}
-
Sass::Util.flatten(trim(weaves), 1).map {|p| Sequence.new(p)}
-
end
-
-
# Returns whether or not this selector matches all elements
-
# that the given selector matches (as well as possibly more).
-
#
-
# @example
-
# (.foo).superselector?(.foo.bar) #=> true
-
# (.foo).superselector?(.bar) #=> false
-
# (.bar .foo).superselector?(.foo) #=> false
-
# @param sseq [SimpleSequence]
-
# @return [Boolean]
-
1
def superselector?(sseq)
-
return false unless members.size == 1
-
members.last.superselector?(sseq)
-
end
-
-
# @see Simple#to_a
-
1
def to_a
-
ary = @members.map {|seq_or_op| seq_or_op.is_a?(SimpleSequence) ? seq_or_op.to_a : seq_or_op}
-
Sass::Util.intersperse(ary, " ").flatten.compact
-
end
-
-
# Returns a string representation of the sequence.
-
# This is basically the selector string.
-
#
-
# @return [String]
-
1
def inspect
-
members.map {|m| m.inspect}.join(" ")
-
end
-
-
# Add to the {SimpleSequence#sources} sets of the child simple sequences.
-
# This destructively modifies this sequence's members array, but not the
-
# child simple sequences.
-
#
-
# @param sources [Set<Sequence>]
-
1
def add_sources!(sources)
-
members.map! {|m| m.is_a?(SimpleSequence) ? m.with_more_sources(sources) : m}
-
end
-
-
1
private
-
-
# Conceptually, this expands "parenthesized selectors".
-
# That is, if we have `.A .B {@extend .C}` and `.D .C {...}`,
-
# this conceptually expands into `.D .C, .D (.A .B)`,
-
# and this function translates `.D (.A .B)` into `.D .A .B, .A.D .B, .D .A .B`.
-
#
-
# @param path [Array<Array<SimpleSequence or String>>] A list of parenthesized selector groups.
-
# @return [Array<Array<SimpleSequence or String>>] A list of fully-expanded selectors.
-
1
def weave(path)
-
# This function works by moving through the selector path left-to-right,
-
# building all possible prefixes simultaneously. These prefixes are
-
# `befores`, while the remaining parenthesized suffixes is `afters`.
-
befores = [[]]
-
afters = path.dup
-
-
until afters.empty?
-
current = afters.shift.dup
-
last_current = [current.pop]
-
befores = Sass::Util.flatten(befores.map do |before|
-
next [] unless sub = subweave(before, current)
-
sub.map {|seqs| seqs + last_current}
-
end, 1)
-
end
-
return befores
-
end
-
-
# This interweaves two lists of selectors,
-
# returning all possible orderings of them (including using unification)
-
# that maintain the relative ordering of the input arrays.
-
#
-
# For example, given `.foo .bar` and `.baz .bang`,
-
# this would return `.foo .bar .baz .bang`, `.foo .bar.baz .bang`,
-
# `.foo .baz .bar .bang`, `.foo .baz .bar.bang`, `.foo .baz .bang .bar`,
-
# and so on until `.baz .bang .foo .bar`.
-
#
-
# Semantically, for selectors A and B, this returns all selectors `AB_i`
-
# such that the union over all i of elements matched by `AB_i X` is
-
# identical to the intersection of all elements matched by `A X` and all
-
# elements matched by `B X`. Some `AB_i` are elided to reduce the size of
-
# the output.
-
#
-
# @param seq1 [Array<SimpleSequence or String>]
-
# @param seq2 [Array<SimpleSequence or String>]
-
# @return [Array<Array<SimpleSequence or String>>]
-
1
def subweave(seq1, seq2)
-
return [seq2] if seq1.empty?
-
return [seq1] if seq2.empty?
-
-
seq1, seq2 = seq1.dup, seq2.dup
-
return unless init = merge_initial_ops(seq1, seq2)
-
return unless fin = merge_final_ops(seq1, seq2)
-
seq1 = group_selectors(seq1)
-
seq2 = group_selectors(seq2)
-
lcs = Sass::Util.lcs(seq2, seq1) do |s1, s2|
-
next s1 if s1 == s2
-
next unless s1.first.is_a?(SimpleSequence) && s2.first.is_a?(SimpleSequence)
-
next s2 if parent_superselector?(s1, s2)
-
next s1 if parent_superselector?(s2, s1)
-
end
-
-
diff = [[init]]
-
until lcs.empty?
-
diff << chunks(seq1, seq2) {|s| parent_superselector?(s.first, lcs.first)} << [lcs.shift]
-
seq1.shift
-
seq2.shift
-
end
-
diff << chunks(seq1, seq2) {|s| s.empty?}
-
diff += fin.map {|sel| sel.is_a?(Array) ? sel : [sel]}
-
diff.reject! {|c| c.empty?}
-
-
Sass::Util.paths(diff).map {|p| p.flatten}.reject {|p| path_has_two_subjects?(p)}
-
end
-
-
# Extracts initial selector combinators (`"+"`, `">"`, `"~"`, and `"\n"`)
-
# from two sequences and merges them together into a single array of
-
# selector combinators.
-
#
-
# @param seq1 [Array<SimpleSequence or String>]
-
# @param seq2 [Array<SimpleSequence or String>]
-
# @return [Array<String>, nil] If there are no operators in the merged
-
# sequence, this will be the empty array. If the operators cannot be
-
# merged, this will be nil.
-
1
def merge_initial_ops(seq1, seq2)
-
ops1, ops2 = [], []
-
ops1 << seq1.shift while seq1.first.is_a?(String)
-
ops2 << seq2.shift while seq2.first.is_a?(String)
-
-
newline = false
-
newline ||= !!ops1.shift if ops1.first == "\n"
-
newline ||= !!ops2.shift if ops2.first == "\n"
-
-
# If neither sequence is a subsequence of the other, they cannot be
-
# merged successfully
-
lcs = Sass::Util.lcs(ops1, ops2)
-
return unless lcs == ops1 || lcs == ops2
-
return (newline ? ["\n"] : []) + (ops1.size > ops2.size ? ops1 : ops2)
-
end
-
-
# Extracts final selector combinators (`"+"`, `">"`, `"~"`) and the
-
# selectors to which they apply from two sequences and merges them
-
# together into a single array.
-
#
-
# @param seq1 [Array<SimpleSequence or String>]
-
# @param seq2 [Array<SimpleSequence or String>]
-
# @return [Array<SimpleSequence or String or
-
# Array<Array<SimpleSequence or String>>]
-
# If there are no trailing combinators to be merged, this will be the
-
# empty array. If the trailing combinators cannot be merged, this will
-
# be nil. Otherwise, this will contained the merged selector. Array
-
# elements are [Sass::Util#paths]-style options; conceptually, an "or"
-
# of multiple selectors.
-
1
def merge_final_ops(seq1, seq2, res = [])
-
ops1, ops2 = [], []
-
ops1 << seq1.pop while seq1.last.is_a?(String)
-
ops2 << seq2.pop while seq2.last.is_a?(String)
-
-
# Not worth the headache of trying to preserve newlines here. The most
-
# important use of newlines is at the beginning of the selector to wrap
-
# across lines anyway.
-
ops1.reject! {|o| o == "\n"}
-
ops2.reject! {|o| o == "\n"}
-
-
return res if ops1.empty? && ops2.empty?
-
if ops1.size > 1 || ops2.size > 1
-
# If there are multiple operators, something hacky's going on. If one
-
# is a supersequence of the other, use that, otherwise give up.
-
lcs = Sass::Util.lcs(ops1, ops2)
-
return unless lcs == ops1 || lcs == ops2
-
res.unshift(*(ops1.size > ops2.size ? ops1 : ops2).reverse)
-
return res
-
end
-
-
# This code looks complicated, but it's actually just a bunch of special
-
# cases for interactions between different combinators.
-
op1, op2 = ops1.first, ops2.first
-
if op1 && op2
-
sel1 = seq1.pop
-
sel2 = seq2.pop
-
if op1 == '~' && op2 == '~'
-
if sel1.superselector?(sel2)
-
res.unshift sel2, '~'
-
elsif sel2.superselector?(sel1)
-
res.unshift sel1, '~'
-
else
-
merged = sel1.unify(sel2.members, sel2.subject?)
-
res.unshift [
-
[sel1, '~', sel2, '~'],
-
[sel2, '~', sel1, '~'],
-
([merged, '~'] if merged)
-
].compact
-
end
-
elsif (op1 == '~' && op2 == '+') || (op1 == '+' && op2 == '~')
-
if op1 == '~'
-
tilde_sel, plus_sel = sel1, sel2
-
else
-
tilde_sel, plus_sel = sel2, sel1
-
end
-
-
if tilde_sel.superselector?(plus_sel)
-
res.unshift plus_sel, '+'
-
else
-
merged = plus_sel.unify(tilde_sel.members, tilde_sel.subject?)
-
res.unshift [
-
[tilde_sel, '~', plus_sel, '+'],
-
([merged, '+'] if merged)
-
].compact
-
end
-
elsif op1 == '>' && %w[~ +].include?(op2)
-
res.unshift sel2, op2
-
seq1.push sel1, op1
-
elsif op2 == '>' && %w[~ +].include?(op1)
-
res.unshift sel1, op1
-
seq2.push sel2, op2
-
elsif op1 == op2
-
return unless merged = sel1.unify(sel2.members, sel2.subject?)
-
res.unshift merged, op1
-
else
-
# Unknown selector combinators can't be unified
-
return
-
end
-
return merge_final_ops(seq1, seq2, res)
-
elsif op1
-
seq2.pop if op1 == '>' && seq2.last && seq2.last.superselector?(seq1.last)
-
res.unshift seq1.pop, op1
-
return merge_final_ops(seq1, seq2, res)
-
else # op2
-
seq1.pop if op2 == '>' && seq1.last && seq1.last.superselector?(seq2.last)
-
res.unshift seq2.pop, op2
-
return merge_final_ops(seq1, seq2, res)
-
end
-
end
-
-
# Takes initial subsequences of `seq1` and `seq2` and returns all
-
# orderings of those subsequences. The initial subsequences are determined
-
# by a block.
-
#
-
# Destructively removes the initial subsequences of `seq1` and `seq2`.
-
#
-
# For example, given `(A B C | D E)` and `(1 2 | 3 4 5)` (with `|`
-
# denoting the boundary of the initial subsequence), this would return
-
# `[(A B C 1 2), (1 2 A B C)]`. The sequences would then be `(D E)` and
-
# `(3 4 5)`.
-
#
-
# @param seq1 [Array]
-
# @param seq2 [Array]
-
# @yield [a] Used to determine when to cut off the initial subsequences.
-
# Called repeatedly for each sequence until it returns true.
-
# @yieldparam a [Array] A final subsequence of one input sequence after
-
# cutting off some initial subsequence.
-
# @yieldreturn [Boolean] Whether or not to cut off the initial subsequence
-
# here.
-
# @return [Array<Array>] All possible orderings of the initial subsequences.
-
1
def chunks(seq1, seq2)
-
chunk1 = []
-
chunk1 << seq1.shift until yield seq1
-
chunk2 = []
-
chunk2 << seq2.shift until yield seq2
-
return [] if chunk1.empty? && chunk2.empty?
-
return [chunk2] if chunk1.empty?
-
return [chunk1] if chunk2.empty?
-
[chunk1 + chunk2, chunk2 + chunk1]
-
end
-
-
# Groups a sequence into subsequences. The subsequences are determined by
-
# strings; adjacent non-string elements will be put into separate groups,
-
# but any element adjacent to a string will be grouped with that string.
-
#
-
# For example, `(A B "C" D E "F" G "H" "I" J)` will become `[(A) (B "C" D)
-
# (E "F" G "H" "I" J)]`.
-
#
-
# @param seq [Array]
-
# @return [Array<Array>]
-
1
def group_selectors(seq)
-
newseq = []
-
tail = seq.dup
-
until tail.empty?
-
head = []
-
begin
-
head << tail.shift
-
end while !tail.empty? && head.last.is_a?(String) || tail.first.is_a?(String)
-
newseq << head
-
end
-
return newseq
-
end
-
-
# Given two selector sequences, returns whether `seq1` is a
-
# superselector of `seq2`; that is, whether `seq1` matches every
-
# element `seq2` matches.
-
#
-
# @param seq1 [Array<SimpleSequence or String>]
-
# @param seq2 [Array<SimpleSequence or String>]
-
# @return [Boolean]
-
1
def _superselector?(seq1, seq2)
-
seq1 = seq1.reject {|e| e == "\n"}
-
seq2 = seq2.reject {|e| e == "\n"}
-
# Selectors with leading or trailing operators are neither
-
# superselectors nor subselectors.
-
return if seq1.last.is_a?(String) || seq2.last.is_a?(String) ||
-
seq1.first.is_a?(String) || seq2.first.is_a?(String)
-
# More complex selectors are never superselectors of less complex ones
-
return if seq1.size > seq2.size
-
return seq1.first.superselector?(seq2.last) if seq1.size == 1
-
-
_, si = Sass::Util.enum_with_index(seq2).find do |e, i|
-
return if i == seq2.size - 1
-
next if e.is_a?(String)
-
seq1.first.superselector?(e)
-
end
-
return unless si
-
-
if seq1[1].is_a?(String)
-
return unless seq2[si+1].is_a?(String)
-
# .foo ~ .bar is a superselector of .foo + .bar
-
return unless seq1[1] == "~" ? seq2[si+1] != ">" : seq1[1] == seq2[si+1]
-
return _superselector?(seq1[2..-1], seq2[si+2..-1])
-
elsif seq2[si+1].is_a?(String)
-
return unless seq2[si+1] == ">"
-
return _superselector?(seq1[1..-1], seq2[si+2..-1])
-
else
-
return _superselector?(seq1[1..-1], seq2[si+1..-1])
-
end
-
end
-
-
# Like \{#_superselector?}, but compares the selectors in the
-
# context of parent selectors, as though they shared an implicit
-
# base simple selector. For example, `B` is not normally a
-
# superselector of `B A`, since it doesn't match `A` elements.
-
# However, it is a parent superselector, since `B X` is a
-
# superselector of `B A X`.
-
#
-
# @param seq1 [Array<SimpleSequence or String>]
-
# @param seq2 [Array<SimpleSequence or String>]
-
# @return [Boolean]
-
1
def parent_superselector?(seq1, seq2)
-
base = Sass::Selector::SimpleSequence.new([Sass::Selector::Placeholder.new('<temp>')], false)
-
_superselector?(seq1 + [base], seq2 + [base])
-
end
-
-
# Removes redundant selectors from between multiple lists of
-
# selectors. This takes a list of lists of selector sequences;
-
# each individual list is assumed to have no redundancy within
-
# itself. A selector is only removed if it's redundant with a
-
# selector in another list.
-
#
-
# "Redundant" here means that one selector is a superselector of
-
# the other. The more specific selector is removed.
-
#
-
# @param seqses [Array<Array<Array<SimpleSequence or String>>>]
-
# @return [Array<Array<Array<SimpleSequence or String>>>]
-
1
def trim(seqses)
-
# Avoid truly horrific quadratic behavior. TODO: I think there
-
# may be a way to get perfect trimming without going quadratic.
-
return seqses if seqses.size > 100
-
-
# Keep the results in a separate array so we can be sure we aren't
-
# comparing against an already-trimmed selector. This ensures that two
-
# identical selectors don't mutually trim one another.
-
result = seqses.dup
-
-
# This is n^2 on the sequences, but only comparing between
-
# separate sequences should limit the quadratic behavior.
-
seqses.each_with_index do |seqs1, i|
-
result[i] = seqs1.reject do |seq1|
-
max_spec = _sources(seq1).map {|seq| seq.specificity}.max || 0
-
result.any? do |seqs2|
-
next if seqs1.equal?(seqs2)
-
# Second Law of Extend: the specificity of a generated selector
-
# should never be less than the specificity of the extending
-
# selector.
-
#
-
# See https://github.com/nex3/sass/issues/324.
-
seqs2.any? {|seq2| _specificity(seq2) >= max_spec && _superselector?(seq2, seq1)}
-
end
-
end
-
end
-
result
-
end
-
-
1
def _hash
-
members.reject {|m| m == "\n"}.hash
-
end
-
-
1
def _eql?(other)
-
other.members.reject {|m| m == "\n"}.eql?(self.members.reject {|m| m == "\n"})
-
end
-
-
1
private
-
-
1
def path_has_two_subjects?(path)
-
subject = false
-
path.each do |sseq_or_op|
-
next unless sseq_or_op.is_a?(SimpleSequence)
-
next unless sseq_or_op.subject?
-
return true if subject
-
subject = true
-
end
-
false
-
end
-
-
1
def _sources(seq)
-
s = Set.new
-
seq.map {|sseq_or_op| s.merge sseq_or_op.sources if sseq_or_op.is_a?(SimpleSequence)}
-
s
-
end
-
-
1
def extended_not_expanded_to_s(extended_not_expanded)
-
extended_not_expanded.map do |choices|
-
choices = choices.map do |sel|
-
next sel.first.to_s if sel.size == 1
-
"#{sel.join ' '}"
-
end
-
next choices.first if choices.size == 1 && !choices.include?(' ')
-
"(#{choices.join ', '})"
-
end.join ' '
-
end
-
end
-
end
-
end
-
1
module Sass
-
1
module Selector
-
# The abstract superclass for simple selectors
-
# (that is, those that don't compose multiple selectors).
-
1
class Simple
-
# The line of the Sass template on which this selector was declared.
-
#
-
# @return [Fixnum]
-
1
attr_accessor :line
-
-
# The name of the file in which this selector was declared,
-
# or `nil` if it was not declared in a file (e.g. on stdin).
-
#
-
# @return [String, nil]
-
1
attr_accessor :filename
-
-
# Returns a representation of the node
-
# as an array of strings and potentially {Sass::Script::Node}s
-
# (if there's interpolation in the selector).
-
# When the interpolation is resolved and the strings are joined together,
-
# this will be the string representation of this node.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
1
def to_a
-
Sass::Util.abstract(self)
-
end
-
-
# Returns a string representation of the node.
-
# This is basically the selector string.
-
#
-
# @return [String]
-
1
def inspect
-
to_a.map {|e| e.is_a?(Sass::Script::Node) ? "\#{#{e.to_sass}}" : e}.join
-
end
-
-
# @see \{#inspect}
-
# @return [String]
-
1
def to_s
-
inspect
-
end
-
-
# Returns a hash code for this selector object.
-
#
-
# By default, this is based on the value of \{#to\_a},
-
# so if that contains information irrelevant to the identity of the selector,
-
# this should be overridden.
-
#
-
# @return [Fixnum]
-
1
def hash
-
@_hash ||= to_a.hash
-
end
-
-
# Checks equality between this and another object.
-
#
-
# By default, this is based on the value of \{#to\_a},
-
# so if that contains information irrelevant to the identity of the selector,
-
# this should be overridden.
-
#
-
# @param other [Object] The object to test equality against
-
# @return [Boolean] Whether or not this is equal to `other`
-
1
def eql?(other)
-
other.class == self.class && other.hash == self.hash && other.to_a.eql?(to_a)
-
end
-
1
alias_method :==, :eql?
-
-
# Unifies this selector with a {SimpleSequence}'s {SimpleSequence#members members array},
-
# returning another `SimpleSequence` members array
-
# that matches both this selector and the input selector.
-
#
-
# By default, this just appends this selector to the end of the array
-
# (or returns the original array if this selector already exists in it).
-
#
-
# @param sels [Array<Simple>] A {SimpleSequence}'s {SimpleSequence#members members array}
-
# @return [Array<Simple>, nil] A {SimpleSequence} {SimpleSequence#members members array}
-
# matching both `sels` and this selector,
-
# or `nil` if this is impossible (e.g. unifying `#foo` and `#bar`)
-
# @raise [Sass::SyntaxError] If this selector cannot be unified.
-
# This will only ever occur when a dynamic selector,
-
# such as {Parent} or {Interpolation}, is used in unification.
-
# Since these selectors should be resolved
-
# by the time extension and unification happen,
-
# this exception will only ever be raised as a result of programmer error
-
1
def unify(sels)
-
return sels if sels.any? {|sel2| eql?(sel2)}
-
sels_with_ix = Sass::Util.enum_with_index(sels)
-
_, i =
-
if self.is_a?(Pseudo) || self.is_a?(SelectorPseudoClass)
-
sels_with_ix.find {|sel, _| sel.is_a?(Pseudo) && (sels.last.type == :element)}
-
else
-
sels_with_ix.find {|sel, _| sel.is_a?(Pseudo) || sel.is_a?(SelectorPseudoClass)}
-
end
-
return sels + [self] unless i
-
return sels[0...i] + [self] + sels[i..-1]
-
end
-
-
1
protected
-
-
# Unifies two namespaces,
-
# returning a namespace that works for both of them if possible.
-
#
-
# @param ns1 [String, nil] The first namespace.
-
# `nil` means none specified, e.g. `foo`.
-
# The empty string means no namespace specified, e.g. `|foo`.
-
# `"*"` means any namespace is allowed, e.g. `*|foo`.
-
# @param ns2 [String, nil] The second namespace. See `ns1`.
-
# @return [Array(String or nil, Boolean)]
-
# The first value is the unified namespace, or `nil` for no namespace.
-
# The second value is whether or not a namespace that works for both inputs
-
# could be found at all.
-
# If the second value is `false`, the first should be ignored.
-
1
def unify_namespaces(ns1, ns2)
-
return nil, false unless ns1 == ns2 || ns1.nil? || ns1 == ['*'] || ns2.nil? || ns2 == ['*']
-
return ns2, true if ns1 == ['*']
-
return ns1, true if ns2 == ['*']
-
return ns1 || ns2, true
-
end
-
end
-
end
-
end
-
1
module Sass
-
1
module Selector
-
# A unseparated sequence of selectors
-
# that all apply to a single element.
-
# For example, `.foo#bar[attr=baz]` is a simple sequence
-
# of the selectors `.foo`, `#bar`, and `[attr=baz]`.
-
1
class SimpleSequence < AbstractSequence
-
# The array of individual selectors.
-
#
-
# @return [Array<Simple>]
-
1
attr_accessor :members
-
-
# The extending selectors that caused this selector sequence to be
-
# generated. For example:
-
#
-
# a.foo { ... }
-
# b.bar {@extend a}
-
# c.baz {@extend b}
-
#
-
# The generated selector `b.foo.bar` has `{b.bar}` as its `sources` set,
-
# and the generated selector `c.foo.bar.baz` has `{b.bar, c.baz}` as its
-
# `sources` set.
-
#
-
# This is populated during the {#do_extend} process.
-
#
-
# @return {Set<Sequence>}
-
1
attr_accessor :sources
-
-
# @see \{#subject?}
-
1
attr_writer :subject
-
-
# Returns the element or universal selector in this sequence,
-
# if it exists.
-
#
-
# @return [Element, Universal, nil]
-
1
def base
-
@base ||= (members.first if members.first.is_a?(Element) || members.first.is_a?(Universal))
-
end
-
-
1
def pseudo_elements
-
@pseudo_elements ||= (members - [base]).
-
select {|sel| sel.is_a?(Pseudo) && sel.type == :element}
-
end
-
-
# Returns the non-base, non-pseudo-class selectors in this sequence.
-
#
-
# @return [Set<Simple>]
-
1
def rest
-
@rest ||= Set.new(members - [base] - pseudo_elements)
-
end
-
-
# Whether or not this compound selector is the subject of the parent
-
# selector; that is, whether it is prepended with `$` and represents the
-
# actual element that will be selected.
-
#
-
# @return [Boolean]
-
1
def subject?
-
@subject
-
end
-
-
# @param selectors [Array<Simple>] See \{#members}
-
# @param subject [Boolean] See \{#subject?}
-
# @param sources [Set<Sequence>]
-
1
def initialize(selectors, subject, sources = Set.new)
-
@members = selectors
-
@subject = subject
-
@sources = sources
-
end
-
-
# Resolves the {Parent} selectors within this selector
-
# by replacing them with the given parent selector,
-
# handling commas appropriately.
-
#
-
# @param super_seq [Sequence] The parent selector sequence
-
# @return [Array<SimpleSequence>] This selector, with parent references resolved.
-
# This is an array because the parent selector is itself a {Sequence}
-
# @raise [Sass::SyntaxError] If a parent selector is invalid
-
1
def resolve_parent_refs(super_seq)
-
# Parent selector only appears as the first selector in the sequence
-
return [self] unless @members.first.is_a?(Parent)
-
-
members = super_seq.members.dup
-
newline = members.pop if members.last == "\n"
-
return members if @members.size == 1
-
unless members.last.is_a?(SimpleSequence)
-
raise Sass::SyntaxError.new("Invalid parent selector: " + super_seq.to_a.join)
-
end
-
-
members[0...-1] +
-
[SimpleSequence.new(members.last.members + @members[1..-1], subject?)] +
-
[newline].compact
-
end
-
-
# Non-destrucively extends this selector with the extensions specified in a hash
-
# (which should come from {Sass::Tree::Visitors::Cssize}).
-
#
-
# @overload def do_extend(extends, parent_directives)
-
# @param extends [{Selector::Simple =>
-
# Sass::Tree::Visitors::Cssize::Extend}]
-
# The extensions to perform on this selector
-
# @param parent_directives [Array<Sass::Tree::DirectiveNode>]
-
# The directives containing this selector.
-
# @return [Array<Sequence>] A list of selectors generated
-
# by extending this selector with `extends`.
-
# @see CommaSequence#do_extend
-
1
def do_extend(extends, parent_directives, seen = Set.new)
-
Sass::Util.group_by_to_a(extends.get(members.to_set)) {|ex, _| ex.extender}.map do |seq, group|
-
sels = group.map {|_, s| s}.flatten
-
# If A {@extend B} and C {...},
-
# seq is A, sels is B, and self is C
-
-
self_without_sel = Sass::Util.array_minus(self.members, sels)
-
group.each {|e, _| e.result = :failed_to_unify unless e.result == :succeeded}
-
next unless unified = seq.members.last.unify(self_without_sel, subject?)
-
group.each {|e, _| e.result = :succeeded}
-
next if group.map {|e, _| check_directives_match!(e, parent_directives)}.none?
-
new_seq = Sequence.new(seq.members[0...-1] + [unified])
-
new_seq.add_sources!(sources + [seq])
-
[sels, new_seq]
-
end.compact.map do |sels, seq|
-
seen.include?(sels) ? [] : seq.do_extend(extends, parent_directives, seen + [sels])
-
end.flatten.uniq
-
end
-
-
# Unifies this selector with another {SimpleSequence}'s {SimpleSequence#members members array},
-
# returning another `SimpleSequence`
-
# that matches both this selector and the input selector.
-
#
-
# @param sels [Array<Simple>] A {SimpleSequence}'s {SimpleSequence#members members array}
-
# @param subject [Boolean] Whether the {SimpleSequence} being merged is a subject.
-
# @return [SimpleSequence, nil] A {SimpleSequence} matching both `sels` and this selector,
-
# or `nil` if this is impossible (e.g. unifying `#foo` and `#bar`)
-
# @raise [Sass::SyntaxError] If this selector cannot be unified.
-
# This will only ever occur when a dynamic selector,
-
# such as {Parent} or {Interpolation}, is used in unification.
-
# Since these selectors should be resolved
-
# by the time extension and unification happen,
-
# this exception will only ever be raised as a result of programmer error
-
1
def unify(sels, other_subject)
-
return unless sseq = members.inject(sels) do |member, sel|
-
return unless member
-
sel.unify(member)
-
end
-
SimpleSequence.new(sseq, other_subject || subject?)
-
end
-
-
# Returns whether or not this selector matches all elements
-
# that the given selector matches (as well as possibly more).
-
#
-
# @example
-
# (.foo).superselector?(.foo.bar) #=> true
-
# (.foo).superselector?(.bar) #=> false
-
# @param sseq [SimpleSequence]
-
# @return [Boolean]
-
1
def superselector?(sseq)
-
(base.nil? || base.eql?(sseq.base)) &&
-
pseudo_elements.eql?(sseq.pseudo_elements) &&
-
rest.subset?(sseq.rest)
-
end
-
-
# @see Simple#to_a
-
1
def to_a
-
res = @members.map {|sel| sel.to_a}.flatten
-
res << '!' if subject?
-
res
-
end
-
-
# Returns a string representation of the sequence.
-
# This is basically the selector string.
-
#
-
# @return [String]
-
1
def inspect
-
members.map {|m| m.inspect}.join
-
end
-
-
# Return a copy of this simple sequence with `sources` merged into the
-
# {#sources} set.
-
#
-
# @param sources [Set<Sequence>]
-
# @return [SimpleSequence]
-
1
def with_more_sources(sources)
-
sseq = dup
-
sseq.members = members.dup
-
sseq.sources = self.sources | sources
-
sseq
-
end
-
-
1
private
-
-
1
def check_directives_match!(extend, parent_directives)
-
dirs1 = extend.directives.map {|d| d.resolved_value}
-
dirs2 = parent_directives.map {|d| d.resolved_value}
-
return true if Sass::Util.subsequence?(dirs1, dirs2)
-
-
Sass::Util.sass_warn <<WARNING
-
DEPRECATION WARNING on line #{extend.node.line}#{" of #{extend.node.filename}" if extend.node.filename}:
-
@extending an outer selector from within #{extend.directives.last.name} is deprecated.
-
You may only @extend selectors within the same directive.
-
This will be an error in Sass 3.3.
-
It can only work once @extend is supported natively in the browser.
-
WARNING
-
return false
-
end
-
-
1
def _hash
-
[base, Sass::Util.set_hash(rest)].hash
-
end
-
-
1
def _eql?(other)
-
other.base.eql?(self.base) && other.pseudo_elements == pseudo_elements &&
-
Sass::Util.set_eql?(other.rest, self.rest) && other.subject? == self.subject?
-
end
-
end
-
end
-
end
-
1
module Sass
-
# This module contains functionality that's shared between Haml and Sass.
-
1
module Shared
-
1
extend self
-
-
# Scans through a string looking for the interoplation-opening `#{`
-
# and, when it's found, yields the scanner to the calling code
-
# so it can handle it properly.
-
#
-
# The scanner will have any backslashes immediately in front of the `#{`
-
# as the second capture group (`scan[2]`),
-
# and the text prior to that as the first (`scan[1]`).
-
#
-
# @yieldparam scan [StringScanner] The scanner scanning through the string
-
# @return [String] The text remaining in the scanner after all `#{`s have been processed
-
1
def handle_interpolation(str)
-
scan = Sass::Util::MultibyteStringScanner.new(str)
-
yield scan while scan.scan(/(.*?)(\\*)\#\{/m)
-
scan.rest
-
end
-
-
# Moves a scanner through a balanced pair of characters.
-
# For example:
-
#
-
# Foo (Bar (Baz bang) bop) (Bang (bop bip))
-
# ^ ^
-
# from to
-
#
-
# @param scanner [StringScanner] The string scanner to move
-
# @param start [Character] The character opening the balanced pair.
-
# A `Fixnum` in 1.8, a `String` in 1.9
-
# @param finish [Character] The character closing the balanced pair.
-
# A `Fixnum` in 1.8, a `String` in 1.9
-
# @param count [Fixnum] The number of opening characters matched
-
# before calling this method
-
# @return [(String, String)] The string matched within the balanced pair
-
# and the rest of the string.
-
# `["Foo (Bar (Baz bang) bop)", " (Bang (bop bip))"]` in the example above.
-
1
def balance(scanner, start, finish, count = 0)
-
str = ''
-
scanner = Sass::Util::MultibyteStringScanner.new(scanner) unless scanner.is_a? StringScanner
-
regexp = Regexp.new("(.*?)[\\#{start.chr}\\#{finish.chr}]", Regexp::MULTILINE)
-
while scanner.scan(regexp)
-
str << scanner.matched
-
count += 1 if scanner.matched[-1] == start
-
count -= 1 if scanner.matched[-1] == finish
-
return [str.strip, scanner.rest] if count == 0
-
end
-
end
-
-
# Formats a string for use in error messages about indentation.
-
#
-
# @param indentation [String] The string used for indentation
-
# @param was [Boolean] Whether or not to add `"was"` or `"were"`
-
# (depending on how many characters were in `indentation`)
-
# @return [String] The name of the indentation (e.g. `"12 spaces"`, `"1 tab"`)
-
1
def human_indentation(indentation, was = false)
-
if !indentation.include?(?\t)
-
noun = 'space'
-
elsif !indentation.include?(?\s)
-
noun = 'tab'
-
else
-
return indentation.inspect + (was ? ' was' : '')
-
end
-
-
singular = indentation.length == 1
-
if was
-
was = singular ? ' was' : ' were'
-
else
-
was = ''
-
end
-
-
"#{indentation.length} #{noun}#{'s' unless singular}#{was}"
-
end
-
end
-
end
-
1
module Sass::Tree
-
# A static node representing an unproccessed Sass `@charset` directive.
-
#
-
# @see Sass::Tree
-
1
class CharsetNode < Node
-
# The name of the charset.
-
#
-
# @return [String]
-
1
attr_accessor :name
-
-
# @param name [String] see \{#name}
-
1
def initialize(name)
-
@name = name
-
super()
-
end
-
-
# @see Node#invisible?
-
1
def invisible?
-
!Sass::Util.ruby1_8?
-
end
-
end
-
end
-
1
require 'sass/tree/node'
-
-
1
module Sass::Tree
-
# A static node representing a Sass comment (silent or loud).
-
#
-
# @see Sass::Tree
-
1
class CommentNode < Node
-
# The text of the comment, not including `/*` and `*/`.
-
# Interspersed with {Sass::Script::Node}s representing `#{}`-interpolation
-
# if this is a loud comment.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
1
attr_accessor :value
-
-
# The text of the comment
-
# after any interpolated SassScript has been resolved.
-
# Only set once \{Tree::Visitors::Perform} has been run.
-
#
-
# @return [String]
-
1
attr_accessor :resolved_value
-
-
# The type of the comment. `:silent` means it's never output to CSS,
-
# `:normal` means it's output in every compile mode except `:compressed`,
-
# and `:loud` means it's output even in `:compressed`.
-
#
-
# @return [Symbol]
-
1
attr_accessor :type
-
-
# @param value [Array<String, Sass::Script::Node>] See \{#value}
-
# @param type [Symbol] See \{#type}
-
1
def initialize(value, type)
-
@value = Sass::Util.with_extracted_values(value) {|str| normalize_indentation str}
-
@type = type
-
super()
-
end
-
-
# Compares the contents of two comments.
-
#
-
# @param other [Object] The object to compare with
-
# @return [Boolean] Whether or not this node and the other object
-
# are the same
-
1
def ==(other)
-
self.class == other.class && value == other.value && type == other.type
-
end
-
-
# Returns `true` if this is a silent comment
-
# or the current style doesn't render comments.
-
#
-
# Comments starting with ! are never invisible (and the ! is removed from the output.)
-
#
-
# @return [Boolean]
-
1
def invisible?
-
case @type
-
when :loud; false
-
when :silent; true
-
else; style == :compressed
-
end
-
end
-
-
# Returns the number of lines in the comment.
-
#
-
# @return [Fixnum]
-
1
def lines
-
@value.inject(0) do |s, e|
-
next s + e.count("\n") if e.is_a?(String)
-
next s
-
end
-
end
-
-
1
private
-
-
1
def normalize_indentation(str)
-
ind = str.split("\n").inject(str[/^[ \t]*/].split("")) do |pre, line|
-
line[/^[ \t]*/].split("").zip(pre).inject([]) do |arr, (a, b)|
-
break arr if a != b
-
arr << a
-
end
-
end.join
-
str.gsub(/^#{ind}/, '')
-
end
-
end
-
end
-
1
module Sass
-
1
module Tree
-
# A node representing the placement within a mixin of the include statement's content.
-
#
-
# @see Sass::Tree
-
1
class ContentNode < Node
-
end
-
end
-
end
-
1
module Sass::Tree
-
# A node representing an `@import` rule that's importing plain CSS.
-
#
-
# @see Sass::Tree
-
1
class CssImportNode < DirectiveNode
-
# The URI being imported, either as a plain string or an interpolated
-
# script string.
-
#
-
# @return [String, Sass::Script::Node]
-
1
attr_accessor :uri
-
-
# The text of the URI being imported after any interpolated SassScript has
-
# been resolved. Only set once \{Tree::Visitors::Perform} has been run.
-
#
-
# @return [String]
-
1
attr_accessor :resolved_uri
-
-
# The media query for this rule, interspersed with {Sass::Script::Node}s
-
# representing `#{}`-interpolation. Any adjacent strings will be merged
-
# together.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
1
attr_accessor :query
-
-
# The media query for this rule, without any unresolved interpolation. It's
-
# only set once {Tree::Node#perform} has been called.
-
#
-
# @return [Sass::Media::QueryList]
-
1
attr_accessor :resolved_query
-
-
# @param uri [String, Sass::Script::Node] See \{#uri}
-
# @param query [Array<String, Sass::Script::Node>] See \{#query}
-
1
def initialize(uri, query = nil)
-
@uri = uri
-
@query = query
-
super('')
-
end
-
-
# @param uri [String] See \{#resolved_uri}
-
# @return [CssImportNode]
-
1
def self.resolved(uri)
-
node = new(uri)
-
node.resolved_uri = uri
-
node
-
end
-
-
# @see DirectiveNode#value
-
1
def value; raise NotImplementedError; end
-
-
# @see DirectiveNode#resolved_value
-
1
def resolved_value
-
@resolved_value ||=
-
begin
-
str = "@import #{resolved_uri}"
-
str << " #{resolved_query.to_css}" if resolved_query
-
str
-
end
-
end
-
end
-
end
-
1
module Sass
-
1
module Tree
-
# A dynamic node representing a Sass `@debug` statement.
-
#
-
# @see Sass::Tree
-
1
class DebugNode < Node
-
# The expression to print.
-
# @return [Script::Node]
-
1
attr_accessor :expr
-
-
# @param expr [Script::Node] The expression to print
-
1
def initialize(expr)
-
@expr = expr
-
super()
-
end
-
end
-
end
-
end
-
1
module Sass::Tree
-
# A static node representing an unproccessed Sass `@`-directive.
-
# Directives known to Sass, like `@for` and `@debug`,
-
# are handled by their own nodes;
-
# only CSS directives like `@media` and `@font-face` become {DirectiveNode}s.
-
#
-
# `@import` and `@charset` are special cases;
-
# they become {ImportNode}s and {CharsetNode}s, respectively.
-
#
-
# @see Sass::Tree
-
1
class DirectiveNode < Node
-
# The text of the directive, `@` and all, with interpolation included.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
1
attr_accessor :value
-
-
# The text of the directive after any interpolated SassScript has been resolved.
-
# Only set once \{Tree::Visitors::Perform} has been run.
-
#
-
# @return [String]
-
1
attr_accessor :resolved_value
-
-
# @param value [Array<String, Sass::Script::Node>] See \{#value}
-
1
def initialize(value)
-
@value = value
-
super()
-
end
-
-
# @param value [String] See \{#resolved_value}
-
# @return [DirectiveNode]
-
1
def self.resolved(value)
-
node = new([value])
-
node.resolved_value = value
-
node
-
end
-
-
# @return [String] The name of the directive, including `@`.
-
1
def name
-
value.first.gsub(/ .*$/, '')
-
end
-
end
-
end
-
1
require 'sass/tree/node'
-
-
1
module Sass::Tree
-
# A dynamic node representing a Sass `@each` loop.
-
#
-
# @see Sass::Tree
-
1
class EachNode < Node
-
# The name of the loop variable.
-
# @return [String]
-
1
attr_reader :var
-
-
# The parse tree for the list.
-
# @param [Script::Node]
-
1
attr_accessor :list
-
-
# @param var [String] The name of the loop variable
-
# @param list [Script::Node] The parse tree for the list
-
1
def initialize(var, list)
-
@var = var
-
@list = list
-
super()
-
end
-
end
-
end
-
1
require 'sass/tree/node'
-
-
1
module Sass::Tree
-
# A static node reprenting an `@extend` directive.
-
#
-
# @see Sass::Tree
-
1
class ExtendNode < Node
-
# The parsed selector after interpolation has been resolved.
-
# Only set once {Tree::Visitors::Perform} has been run.
-
#
-
# @return [Selector::CommaSequence]
-
1
attr_accessor :resolved_selector
-
-
# The CSS selector to extend, interspersed with {Sass::Script::Node}s
-
# representing `#{}`-interpolation.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
1
attr_accessor :selector
-
-
# Whether the `@extend` is allowed to match no selectors or not.
-
#
-
# @return [Boolean]
-
1
def optional?; @optional; end
-
-
# @param selector [Array<String, Sass::Script::Node>]
-
# The CSS selector to extend,
-
# interspersed with {Sass::Script::Node}s
-
# representing `#{}`-interpolation.
-
# @param optional [Boolean] See \{#optional}
-
1
def initialize(selector, optional)
-
@selector = selector
-
@optional = optional
-
super()
-
end
-
end
-
end
-
1
require 'sass/tree/node'
-
-
1
module Sass::Tree
-
# A dynamic node representing a Sass `@for` loop.
-
#
-
# @see Sass::Tree
-
1
class ForNode < Node
-
# The name of the loop variable.
-
# @return [String]
-
1
attr_reader :var
-
-
# The parse tree for the initial expression.
-
# @return [Script::Node]
-
1
attr_accessor :from
-
-
# The parse tree for the final expression.
-
# @return [Script::Node]
-
1
attr_accessor :to
-
-
# Whether to include `to` in the loop or stop just before.
-
# @return [Boolean]
-
1
attr_reader :exclusive
-
-
# @param var [String] See \{#var}
-
# @param from [Script::Node] See \{#from}
-
# @param to [Script::Node] See \{#to}
-
# @param exclusive [Boolean] See \{#exclusive}
-
1
def initialize(var, from, to, exclusive)
-
@var = var
-
@from = from
-
@to = to
-
@exclusive = exclusive
-
super()
-
end
-
end
-
end
-
1
module Sass
-
1
module Tree
-
# A dynamic node representing a function definition.
-
#
-
# @see Sass::Tree
-
1
class FunctionNode < Node
-
# The name of the function.
-
# @return [String]
-
1
attr_reader :name
-
-
# The arguments to the function. Each element is a tuple
-
# containing the variable for argument and the parse tree for
-
# the default value of the argument
-
#
-
# @return [Array<Script::Node>]
-
1
attr_accessor :args
-
-
# The splat argument for this function, if one exists.
-
#
-
# @return [Script::Node?]
-
1
attr_accessor :splat
-
-
# @param name [String] The function name
-
# @param args [Array<(Script::Node, Script::Node)>] The arguments for the function.
-
# @param splat [Script::Node] See \{#splat}
-
1
def initialize(name, args, splat)
-
@name = name
-
@args = args
-
@splat = splat
-
super()
-
end
-
end
-
end
-
end
-
1
require 'sass/tree/node'
-
-
1
module Sass::Tree
-
# A dynamic node representing a Sass `@if` statement.
-
#
-
# {IfNode}s are a little odd, in that they also represent `@else` and `@else if`s.
-
# This is done as a linked list:
-
# each {IfNode} has a link (\{#else}) to the next {IfNode}.
-
#
-
# @see Sass::Tree
-
1
class IfNode < Node
-
# The conditional expression.
-
# If this is nil, this is an `@else` node, not an `@else if`.
-
#
-
# @return [Script::Expr]
-
1
attr_accessor :expr
-
-
# The next {IfNode} in the if-else list, or `nil`.
-
#
-
# @return [IfNode]
-
1
attr_accessor :else
-
-
# @param expr [Script::Expr] See \{#expr}
-
1
def initialize(expr)
-
@expr = expr
-
@last_else = self
-
super()
-
end
-
-
# Append an `@else` node to the end of the list.
-
#
-
# @param node [IfNode] The `@else` node to append
-
1
def add_else(node)
-
@last_else.else = node
-
@last_else = node
-
end
-
-
1
def _dump(f)
-
Marshal.dump([self.expr, self.else, self.children])
-
end
-
-
1
def self._load(data)
-
expr, else_, children = Marshal.load(data)
-
node = IfNode.new(expr)
-
node.else = else_
-
node.children = children
-
node.instance_variable_set('@last_else',
-
node.else ? node.else.instance_variable_get('@last_else') : node)
-
node
-
end
-
end
-
end
-
1
module Sass
-
1
module Tree
-
# A static node that wraps the {Sass::Tree} for an `@import`ed file.
-
# It doesn't have a functional purpose other than to add the `@import`ed file
-
# to the backtrace if an error occurs.
-
1
class ImportNode < RootNode
-
# The name of the imported file as it appears in the Sass document.
-
#
-
# @return [String]
-
1
attr_reader :imported_filename
-
-
# Sets the imported file.
-
1
attr_writer :imported_file
-
-
# @param imported_filename [String] The name of the imported file
-
1
def initialize(imported_filename)
-
@imported_filename = imported_filename
-
super(nil)
-
end
-
-
1
def invisible?; to_s.empty?; end
-
-
# Returns the imported file.
-
#
-
# @return [Sass::Engine]
-
# @raise [Sass::SyntaxError] If no file could be found to import.
-
1
def imported_file
-
@imported_file ||= import
-
end
-
-
# Returns whether or not this import should emit a CSS @import declaration
-
#
-
# @return [Boolean] Whether or not this is a simple CSS @import declaration.
-
1
def css_import?
-
if @imported_filename =~ /\.css$/
-
@imported_filename
-
elsif imported_file.is_a?(String) && imported_file =~ /\.css$/
-
imported_file
-
end
-
end
-
-
1
private
-
-
1
def import
-
paths = @options[:load_paths]
-
-
if @options[:importer]
-
f = @options[:importer].find_relative(
-
@imported_filename, @options[:filename], options_for_importer)
-
return f if f
-
end
-
-
paths.each do |p|
-
if f = p.find(@imported_filename, options_for_importer)
-
return f
-
end
-
end
-
-
message = "File to import not found or unreadable: #{@imported_filename}.\n"
-
if paths.size == 1
-
message << "Load path: #{paths.first}"
-
else
-
message << "Load paths:\n " << paths.join("\n ")
-
end
-
raise SyntaxError.new(message)
-
rescue SyntaxError => e
-
raise SyntaxError.new(e.message, :line => self.line, :filename => @filename)
-
end
-
-
1
def options_for_importer
-
@options.merge(:_line => line)
-
end
-
end
-
end
-
end
-
1
module Sass::Tree
-
# A static node representing a `@media` rule.
-
# `@media` rules behave differently from other directives
-
# in that when they're nested within rules,
-
# they bubble up to top-level.
-
#
-
# @see Sass::Tree
-
1
class MediaNode < DirectiveNode
-
# TODO: parse and cache the query immediately if it has no dynamic elements
-
-
# The media query for this rule, interspersed with {Sass::Script::Node}s
-
# representing `#{}`-interpolation. Any adjacent strings will be merged
-
# together.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
1
attr_accessor :query
-
-
# The media query for this rule, without any unresolved interpolation. It's
-
# only set once {Tree::Node#perform} has been called.
-
#
-
# @return [Sass::Media::QueryList]
-
1
attr_accessor :resolved_query
-
-
# @see RuleNode#tabs
-
1
attr_accessor :tabs
-
-
# @see RuleNode#group_end
-
1
attr_accessor :group_end
-
-
# @param query [Array<String, Sass::Script::Node>] See \{#query}
-
1
def initialize(query)
-
@query = query
-
@tabs = 0
-
super('')
-
end
-
-
# @see DirectiveNode#value
-
1
def value; raise NotImplementedError; end
-
-
# @see DirectiveNode#name
-
1
def name; '@media'; end
-
-
# @see DirectiveNode#resolved_value
-
1
def resolved_value
-
@resolved_value ||= "@media #{resolved_query.to_css}"
-
end
-
-
# True when the directive has no visible children.
-
#
-
# @return [Boolean]
-
1
def invisible?
-
children.all? {|c| c.invisible?}
-
end
-
-
# @see Node#bubbles?
-
1
def bubbles?; true; end
-
end
-
end
-
1
module Sass
-
1
module Tree
-
# A dynamic node representing a mixin definition.
-
#
-
# @see Sass::Tree
-
1
class MixinDefNode < Node
-
# The mixin name.
-
# @return [String]
-
1
attr_reader :name
-
-
# The arguments for the mixin.
-
# Each element is a tuple containing the variable for argument
-
# and the parse tree for the default value of the argument.
-
#
-
# @return [Array<(Script::Node, Script::Node)>]
-
1
attr_accessor :args
-
-
# The splat argument for this mixin, if one exists.
-
#
-
# @return [Script::Node?]
-
1
attr_accessor :splat
-
-
# Whether the mixin uses `@content`. Set during the nesting check phase.
-
# @return [Boolean]
-
1
attr_accessor :has_content
-
-
# @param name [String] The mixin name
-
# @param args [Array<(Script::Node, Script::Node)>] See \{#args}
-
# @param splat [Script::Node] See \{#splat}
-
1
def initialize(name, args, splat)
-
@name = name
-
@args = args
-
@splat = splat
-
super()
-
end
-
end
-
end
-
end
-
1
require 'sass/tree/node'
-
-
1
module Sass::Tree
-
# A static node representing a mixin include.
-
# When in a static tree, the sole purpose is to wrap exceptions
-
# to add the mixin to the backtrace.
-
#
-
# @see Sass::Tree
-
1
class MixinNode < Node
-
# The name of the mixin.
-
# @return [String]
-
1
attr_reader :name
-
-
# The arguments to the mixin.
-
# @return [Array<Script::Node>]
-
1
attr_accessor :args
-
-
# A hash from keyword argument names to values.
-
# @return [{String => Script::Node}]
-
1
attr_accessor :keywords
-
-
# The splat argument for this mixin, if one exists.
-
#
-
# @return [Script::Node?]
-
1
attr_accessor :splat
-
-
# @param name [String] The name of the mixin
-
# @param args [Array<Script::Node>] See \{#args}
-
# @param splat [Script::Node] See \{#splat}
-
# @param keywords [{String => Script::Node}] See \{#keywords}
-
1
def initialize(name, args, keywords, splat)
-
@name = name
-
@args = args
-
@keywords = keywords
-
@splat = splat
-
super()
-
end
-
end
-
end
-
1
module Sass
-
# A namespace for nodes in the Sass parse tree.
-
#
-
# The Sass parse tree has three states: dynamic, static Sass, and static CSS.
-
#
-
# When it's first parsed, a Sass document is in the dynamic state.
-
# It has nodes for mixin definitions and `@for` loops and so forth,
-
# in addition to nodes for CSS rules and properties.
-
# Nodes that only appear in this state are called **dynamic nodes**.
-
#
-
# {Tree::Visitors::Perform} creates a static Sass tree, which is different.
-
# It still has nodes for CSS rules and properties
-
# but it doesn't have any dynamic-generation-related nodes.
-
# The nodes in this state are in the same structure as the Sass document:
-
# rules and properties are nested beneath one another.
-
# Nodes that can be in this state or in the dynamic state
-
# are called **static nodes**; nodes that can only be in this state
-
# are called **solely static nodes**.
-
#
-
# {Tree::Visitors::Cssize} is then used to create a static CSS tree.
-
# This is like a static Sass tree,
-
# but the structure exactly mirrors that of the generated CSS.
-
# Rules and properties can't be nested beneath one another in this state.
-
#
-
# Finally, {Tree::Visitors::ToCss} can be called on a static CSS tree
-
# to get the actual CSS code as a string.
-
1
module Tree
-
# The abstract superclass of all parse-tree nodes.
-
1
class Node
-
1
include Enumerable
-
-
# The child nodes of this node.
-
#
-
# @return [Array<Tree::Node>]
-
1
attr_accessor :children
-
-
# Whether or not this node has child nodes.
-
# This may be true even when \{#children} is empty,
-
# in which case this node has an empty block (e.g. `{}`).
-
#
-
# @return [Boolean]
-
1
attr_accessor :has_children
-
-
# The line of the document on which this node appeared.
-
#
-
# @return [Fixnum]
-
1
attr_accessor :line
-
-
# The name of the document on which this node appeared.
-
#
-
# @return [String]
-
1
attr_writer :filename
-
-
# The options hash for the node.
-
# See {file:SASS_REFERENCE.md#sass_options the Sass options documentation}.
-
#
-
# @return [{Symbol => Object}]
-
1
attr_reader :options
-
-
1
def initialize
-
@children = []
-
end
-
-
# Sets the options hash for the node and all its children.
-
#
-
# @param options [{Symbol => Object}] The options
-
# @see #options
-
1
def options=(options)
-
Sass::Tree::Visitors::SetOptions.visit(self, options)
-
end
-
-
# @private
-
1
def children=(children)
-
self.has_children ||= !children.empty?
-
@children = children
-
end
-
-
# The name of the document on which this node appeared.
-
#
-
# @return [String]
-
1
def filename
-
@filename || (@options && @options[:filename])
-
end
-
-
# Appends a child to the node.
-
#
-
# @param child [Tree::Node, Array<Tree::Node>] The child node or nodes
-
# @raise [Sass::SyntaxError] if `child` is invalid
-
1
def <<(child)
-
return if child.nil?
-
if child.is_a?(Array)
-
child.each {|c| self << c}
-
else
-
self.has_children = true
-
@children << child
-
end
-
end
-
-
# Compares this node and another object (only other {Tree::Node}s will be equal).
-
# This does a structural comparison;
-
# if the contents of the nodes and all the child nodes are equivalent,
-
# then the nodes are as well.
-
#
-
# Only static nodes need to override this.
-
#
-
# @param other [Object] The object to compare with
-
# @return [Boolean] Whether or not this node and the other object
-
# are the same
-
# @see Sass::Tree
-
1
def ==(other)
-
self.class == other.class && other.children == children
-
end
-
-
# True if \{#to\_s} will return `nil`;
-
# that is, if the node shouldn't be rendered.
-
# Should only be called in a static tree.
-
#
-
# @return [Boolean]
-
1
def invisible?; false; end
-
-
# The output style. See {file:SASS_REFERENCE.md#sass_options the Sass options documentation}.
-
#
-
# @return [Symbol]
-
1
def style
-
@options[:style]
-
end
-
-
# Computes the CSS corresponding to this static CSS tree.
-
#
-
# @return [String, nil] The resulting CSS
-
# @see Sass::Tree
-
1
def to_s
-
Sass::Tree::Visitors::ToCss.visit(self)
-
end
-
-
# Returns a representation of the node for debugging purposes.
-
#
-
# @return [String]
-
1
def inspect
-
return self.class.to_s unless has_children
-
"(#{self.class} #{children.map {|c| c.inspect}.join(' ')})"
-
end
-
-
# Iterates through each node in the tree rooted at this node
-
# in a pre-order walk.
-
#
-
# @yield node
-
# @yieldparam node [Node] a node in the tree
-
1
def each
-
yield self
-
children.each {|c| c.each {|n| yield n}}
-
end
-
-
# Converts a node to Sass code that will generate it.
-
#
-
# @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize})
-
# @return [String] The Sass code corresponding to the node
-
1
def to_sass(options = {})
-
Sass::Tree::Visitors::Convert.visit(self, options, :sass)
-
end
-
-
# Converts a node to SCSS code that will generate it.
-
#
-
# @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize})
-
# @return [String] The Sass code corresponding to the node
-
1
def to_scss(options = {})
-
Sass::Tree::Visitors::Convert.visit(self, options, :scss)
-
end
-
-
# Return a deep clone of this node.
-
# The child nodes are cloned, but options are not.
-
#
-
# @return [Node]
-
1
def deep_copy
-
Sass::Tree::Visitors::DeepCopy.visit(self)
-
end
-
-
# Whether or not this node bubbles up through RuleNodes.
-
#
-
# @return [Boolean]
-
1
def bubbles?
-
false
-
end
-
-
1
protected
-
-
# @see Sass::Shared.balance
-
# @raise [Sass::SyntaxError] if the brackets aren't balanced
-
1
def balance(*args)
-
res = Sass::Shared.balance(*args)
-
return res if res
-
raise Sass::SyntaxError.new("Unbalanced brackets.", :line => line)
-
end
-
end
-
end
-
end
-
1
module Sass::Tree
-
# A static node reprenting a CSS property.
-
#
-
# @see Sass::Tree
-
1
class PropNode < Node
-
# The name of the property,
-
# interspersed with {Sass::Script::Node}s
-
# representing `#{}`-interpolation.
-
# Any adjacent strings will be merged together.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
1
attr_accessor :name
-
-
# The name of the property
-
# after any interpolated SassScript has been resolved.
-
# Only set once \{Tree::Visitors::Perform} has been run.
-
#
-
# @return [String]
-
1
attr_accessor :resolved_name
-
-
# The value of the property.
-
#
-
# @return [Sass::Script::Node]
-
1
attr_accessor :value
-
-
# The value of the property
-
# after any interpolated SassScript has been resolved.
-
# Only set once \{Tree::Visitors::Perform} has been run.
-
#
-
# @return [String]
-
1
attr_accessor :resolved_value
-
-
# How deep this property is indented
-
# relative to a normal property.
-
# This is only greater than 0 in the case that:
-
#
-
# * This node is in a CSS tree
-
# * The style is :nested
-
# * This is a child property of another property
-
# * The parent property has a value, and thus will be rendered
-
#
-
# @return [Fixnum]
-
1
attr_accessor :tabs
-
-
# @param name [Array<String, Sass::Script::Node>] See \{#name}
-
# @param value [Sass::Script::Node] See \{#value}
-
# @param prop_syntax [Symbol] `:new` if this property uses `a: b`-style syntax,
-
# `:old` if it uses `:a b`-style syntax
-
1
def initialize(name, value, prop_syntax)
-
@name = Sass::Util.strip_string_array(
-
Sass::Util.merge_adjacent_strings(name))
-
@value = value
-
@tabs = 0
-
@prop_syntax = prop_syntax
-
super()
-
end
-
-
# Compares the names and values of two properties.
-
#
-
# @param other [Object] The object to compare with
-
# @return [Boolean] Whether or not this node and the other object
-
# are the same
-
1
def ==(other)
-
self.class == other.class && name == other.name && value == other.value && super
-
end
-
-
# Returns a appropriate message indicating how to escape pseudo-class selectors.
-
# This only applies for old-style properties with no value,
-
# so returns the empty string if this is new-style.
-
#
-
# @return [String] The message
-
1
def pseudo_class_selector_message
-
return "" if @prop_syntax == :new || !value.is_a?(Sass::Script::String) || !value.value.empty?
-
"\nIf #{declaration.dump} should be a selector, use \"\\#{declaration}\" instead."
-
end
-
-
# Computes the Sass or SCSS code for the variable declaration.
-
# This is like \{#to\_scss} or \{#to\_sass},
-
# except it doesn't print any child properties or a trailing semicolon.
-
#
-
# @param opts [{Symbol => Object}] The options hash for the tree.
-
# @param fmt [Symbol] `:scss` or `:sass`.
-
1
def declaration(opts = {:old => @prop_syntax == :old}, fmt = :sass)
-
name = self.name.map {|n| n.is_a?(String) ? n : "\#{#{n.to_sass(opts)}}"}.join
-
if name[0] == ?:
-
raise Sass::SyntaxError.new("The \"#{name}: #{self.class.val_to_sass(value, opts)}\" hack is not allowed in the Sass indented syntax")
-
end
-
-
old = opts[:old] && fmt == :sass
-
initial = old ? ':' : ''
-
mid = old ? '' : ':'
-
"#{initial}#{name}#{mid} #{self.class.val_to_sass(value, opts)}".rstrip
-
end
-
-
# A property node is invisible if its value is empty.
-
#
-
# @return [Boolean]
-
1
def invisible?
-
resolved_value.empty?
-
end
-
-
1
private
-
-
1
def check!
-
if @options[:property_syntax] && @options[:property_syntax] != @prop_syntax
-
raise Sass::SyntaxError.new(
-
"Illegal property syntax: can't use #{@prop_syntax} syntax when :property_syntax => #{@options[:property_syntax].inspect} is set.")
-
end
-
end
-
-
1
class << self
-
# @private
-
1
def val_to_sass(value, opts)
-
val_to_sass_comma(value, opts).to_sass(opts)
-
end
-
-
1
private
-
-
1
def val_to_sass_comma(node, opts)
-
return node unless node.is_a?(Sass::Script::Operation)
-
return val_to_sass_concat(node, opts) unless node.operator == :comma
-
-
Sass::Script::Operation.new(
-
val_to_sass_concat(node.operand1, opts),
-
val_to_sass_comma(node.operand2, opts),
-
node.operator)
-
end
-
-
1
def val_to_sass_concat(node, opts)
-
return node unless node.is_a?(Sass::Script::Operation)
-
return val_to_sass_div(node, opts) unless node.operator == :space
-
-
Sass::Script::Operation.new(
-
val_to_sass_div(node.operand1, opts),
-
val_to_sass_concat(node.operand2, opts),
-
node.operator)
-
end
-
-
1
def val_to_sass_div(node, opts)
-
unless node.is_a?(Sass::Script::Operation) && node.operator == :div &&
-
node.operand1.is_a?(Sass::Script::Number) &&
-
node.operand2.is_a?(Sass::Script::Number) &&
-
(!node.operand1.original || !node.operand2.original)
-
return node
-
end
-
-
Sass::Script::String.new("(#{node.to_sass(opts)})")
-
end
-
-
end
-
end
-
end
-
1
module Sass
-
1
module Tree
-
# A dynamic node representing returning from a function.
-
#
-
# @see Sass::Tree
-
1
class ReturnNode < Node
-
# The expression to return.
-
# @type [Script::Node]
-
1
attr_accessor :expr
-
-
# @param expr [Script::Node] The expression to return
-
1
def initialize(expr)
-
@expr = expr
-
super()
-
end
-
end
-
end
-
end
-
1
module Sass
-
1
module Tree
-
# A static node that is the root node of the Sass document.
-
1
class RootNode < Node
-
# The Sass template from which this node was created
-
#
-
# @param template [String]
-
1
attr_reader :template
-
-
# @param template [String] The Sass template from which this node was created
-
1
def initialize(template)
-
super()
-
@template = template
-
end
-
-
# Runs the dynamic Sass code *and* computes the CSS for the tree.
-
# @see #to_s
-
1
def render
-
Visitors::CheckNesting.visit(self)
-
result = Visitors::Perform.visit(self)
-
Visitors::CheckNesting.visit(result) # Check again to validate mixins
-
result, extends = Visitors::Cssize.visit(result)
-
Visitors::Extend.visit(result, extends)
-
result.to_s
-
end
-
end
-
end
-
end
-
1
require 'pathname'
-
1
require 'uri'
-
-
1
module Sass::Tree
-
# A static node reprenting a CSS rule.
-
#
-
# @see Sass::Tree
-
1
class RuleNode < Node
-
# The character used to include the parent selector
-
1
PARENT = '&'
-
-
# The CSS selector for this rule,
-
# interspersed with {Sass::Script::Node}s
-
# representing `#{}`-interpolation.
-
# Any adjacent strings will be merged together.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
1
attr_accessor :rule
-
-
# The CSS selector for this rule,
-
# without any unresolved interpolation
-
# but with parent references still intact.
-
# It's only set once {Tree::Node#perform} has been called.
-
#
-
# @return [Selector::CommaSequence]
-
1
attr_accessor :parsed_rules
-
-
# The CSS selector for this rule,
-
# without any unresolved interpolation or parent references.
-
# It's only set once {Tree::Visitors::Cssize} has been run.
-
#
-
# @return [Selector::CommaSequence]
-
1
attr_accessor :resolved_rules
-
-
# How deep this rule is indented
-
# relative to a base-level rule.
-
# This is only greater than 0 in the case that:
-
#
-
# * This node is in a CSS tree
-
# * The style is :nested
-
# * This is a child rule of another rule
-
# * The parent rule has properties, and thus will be rendered
-
#
-
# @return [Fixnum]
-
1
attr_accessor :tabs
-
-
# Whether or not this rule is the last rule in a nested group.
-
# This is only set in a CSS tree.
-
#
-
# @return [Boolean]
-
1
attr_accessor :group_end
-
-
# The stack trace.
-
# This is only readable in a CSS tree as it is written during the perform step
-
# and only when the :trace_selectors option is set.
-
#
-
# @return [Array<String>]
-
1
attr_accessor :stack_trace
-
-
# @param rule [Array<String, Sass::Script::Node>]
-
# The CSS rule. See \{#rule}
-
1
def initialize(rule)
-
merged = Sass::Util.merge_adjacent_strings(rule)
-
@rule = Sass::Util.strip_string_array(merged)
-
@tabs = 0
-
try_to_parse_non_interpolated_rules
-
super()
-
end
-
-
# If we've precached the parsed selector, set the line on it, too.
-
1
def line=(line)
-
@parsed_rules.line = line if @parsed_rules
-
super
-
end
-
-
# If we've precached the parsed selector, set the filename on it, too.
-
1
def filename=(filename)
-
@parsed_rules.filename = filename if @parsed_rules
-
super
-
end
-
-
# Compares the contents of two rules.
-
#
-
# @param other [Object] The object to compare with
-
# @return [Boolean] Whether or not this node and the other object
-
# are the same
-
1
def ==(other)
-
self.class == other.class && rule == other.rule && super
-
end
-
-
# Adds another {RuleNode}'s rules to this one's.
-
#
-
# @param node [RuleNode] The other node
-
1
def add_rules(node)
-
@rule = Sass::Util.strip_string_array(
-
Sass::Util.merge_adjacent_strings(@rule + ["\n"] + node.rule))
-
try_to_parse_non_interpolated_rules
-
end
-
-
# @return [Boolean] Whether or not this rule is continued on the next line
-
1
def continued?
-
last = @rule.last
-
last.is_a?(String) && last[-1] == ?,
-
end
-
-
# A hash that will be associated with this rule in the CSS document
-
# if the {file:SASS_REFERENCE.md#debug_info-option `:debug_info` option} is enabled.
-
# This data is used by e.g. [the FireSass Firebug extension](https://addons.mozilla.org/en-US/firefox/addon/103988).
-
#
-
# @return [{#to_s => #to_s}]
-
1
def debug_info
-
{:filename => filename && ("file://" + URI.escape(File.expand_path(filename))),
-
:line => self.line}
-
end
-
-
# A rule node is invisible if it has only placeholder selectors.
-
1
def invisible?
-
resolved_rules.members.all? {|seq| seq.has_placeholder?}
-
end
-
-
1
private
-
-
1
def try_to_parse_non_interpolated_rules
-
if @rule.all? {|t| t.kind_of?(String)}
-
# We don't use real filename/line info because we don't have it yet.
-
# When we get it, we'll set it on the parsed rules if possible.
-
parser = Sass::SCSS::StaticParser.new(@rule.join.strip, '', 1)
-
@parsed_rules = parser.parse_selector rescue nil
-
end
-
end
-
end
-
end
-
1
module Sass::Tree
-
# A static node representing a `@supports` rule.
-
# `@supports` rules behave differently from other directives
-
# in that when they're nested within rules,
-
# they bubble up to top-level.
-
#
-
# @see Sass::Tree
-
1
class SupportsNode < DirectiveNode
-
# The name, which may include a browser prefix.
-
#
-
# @return [String]
-
1
attr_accessor :name
-
-
# The supports condition.
-
#
-
# @return [Sass::Supports::Condition]
-
1
attr_accessor :condition
-
-
# @see RuleNode#tabs
-
1
attr_accessor :tabs
-
-
# @see RuleNode#group_end
-
1
attr_accessor :group_end
-
-
# @param condition [Sass::Supports::Condition] See \{#condition}
-
1
def initialize(name, condition)
-
@name = name
-
@condition = condition
-
@tabs = 0
-
super('')
-
end
-
-
# @see DirectiveNode#value
-
1
def value; raise NotImplementedError; end
-
-
# @see DirectiveNode#resolved_value
-
1
def resolved_value
-
@resolved_value ||= "@#{name} #{condition.to_css}"
-
end
-
-
# True when the directive has no visible children.
-
#
-
# @return [Boolean]
-
1
def invisible?
-
children.all? {|c| c.invisible?}
-
end
-
-
# @see Node#bubbles?
-
1
def bubbles?; true; end
-
end
-
end
-
1
require 'sass/tree/node'
-
-
1
module Sass::Tree
-
# A solely static node left over after a mixin include or @content has been performed.
-
# Its sole purpose is to wrap exceptions to add to the backtrace.
-
#
-
# @see Sass::Tree
-
1
class TraceNode < Node
-
# The name of the trace entry to add.
-
# @return [String]
-
1
attr_reader :name
-
-
# @param name [String] The name of the trace entry to add.
-
1
def initialize(name)
-
@name = name
-
self.has_children = true
-
super()
-
end
-
-
# Initializes this node from an existing node.
-
# @param name [String] The name of the trace entry to add.
-
# @param mixin [Node] The node to copy information from.
-
# @return [TraceNode]
-
1
def self.from_node(name, node)
-
trace = new(name)
-
trace.line = node.line
-
trace.filename = node.filename
-
trace.options = node.options
-
trace
-
end
-
end
-
end
-
1
module Sass
-
1
module Tree
-
# A dynamic node representing a variable definition.
-
#
-
# @see Sass::Tree
-
1
class VariableNode < Node
-
# The name of the variable.
-
# @return [String]
-
1
attr_reader :name
-
-
# The parse tree for the variable value.
-
# @return [Script::Node]
-
1
attr_accessor :expr
-
-
# Whether this is a guarded variable assignment (`!default`).
-
# @return [Boolean]
-
1
attr_reader :guarded
-
-
# @param name [String] The name of the variable
-
# @param expr [Script::Node] See \{#expr}
-
# @param guarded [Boolean] See \{#guarded}
-
1
def initialize(name, expr, guarded)
-
@name = name
-
@expr = expr
-
@guarded = guarded
-
super()
-
end
-
end
-
end
-
end
-
# Visitors are used to traverse the Sass parse tree.
-
# Visitors should extend {Visitors::Base},
-
# which provides a small amount of scaffolding for traversal.
-
1
module Sass::Tree::Visitors
-
# The abstract base class for Sass visitors.
-
# Visitors should extend this class,
-
# then implement `visit_*` methods for each node they care about
-
# (e.g. `visit_rule` for {RuleNode} or `visit_for` for {ForNode}).
-
# These methods take the node in question as argument.
-
# They may `yield` to visit the child nodes of the current node.
-
#
-
# *Note*: due to the unusual nature of {Sass::Tree::IfNode},
-
# special care must be taken to ensure that it is properly handled.
-
# In particular, there is no built-in scaffolding
-
# for dealing with the return value of `@else` nodes.
-
#
-
# @abstract
-
1
class Base
-
# Runs the visitor on a tree.
-
#
-
# @param root [Tree::Node] The root node of the Sass tree.
-
# @return [Object] The return value of \{#visit} for the root node.
-
1
def self.visit(root)
-
new.send(:visit, root)
-
end
-
-
1
protected
-
-
# Runs the visitor on the given node.
-
# This can be overridden by subclasses that need to do something for each node.
-
#
-
# @param node [Tree::Node] The node to visit.
-
# @return [Object] The return value of the `visit_*` method for this node.
-
1
def visit(node)
-
method = "visit_#{node_name node}"
-
if self.respond_to?(method, true)
-
self.send(method, node) {visit_children(node)}
-
else
-
visit_children(node)
-
end
-
end
-
-
# Visit the child nodes for a given node.
-
# This can be overridden by subclasses that need to do something
-
# with the child nodes' return values.
-
#
-
# This method is run when `visit_*` methods `yield`,
-
# and its return value is returned from the `yield`.
-
#
-
# @param parent [Tree::Node] The parent node of the children to visit.
-
# @return [Array<Object>] The return values of the `visit_*` methods for the children.
-
1
def visit_children(parent)
-
parent.children.map {|c| visit(c)}
-
end
-
-
1
NODE_NAME_RE = /.*::(.*?)Node$/
-
-
# Returns the name of a node as used in the `visit_*` method.
-
#
-
# @param [Tree::Node] node The node.
-
# @return [String] The name.
-
1
def node_name(node)
-
@@node_names ||= {}
-
@@node_names[node.class.name] ||= node.class.name.gsub(NODE_NAME_RE, '\\1').downcase
-
end
-
-
# `yield`s, then runs the visitor on the `@else` clause if the node has one.
-
# This exists to ensure that the contents of the `@else` clause get visited.
-
1
def visit_if(node)
-
yield
-
visit(node.else) if node.else
-
node
-
end
-
end
-
end
-
# A visitor for checking that all nodes are properly nested.
-
1
class Sass::Tree::Visitors::CheckNesting < Sass::Tree::Visitors::Base
-
1
protected
-
-
1
def initialize
-
@parents = []
-
end
-
-
1
def visit(node)
-
if error = @parent && (
-
try_send("invalid_#{node_name @parent}_child?", @parent, node) ||
-
try_send("invalid_#{node_name node}_parent?", @parent, node))
-
raise Sass::SyntaxError.new(error)
-
end
-
super
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
1
CONTROL_NODES = [Sass::Tree::EachNode, Sass::Tree::ForNode, Sass::Tree::IfNode,
-
Sass::Tree::WhileNode, Sass::Tree::TraceNode]
-
1
SCRIPT_NODES = [Sass::Tree::ImportNode] + CONTROL_NODES
-
1
def visit_children(parent)
-
old_parent = @parent
-
@parent = parent unless is_any_of?(parent, SCRIPT_NODES) ||
-
(parent.bubbles? && !old_parent.is_a?(Sass::Tree::RootNode))
-
@parents.push parent
-
super
-
ensure
-
@parent = old_parent
-
@parents.pop
-
end
-
-
1
def visit_root(node)
-
yield
-
rescue Sass::SyntaxError => e
-
e.sass_template ||= node.template
-
raise e
-
end
-
-
1
def visit_import(node)
-
yield
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.children.first.filename)
-
e.add_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
1
def visit_mixindef(node)
-
@current_mixin_def, old_mixin_def = node, @current_mixin_def
-
yield
-
ensure
-
@current_mixin_def = old_mixin_def
-
end
-
-
1
def invalid_content_parent?(parent, child)
-
if @current_mixin_def
-
@current_mixin_def.has_content = true
-
nil
-
else
-
"@content may only be used within a mixin."
-
end
-
end
-
-
1
def invalid_charset_parent?(parent, child)
-
"@charset may only be used at the root of a document." unless parent.is_a?(Sass::Tree::RootNode)
-
end
-
-
1
VALID_EXTEND_PARENTS = [Sass::Tree::RuleNode, Sass::Tree::MixinDefNode, Sass::Tree::MixinNode]
-
1
def invalid_extend_parent?(parent, child)
-
unless is_any_of?(parent, VALID_EXTEND_PARENTS)
-
return "Extend directives may only be used within rules."
-
end
-
end
-
-
1
INVALID_IMPORT_PARENTS = CONTROL_NODES +
-
[Sass::Tree::MixinDefNode, Sass::Tree::MixinNode]
-
1
def invalid_import_parent?(parent, child)
-
unless (@parents.map {|p| p.class} & INVALID_IMPORT_PARENTS).empty?
-
return "Import directives may not be used within control directives or mixins."
-
end
-
return if parent.is_a?(Sass::Tree::RootNode)
-
return "CSS import directives may only be used at the root of a document." if child.css_import?
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => child.imported_file.options[:filename])
-
e.add_backtrace(:filename => child.filename, :line => child.line)
-
raise e
-
end
-
-
1
def invalid_mixindef_parent?(parent, child)
-
unless (@parents.map {|p| p.class} & INVALID_IMPORT_PARENTS).empty?
-
return "Mixins may not be defined within control directives or other mixins."
-
end
-
end
-
-
1
def invalid_function_parent?(parent, child)
-
unless (@parents.map {|p| p.class} & INVALID_IMPORT_PARENTS).empty?
-
return "Functions may not be defined within control directives or other mixins."
-
end
-
end
-
-
1
VALID_FUNCTION_CHILDREN = [
-
Sass::Tree::CommentNode, Sass::Tree::DebugNode, Sass::Tree::ReturnNode,
-
Sass::Tree::VariableNode, Sass::Tree::WarnNode
-
] + CONTROL_NODES
-
1
def invalid_function_child?(parent, child)
-
unless is_any_of?(child, VALID_FUNCTION_CHILDREN)
-
"Functions can only contain variable declarations and control directives."
-
end
-
end
-
-
1
VALID_PROP_CHILDREN = [Sass::Tree::CommentNode, Sass::Tree::PropNode, Sass::Tree::MixinNode] + CONTROL_NODES
-
1
def invalid_prop_child?(parent, child)
-
unless is_any_of?(child, VALID_PROP_CHILDREN)
-
"Illegal nesting: Only properties may be nested beneath properties."
-
end
-
end
-
-
1
VALID_PROP_PARENTS = [Sass::Tree::RuleNode, Sass::Tree::PropNode,
-
Sass::Tree::MixinDefNode, Sass::Tree::DirectiveNode,
-
Sass::Tree::MixinNode]
-
1
def invalid_prop_parent?(parent, child)
-
unless is_any_of?(parent, VALID_PROP_PARENTS)
-
"Properties are only allowed within rules, directives, mixin includes, or other properties." + child.pseudo_class_selector_message
-
end
-
end
-
-
1
def invalid_return_parent?(parent, child)
-
"@return may only be used within a function." unless parent.is_a?(Sass::Tree::FunctionNode)
-
end
-
-
1
private
-
-
1
def is_any_of?(val, classes)
-
for c in classes
-
return true if val.is_a?(c)
-
end
-
return false
-
end
-
-
1
def try_send(method, *args)
-
return unless respond_to?(method, true)
-
send(method, *args)
-
end
-
end
-
-
# A visitor for converting a Sass tree into a source string.
-
1
class Sass::Tree::Visitors::Convert < Sass::Tree::Visitors::Base
-
# Runs the visitor on a tree.
-
#
-
# @param root [Tree::Node] The root node of the Sass tree.
-
# @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize}).
-
# @param format [Symbol] `:sass` or `:scss`.
-
# @return [String] The Sass or SCSS source for the tree.
-
1
def self.visit(root, options, format)
-
new(options, format).send(:visit, root)
-
end
-
-
1
protected
-
-
1
def initialize(options, format)
-
@options = options
-
@format = format
-
@tabs = 0
-
# 2 spaces by default
-
@tab_chars = @options[:indent] || " "
-
end
-
-
1
def visit_children(parent)
-
@tabs += 1
-
return @format == :sass ? "\n" : " {}\n" if parent.children.empty?
-
(@format == :sass ? "\n" : " {\n") + super.join.rstrip + (@format == :sass ? "\n" : "\n#{ @tab_chars * (@tabs-1)}}\n")
-
ensure
-
@tabs -= 1
-
end
-
-
# Ensures proper spacing between top-level nodes.
-
1
def visit_root(node)
-
Sass::Util.enum_cons(node.children + [nil], 2).map do |child, nxt|
-
visit(child) +
-
if nxt &&
-
(child.is_a?(Sass::Tree::CommentNode) &&
-
child.line + child.lines + 1 == nxt.line) ||
-
(child.is_a?(Sass::Tree::ImportNode) && nxt.is_a?(Sass::Tree::ImportNode) &&
-
child.line + 1 == nxt.line) ||
-
(child.is_a?(Sass::Tree::VariableNode) && nxt.is_a?(Sass::Tree::VariableNode) &&
-
child.line + 1 == nxt.line)
-
""
-
else
-
"\n"
-
end
-
end.join.rstrip + "\n"
-
end
-
-
1
def visit_charset(node)
-
"#{tab_str}@charset \"#{node.name}\"#{semi}\n"
-
end
-
-
1
def visit_comment(node)
-
value = interp_to_src(node.value)
-
content = if @format == :sass
-
content = value.gsub(/\*\/$/, '').rstrip
-
if content =~ /\A[ \t]/
-
# Re-indent SCSS comments like this:
-
# /* foo
-
# bar
-
# baz */
-
content.gsub!(/^/, ' ')
-
content.sub!(/\A([ \t]*)\/\*/, '/*\1')
-
end
-
-
content =
-
unless content.include?("\n")
-
content
-
else
-
content.gsub!(/\n( \*|\/\/)/, "\n ")
-
spaces = content.scan(/\n( *)/).map {|s| s.first.size}.min
-
sep = node.type == :silent ? "\n//" : "\n *"
-
if spaces >= 2
-
content.gsub(/\n /, sep)
-
else
-
content.gsub(/\n#{' ' * spaces}/, sep)
-
end
-
end
-
-
content.gsub!(/\A\/\*/, '//') if node.type == :silent
-
content.gsub!(/^/, tab_str)
-
content.rstrip + "\n"
-
else
-
spaces = (@tab_chars * [@tabs - value[/^ */].size, 0].max)
-
content = if node.type == :silent
-
value.gsub(/^[\/ ]\*/, '//').gsub(/ *\*\/$/, '')
-
else
-
value
-
end.gsub(/^/, spaces) + "\n"
-
content
-
end
-
content
-
end
-
-
1
def visit_debug(node)
-
"#{tab_str}@debug #{node.expr.to_sass(@options)}#{semi}\n"
-
end
-
-
1
def visit_directive(node)
-
res = "#{tab_str}#{interp_to_src(node.value)}"
-
res.gsub!(/^@import \#\{(.*)\}([^}]*)$/, '@import \1\2');
-
return res + "#{semi}\n" unless node.has_children
-
res + yield + "\n"
-
end
-
-
1
def visit_each(node)
-
"#{tab_str}@each $#{dasherize(node.var)} in #{node.list.to_sass(@options)}#{yield}"
-
end
-
-
1
def visit_extend(node)
-
"#{tab_str}@extend #{selector_to_src(node.selector).lstrip}#{semi}#{" !optional" if node.optional?}\n"
-
end
-
-
1
def visit_for(node)
-
"#{tab_str}@for $#{dasherize(node.var)} from #{node.from.to_sass(@options)} " +
-
"#{node.exclusive ? "to" : "through"} #{node.to.to_sass(@options)}#{yield}"
-
end
-
-
1
def visit_function(node)
-
args = node.args.map do |v, d|
-
d ? "#{v.to_sass(@options)}: #{d.to_sass(@options)}" : v.to_sass(@options)
-
end.join(", ")
-
if node.splat
-
args << ", " unless node.args.empty?
-
args << node.splat.to_sass(@options) << "..."
-
end
-
-
"#{tab_str}@function #{dasherize(node.name)}(#{args})#{yield}"
-
end
-
-
1
def visit_if(node)
-
name =
-
if !@is_else; "if"
-
elsif node.expr; "else if"
-
else; "else"
-
end
-
@is_else = false
-
str = "#{tab_str}@#{name}"
-
str << " #{node.expr.to_sass(@options)}" if node.expr
-
str << yield
-
@is_else = true
-
str << visit(node.else) if node.else
-
str
-
ensure
-
@is_else = false
-
end
-
-
1
def visit_import(node)
-
quote = @format == :scss ? '"' : ''
-
"#{tab_str}@import #{quote}#{node.imported_filename}#{quote}#{semi}\n"
-
end
-
-
1
def visit_media(node)
-
"#{tab_str}@media #{media_interp_to_src(node.query)}#{yield}"
-
end
-
-
1
def visit_supports(node)
-
"#{tab_str}@#{node.name} #{node.condition.to_src(@options)}#{yield}"
-
end
-
-
1
def visit_cssimport(node)
-
if node.uri.is_a?(Sass::Script::Node)
-
str = "#{tab_str}@import #{node.uri.to_sass(@options)}"
-
else
-
str = "#{tab_str}@import #{node.uri}"
-
end
-
str << " #{interp_to_src(node.query)}" unless node.query.empty?
-
"#{str}#{semi}\n"
-
end
-
-
1
def visit_mixindef(node)
-
args =
-
if node.args.empty? && node.splat.nil?
-
""
-
else
-
str = '('
-
str << node.args.map do |v, d|
-
if d
-
"#{v.to_sass(@options)}: #{d.to_sass(@options)}"
-
else
-
v.to_sass(@options)
-
end
-
end.join(", ")
-
-
if node.splat
-
str << ", " unless node.args.empty?
-
str << node.splat.to_sass(@options) << '...'
-
end
-
-
str << ')'
-
end
-
-
"#{tab_str}#{@format == :sass ? '=' : '@mixin '}#{dasherize(node.name)}#{args}#{yield}"
-
end
-
-
1
def visit_mixin(node)
-
arg_to_sass = lambda do |arg|
-
sass = arg.to_sass(@options)
-
sass = "(#{sass})" if arg.is_a?(Sass::Script::List) && arg.separator == :comma
-
sass
-
end
-
-
unless node.args.empty? && node.keywords.empty? && node.splat.nil?
-
args = node.args.map(&arg_to_sass).join(", ")
-
keywords = Sass::Util.hash_to_a(node.keywords).
-
map {|k, v| "$#{dasherize(k)}: #{arg_to_sass[v]}"}.join(', ')
-
if node.splat
-
splat = (args.empty? && keywords.empty?) ? "" : ", "
-
splat = "#{splat}#{arg_to_sass[node.splat]}..."
-
end
-
arglist = "(#{args}#{', ' unless args.empty? || keywords.empty?}#{keywords}#{splat})"
-
end
-
"#{tab_str}#{@format == :sass ? '+' : '@include '}#{dasherize(node.name)}#{arglist}#{node.has_children ? yield : semi}\n"
-
end
-
-
1
def visit_content(node)
-
"#{tab_str}@content#{semi}\n"
-
end
-
-
1
def visit_prop(node)
-
res = tab_str + node.declaration(@options, @format)
-
return res + semi + "\n" if node.children.empty?
-
res + yield.rstrip + semi + "\n"
-
end
-
-
1
def visit_return(node)
-
"#{tab_str}@return #{node.expr.to_sass(@options)}#{semi}\n"
-
end
-
-
1
def visit_rule(node)
-
if @format == :sass
-
name = selector_to_sass(node.rule)
-
name = "\\" + name if name[0] == ?:
-
name.gsub(/^/, tab_str) + yield
-
elsif @format == :scss
-
name = selector_to_scss(node.rule)
-
res = name + yield
-
if node.children.last.is_a?(Sass::Tree::CommentNode) && node.children.last.type == :silent
-
res.slice!(-3..-1)
-
res << "\n" << tab_str << "}\n"
-
end
-
res
-
end
-
end
-
-
1
def visit_variable(node)
-
"#{tab_str}$#{dasherize(node.name)}: #{node.expr.to_sass(@options)}#{' !default' if node.guarded}#{semi}\n"
-
end
-
-
1
def visit_warn(node)
-
"#{tab_str}@warn #{node.expr.to_sass(@options)}#{semi}\n"
-
end
-
-
1
def visit_while(node)
-
"#{tab_str}@while #{node.expr.to_sass(@options)}#{yield}"
-
end
-
-
1
private
-
-
1
def interp_to_src(interp)
-
interp.map do |r|
-
next r if r.is_a?(String)
-
"\#{#{r.to_sass(@options)}}"
-
end.join
-
end
-
-
# Like interp_to_src, but removes the unnecessary `#{}` around the keys and
-
# values in media expressions.
-
1
def media_interp_to_src(interp)
-
Sass::Util.enum_with_index(interp).map do |r, i|
-
next r if r.is_a?(String)
-
before, after = interp[i-1], interp[i+1]
-
if before.is_a?(String) && after.is_a?(String) &&
-
((before[-1] == ?( && after[0] == ?:) ||
-
(before =~ /:\s*/ && after[0] == ?)))
-
r.to_sass(@options)
-
else
-
"\#{#{r.to_sass(@options)}}"
-
end
-
end.join
-
end
-
-
1
def selector_to_src(sel)
-
@format == :sass ? selector_to_sass(sel) : selector_to_scss(sel)
-
end
-
-
1
def selector_to_sass(sel)
-
sel.map do |r|
-
if r.is_a?(String)
-
r.gsub(/(,)?([ \t]*)\n\s*/) {$1 ? "#{$1}#{$2}\n" : " "}
-
else
-
"\#{#{r.to_sass(@options)}}"
-
end
-
end.join
-
end
-
-
1
def selector_to_scss(sel)
-
interp_to_src(sel).gsub(/^[ \t]*/, tab_str).gsub(/[ \t]*$/, '')
-
end
-
-
1
def semi
-
@format == :sass ? "" : ";"
-
end
-
-
1
def tab_str
-
@tab_chars * @tabs
-
end
-
-
1
def dasherize(s)
-
if @options[:dasherize]
-
s.gsub('_', '-')
-
else
-
s
-
end
-
end
-
end
-
# A visitor for converting a static Sass tree into a static CSS tree.
-
1
class Sass::Tree::Visitors::Cssize < Sass::Tree::Visitors::Base
-
# @param root [Tree::Node] The root node of the tree to visit.
-
# @return [(Tree::Node, Sass::Util::SubsetMap)] The resulting tree of static nodes
-
# *and* the extensions defined for this tree
-
1
def self.visit(root); super; end
-
-
1
protected
-
-
# Returns the immediate parent of the current node.
-
# @return [Tree::Node]
-
1
attr_reader :parent
-
-
1
def initialize
-
@parent_directives = []
-
@extends = Sass::Util::SubsetMap.new
-
end
-
-
# If an exception is raised, this adds proper metadata to the backtrace.
-
1
def visit(node)
-
super(node)
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
# Keeps track of the current parent node.
-
1
def visit_children(parent)
-
with_parent parent do
-
parent.children = super.flatten
-
parent
-
end
-
end
-
-
1
MERGEABLE_DIRECTIVES = [Sass::Tree::MediaNode]
-
-
# Runs a block of code with the current parent node
-
# replaced with the given node.
-
#
-
# @param parent [Tree::Node] The new parent for the duration of the block.
-
# @yield A block in which the parent is set to `parent`.
-
# @return [Object] The return value of the block.
-
1
def with_parent(parent)
-
if parent.is_a?(Sass::Tree::DirectiveNode)
-
if MERGEABLE_DIRECTIVES.any? {|klass| parent.is_a?(klass)}
-
old_parent_directive = @parent_directives.pop
-
end
-
@parent_directives.push parent
-
end
-
-
old_parent, @parent = @parent, parent
-
yield
-
ensure
-
@parent_directives.pop if parent.is_a?(Sass::Tree::DirectiveNode)
-
@parent_directives.push old_parent_directive if old_parent_directive
-
@parent = old_parent
-
end
-
-
# In Ruby 1.8, ensures that there's only one `@charset` directive
-
# and that it's at the top of the document.
-
#
-
# @return [(Tree::Node, Sass::Util::SubsetMap)] The resulting tree of static nodes
-
# *and* the extensions defined for this tree
-
1
def visit_root(node)
-
yield
-
-
if parent.nil?
-
# In Ruby 1.9 we can make all @charset nodes invisible
-
# and infer the final @charset from the encoding of the final string.
-
if Sass::Util.ruby1_8?
-
charset = node.children.find {|c| c.is_a?(Sass::Tree::CharsetNode)}
-
node.children.reject! {|c| c.is_a?(Sass::Tree::CharsetNode)}
-
node.children.unshift charset if charset
-
end
-
-
imports_to_move = []
-
import_limit = nil
-
i = -1
-
node.children.reject! do |n|
-
i += 1
-
if import_limit
-
next false unless n.is_a?(Sass::Tree::CssImportNode)
-
imports_to_move << n
-
next true
-
end
-
-
if !n.is_a?(Sass::Tree::CommentNode) &&
-
!n.is_a?(Sass::Tree::CharsetNode) &&
-
!n.is_a?(Sass::Tree::CssImportNode)
-
import_limit = i
-
end
-
-
false
-
end
-
-
if import_limit
-
node.children = node.children[0...import_limit] + imports_to_move +
-
node.children[import_limit..-1]
-
end
-
end
-
-
return node, @extends
-
rescue Sass::SyntaxError => e
-
e.sass_template ||= node.template
-
raise e
-
end
-
-
# A simple struct wrapping up information about a single `@extend` instance. A
-
# single [ExtendNode] can have multiple Extends if either the parent node or
-
# the extended selector is a comma sequence.
-
#
-
# @attr extender [Sass::Selector::Sequence]
-
# The selector of the CSS rule containing the `@extend`.
-
# @attr target [Array<Sass::Selector::Simple>] The selector being `@extend`ed.
-
# @attr node [Sass::Tree::ExtendNode] The node that produced this extend.
-
# @attr directives [Array<Sass::Tree::DirectiveNode>]
-
# The directives containing the `@extend`.
-
# @attr result [Symbol]
-
# The result of this extend. One of `:not_found` (the target doesn't exist
-
# in the document), `:failed_to_unify` (the target exists but cannot be
-
# unified with the extender), or `:succeeded`.
-
1
Extend = Struct.new(:extender, :target, :node, :directives, :result)
-
-
# Registers an extension in the `@extends` subset map.
-
1
def visit_extend(node)
-
node.resolved_selector.members.each do |seq|
-
if seq.members.size > 1
-
raise Sass::SyntaxError.new("Can't extend #{seq.to_a.join}: can't extend nested selectors")
-
end
-
-
sseq = seq.members.first
-
if !sseq.is_a?(Sass::Selector::SimpleSequence)
-
raise Sass::SyntaxError.new("Can't extend #{seq.to_a.join}: invalid selector")
-
elsif sseq.members.any? {|ss| ss.is_a?(Sass::Selector::Parent)}
-
raise Sass::SyntaxError.new("Can't extend #{seq.to_a.join}: can't extend parent selectors")
-
end
-
-
sel = sseq.members
-
parent.resolved_rules.members.each do |member|
-
if !member.members.last.is_a?(Sass::Selector::SimpleSequence)
-
raise Sass::SyntaxError.new("#{member} can't extend: invalid selector")
-
end
-
-
@extends[sel] = Extend.new(member, sel, node, @parent_directives.dup, :not_found)
-
end
-
end
-
-
[]
-
end
-
-
# Modifies exception backtraces to include the imported file.
-
1
def visit_import(node)
-
# Don't use #visit_children to avoid adding the import node to the list of parents.
-
node.children.map {|c| visit(c)}.flatten
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.children.first.filename)
-
e.add_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
# Bubbles the `@media` directive up through RuleNodes
-
# and merges it with other `@media` directives.
-
1
def visit_media(node)
-
yield unless bubble(node)
-
media = node.children.select {|c| c.is_a?(Sass::Tree::MediaNode)}
-
node.children.reject! {|c| c.is_a?(Sass::Tree::MediaNode)}
-
media = media.select {|n| n.resolved_query = n.resolved_query.merge(node.resolved_query)}
-
(node.children.empty? ? [] : [node]) + media
-
end
-
-
# Bubbles the `@supports` directive up through RuleNodes.
-
1
def visit_supports(node)
-
yield unless bubble(node)
-
node
-
end
-
-
# Asserts that all the traced children are valid in their new location.
-
1
def visit_trace(node)
-
# Don't use #visit_children to avoid adding the trace node to the list of parents.
-
node.children.map {|c| visit(c)}.flatten
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:mixin => node.name, :filename => node.filename, :line => node.line)
-
e.add_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
# Converts nested properties into flat properties
-
# and updates the indentation of the prop node based on the nesting level.
-
1
def visit_prop(node)
-
if parent.is_a?(Sass::Tree::PropNode)
-
node.resolved_name = "#{parent.resolved_name}-#{node.resolved_name}"
-
node.tabs = parent.tabs + (parent.resolved_value.empty? ? 0 : 1) if node.style == :nested
-
end
-
-
yield
-
-
result = node.children.dup
-
if !node.resolved_value.empty? || node.children.empty?
-
node.send(:check!)
-
result.unshift(node)
-
end
-
-
result
-
end
-
-
# Resolves parent references and nested selectors,
-
# and updates the indentation of the rule node based on the nesting level.
-
1
def visit_rule(node)
-
parent_resolved_rules = parent.is_a?(Sass::Tree::RuleNode) ? parent.resolved_rules : nil
-
# It's possible for resolved_rules to be set if we've duplicated this node during @media bubbling
-
node.resolved_rules ||= node.parsed_rules.resolve_parent_refs(parent_resolved_rules)
-
-
yield
-
-
rules = node.children.select {|c| c.is_a?(Sass::Tree::RuleNode) || c.bubbles?}
-
props = node.children.reject {|c| c.is_a?(Sass::Tree::RuleNode) || c.bubbles? || c.invisible?}
-
-
unless props.empty?
-
node.children = props
-
rules.each {|r| r.tabs += 1} if node.style == :nested
-
rules.unshift(node)
-
end
-
-
rules.last.group_end = true unless parent.is_a?(Sass::Tree::RuleNode) || rules.empty?
-
-
rules
-
end
-
-
1
private
-
-
1
def bubble(node)
-
return unless parent.is_a?(Sass::Tree::RuleNode)
-
new_rule = parent.dup
-
new_rule.children = node.children
-
node.children = with_parent(node) {Array(visit(new_rule))}
-
# If the last child is actually the end of the group,
-
# the parent's cssize will set it properly
-
node.children.last.group_end = false unless node.children.empty?
-
true
-
end
-
end
-
# A visitor for performing selector inheritance on a static CSS tree.
-
#
-
# Destructively modifies the tree.
-
1
class Sass::Tree::Visitors::Extend < Sass::Tree::Visitors::Base
-
# Performs the given extensions on the static CSS tree based in `root`, then
-
# validates that all extends matched some selector.
-
#
-
# @param root [Tree::Node] The root node of the tree to visit.
-
# @param extends [Sass::Util::SubsetMap{Selector::Simple =>
-
# Sass::Tree::Visitors::Cssize::Extend}]
-
# The extensions to perform on this tree.
-
# @return [Object] The return value of \{#visit} for the root node.
-
1
def self.visit(root, extends)
-
return if extends.empty?
-
new(extends).send(:visit, root)
-
check_extends_fired! extends
-
end
-
-
1
protected
-
-
1
def initialize(extends)
-
@parent_directives = []
-
@extends = extends
-
end
-
-
# If an exception is raised, this adds proper metadata to the backtrace.
-
1
def visit(node)
-
super(node)
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
# Keeps track of the current parent directives.
-
1
def visit_children(parent)
-
@parent_directives.push parent if parent.is_a?(Sass::Tree::DirectiveNode)
-
super
-
ensure
-
@parent_directives.pop if parent.is_a?(Sass::Tree::DirectiveNode)
-
end
-
-
# Applies the extend to a single rule's selector.
-
1
def visit_rule(node)
-
node.resolved_rules = node.resolved_rules.do_extend(@extends, @parent_directives)
-
end
-
-
1
private
-
-
1
def self.check_extends_fired!(extends)
-
extends.each_value do |ex|
-
next if ex.result == :succeeded || ex.node.optional?
-
warn = "\"#{ex.extender}\" failed to @extend \"#{ex.target.join}\"."
-
reason =
-
if ex.result == :not_found
-
"The selector \"#{ex.target.join}\" was not found."
-
else
-
"No selectors matching \"#{ex.target.join}\" could be unified with \"#{ex.extender}\"."
-
end
-
-
Sass::Util.sass_warn <<WARN
-
WARNING on line #{ex.node.line}#{" of #{ex.node.filename}" if ex.node.filename}: #{warn}
-
#{reason}
-
This will be an error in future releases of Sass.
-
Use "@extend #{ex.target.join} !optional" if the extend should be able to fail.
-
WARN
-
end
-
end
-
end
-
# A visitor for converting a dynamic Sass tree into a static Sass tree.
-
1
class Sass::Tree::Visitors::Perform < Sass::Tree::Visitors::Base
-
# @param root [Tree::Node] The root node of the tree to visit.
-
# @param environment [Sass::Environment] The lexical environment.
-
# @return [Tree::Node] The resulting tree of static nodes.
-
1
def self.visit(root, environment = Sass::Environment.new)
-
new(environment).send(:visit, root)
-
end
-
-
# @api private
-
1
def self.perform_arguments(callable, args, keywords, splat)
-
desc = "#{callable.type.capitalize} #{callable.name}"
-
downcase_desc = "#{callable.type} #{callable.name}"
-
-
begin
-
unless keywords.empty?
-
unknown_args = Sass::Util.array_minus(keywords.keys,
-
callable.args.map {|var| var.first.underscored_name})
-
if callable.splat && unknown_args.include?(callable.splat.underscored_name)
-
raise Sass::SyntaxError.new("Argument $#{callable.splat.name} of #{downcase_desc} cannot be used as a named argument.")
-
elsif unknown_args.any?
-
description = unknown_args.length > 1 ? 'the following arguments:' : 'an argument named'
-
raise Sass::SyntaxError.new("#{desc} doesn't have #{description} #{unknown_args.map {|name| "$#{name}"}.join ', '}.")
-
end
-
end
-
rescue Sass::SyntaxError => keyword_exception
-
end
-
-
# If there's no splat, raise the keyword exception immediately. The actual
-
# raising happens in the ensure clause at the end of this function.
-
return if keyword_exception && !callable.splat
-
-
if args.size > callable.args.size && !callable.splat
-
takes = callable.args.size
-
passed = args.size
-
raise Sass::SyntaxError.new(
-
"#{desc} takes #{takes} argument#{'s' unless takes == 1} " +
-
"but #{passed} #{passed == 1 ? 'was' : 'were'} passed.")
-
end
-
-
splat_sep = :comma
-
if splat
-
args += splat.to_a
-
splat_sep = splat.separator if splat.is_a?(Sass::Script::List)
-
# If the splat argument exists, there won't be any keywords passed in
-
# manually, so we can safely overwrite rather than merge here.
-
keywords = splat.keywords if splat.is_a?(Sass::Script::ArgList)
-
end
-
-
keywords = keywords.dup
-
env = Sass::Environment.new(callable.environment)
-
callable.args.zip(args[0...callable.args.length]) do |(var, default), value|
-
if value && keywords.include?(var.underscored_name)
-
raise Sass::SyntaxError.new("#{desc} was passed argument $#{var.name} both by position and by name.")
-
end
-
-
value ||= keywords.delete(var.underscored_name)
-
value ||= default && default.perform(env)
-
raise Sass::SyntaxError.new("#{desc} is missing argument #{var.inspect}.") unless value
-
env.set_local_var(var.name, value)
-
end
-
-
if callable.splat
-
rest = args[callable.args.length..-1]
-
arg_list = Sass::Script::ArgList.new(rest, keywords.dup, splat_sep)
-
arg_list.options = env.options
-
env.set_local_var(callable.splat.name, arg_list)
-
end
-
-
yield env
-
rescue Exception => e
-
ensure
-
# If there's a keyword exception, we don't want to throw it immediately,
-
# because the invalid keywords may be part of a glob argument that should be
-
# passed on to another function. So we only raise it if we reach the end of
-
# this function *and* the keywords attached to the argument list glob object
-
# haven't been accessed.
-
#
-
# The keyword exception takes precedence over any Sass errors, but not over
-
# non-Sass exceptions.
-
if keyword_exception &&
-
!(arg_list && arg_list.keywords_accessed) &&
-
(e.nil? || e.is_a?(Sass::SyntaxError))
-
raise keyword_exception
-
elsif e
-
raise e
-
end
-
end
-
-
1
protected
-
-
1
def initialize(env)
-
@environment = env
-
# Stack trace information, including mixin includes and imports.
-
@stack = []
-
end
-
-
# If an exception is raised, this adds proper metadata to the backtrace.
-
1
def visit(node)
-
super(node.dup)
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
# Keeps track of the current environment.
-
1
def visit_children(parent)
-
with_environment Sass::Environment.new(@environment, parent.options) do
-
parent.children = super.flatten
-
parent
-
end
-
end
-
-
# Runs a block of code with the current environment replaced with the given one.
-
#
-
# @param env [Sass::Environment] The new environment for the duration of the block.
-
# @yield A block in which the environment is set to `env`.
-
# @return [Object] The return value of the block.
-
1
def with_environment(env)
-
old_env, @environment = @environment, env
-
yield
-
ensure
-
@environment = old_env
-
end
-
-
# Sets the options on the environment if this is the top-level root.
-
1
def visit_root(node)
-
yield
-
rescue Sass::SyntaxError => e
-
e.sass_template ||= node.template
-
raise e
-
end
-
-
# Removes this node from the tree if it's a silent comment.
-
1
def visit_comment(node)
-
return [] if node.invisible?
-
node.resolved_value = run_interp_no_strip(node.value)
-
node.resolved_value.gsub!(/\\([\\#])/, '\1')
-
node
-
end
-
-
# Prints the expression to STDERR.
-
1
def visit_debug(node)
-
res = node.expr.perform(@environment)
-
res = res.value if res.is_a?(Sass::Script::String)
-
if node.filename
-
Sass::Util.sass_warn "#{node.filename}:#{node.line} DEBUG: #{res}"
-
else
-
Sass::Util.sass_warn "Line #{node.line} DEBUG: #{res}"
-
end
-
[]
-
end
-
-
# Runs the child nodes once for each value in the list.
-
1
def visit_each(node)
-
list = node.list.perform(@environment)
-
-
with_environment Sass::Environment.new(@environment) do
-
list.to_a.map do |v|
-
@environment.set_local_var(node.var, v)
-
node.children.map {|c| visit(c)}
-
end.flatten
-
end
-
end
-
-
# Runs SassScript interpolation in the selector,
-
# and then parses the result into a {Sass::Selector::CommaSequence}.
-
1
def visit_extend(node)
-
parser = Sass::SCSS::StaticParser.new(run_interp(node.selector), node.filename, node.line)
-
node.resolved_selector = parser.parse_selector
-
node
-
end
-
-
# Runs the child nodes once for each time through the loop, varying the variable each time.
-
1
def visit_for(node)
-
from = node.from.perform(@environment)
-
to = node.to.perform(@environment)
-
from.assert_int!
-
to.assert_int!
-
-
to = to.coerce(from.numerator_units, from.denominator_units)
-
range = Range.new(from.to_i, to.to_i, node.exclusive)
-
-
with_environment Sass::Environment.new(@environment) do
-
range.map do |i|
-
@environment.set_local_var(node.var,
-
Sass::Script::Number.new(i, from.numerator_units, from.denominator_units))
-
node.children.map {|c| visit(c)}
-
end.flatten
-
end
-
end
-
-
# Loads the function into the environment.
-
1
def visit_function(node)
-
env = Sass::Environment.new(@environment, node.options)
-
@environment.set_local_function(node.name,
-
Sass::Callable.new(node.name, node.args, node.splat, env, node.children, !:has_content, "function"))
-
[]
-
end
-
-
# Runs the child nodes if the conditional expression is true;
-
# otherwise, tries the else nodes.
-
1
def visit_if(node)
-
if node.expr.nil? || node.expr.perform(@environment).to_bool
-
yield
-
node.children
-
elsif node.else
-
visit(node.else)
-
else
-
[]
-
end
-
end
-
-
# Returns a static DirectiveNode if this is importing a CSS file,
-
# or parses and includes the imported Sass file.
-
1
def visit_import(node)
-
if path = node.css_import?
-
return Sass::Tree::CssImportNode.resolved("url(#{path})")
-
end
-
file = node.imported_file
-
handle_import_loop!(node) if @stack.any? {|e| e[:filename] == file.options[:filename]}
-
-
begin
-
@stack.push(:filename => node.filename, :line => node.line)
-
root = file.to_tree
-
Sass::Tree::Visitors::CheckNesting.visit(root)
-
node.children = root.children.map {|c| visit(c)}.flatten
-
node
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.imported_file.options[:filename])
-
e.add_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
ensure
-
@stack.pop unless path
-
end
-
-
# Loads a mixin into the environment.
-
1
def visit_mixindef(node)
-
env = Sass::Environment.new(@environment, node.options)
-
@environment.set_local_mixin(node.name,
-
Sass::Callable.new(node.name, node.args, node.splat, env, node.children, node.has_content, "mixin"))
-
[]
-
end
-
-
# Runs a mixin.
-
1
def visit_mixin(node)
-
include_loop = true
-
handle_include_loop!(node) if @stack.any? {|e| e[:name] == node.name}
-
include_loop = false
-
-
@stack.push(:filename => node.filename, :line => node.line, :name => node.name)
-
raise Sass::SyntaxError.new("Undefined mixin '#{node.name}'.") unless mixin = @environment.mixin(node.name)
-
-
if node.children.any? && !mixin.has_content
-
raise Sass::SyntaxError.new(%Q{Mixin "#{node.name}" does not accept a content block.})
-
end
-
-
args = node.args.map {|a| a.perform(@environment)}
-
keywords = Sass::Util.map_hash(node.keywords) {|k, v| [k, v.perform(@environment)]}
-
splat = node.splat.perform(@environment) if node.splat
-
-
self.class.perform_arguments(mixin, args, keywords, splat) do |env|
-
env.caller = Sass::Environment.new(@environment)
-
env.content = node.children if node.has_children
-
-
trace_node = Sass::Tree::TraceNode.from_node(node.name, node)
-
with_environment(env) {trace_node.children = mixin.tree.map {|c| visit(c)}.flatten}
-
trace_node
-
end
-
rescue Sass::SyntaxError => e
-
unless include_loop
-
e.modify_backtrace(:mixin => node.name, :line => node.line)
-
e.add_backtrace(:line => node.line)
-
end
-
raise e
-
ensure
-
@stack.pop unless include_loop
-
end
-
-
1
def visit_content(node)
-
return [] unless content = @environment.content
-
@stack.push(:filename => node.filename, :line => node.line, :name => '@content')
-
trace_node = Sass::Tree::TraceNode.from_node('@content', node)
-
with_environment(@environment.caller) {trace_node.children = content.map {|c| visit(c.dup)}.flatten}
-
trace_node
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:mixin => '@content', :line => node.line)
-
e.add_backtrace(:line => node.line)
-
raise e
-
ensure
-
@stack.pop if content
-
end
-
-
# Runs any SassScript that may be embedded in a property.
-
1
def visit_prop(node)
-
node.resolved_name = run_interp(node.name)
-
val = node.value.perform(@environment)
-
node.resolved_value = val.to_s
-
yield
-
end
-
-
# Returns the value of the expression.
-
1
def visit_return(node)
-
throw :_sass_return, node.expr.perform(@environment)
-
end
-
-
# Runs SassScript interpolation in the selector,
-
# and then parses the result into a {Sass::Selector::CommaSequence}.
-
1
def visit_rule(node)
-
rule = node.rule
-
rule = rule.map {|e| e.is_a?(String) && e != ' ' ? e.strip : e} if node.style == :compressed
-
parser = Sass::SCSS::StaticParser.new(run_interp(node.rule), node.filename, node.line)
-
node.parsed_rules ||= parser.parse_selector
-
if node.options[:trace_selectors]
-
@stack.push(:filename => node.filename, :line => node.line)
-
node.stack_trace = stack_trace
-
@stack.pop
-
end
-
yield
-
end
-
-
# Loads the new variable value into the environment.
-
1
def visit_variable(node)
-
var = @environment.var(node.name)
-
return [] if node.guarded && var && !var.null?
-
val = node.expr.perform(@environment)
-
@environment.set_var(node.name, val)
-
[]
-
end
-
-
# Prints the expression to STDERR with a stylesheet trace.
-
1
def visit_warn(node)
-
@stack.push(:filename => node.filename, :line => node.line)
-
res = node.expr.perform(@environment)
-
res = res.value if res.is_a?(Sass::Script::String)
-
msg = "WARNING: #{res}\n "
-
msg << stack_trace.join("\n ") << "\n"
-
Sass::Util.sass_warn msg
-
[]
-
ensure
-
@stack.pop
-
end
-
-
# Runs the child nodes until the continuation expression becomes false.
-
1
def visit_while(node)
-
children = []
-
with_environment Sass::Environment.new(@environment) do
-
children += node.children.map {|c| visit(c)} while node.expr.perform(@environment).to_bool
-
end
-
children.flatten
-
end
-
-
1
def visit_directive(node)
-
node.resolved_value = run_interp(node.value)
-
yield
-
end
-
-
1
def visit_media(node)
-
parser = Sass::SCSS::StaticParser.new(run_interp(node.query), node.filename, node.line)
-
node.resolved_query ||= parser.parse_media_query_list
-
yield
-
end
-
-
1
def visit_supports(node)
-
node.condition = node.condition.deep_copy
-
node.condition.perform(@environment)
-
yield
-
end
-
-
1
def visit_cssimport(node)
-
node.resolved_uri = run_interp([node.uri])
-
if node.query
-
parser = Sass::SCSS::StaticParser.new(run_interp(node.query), node.filename, node.line)
-
node.resolved_query ||= parser.parse_media_query_list
-
end
-
yield
-
end
-
-
1
private
-
-
1
def stack_trace
-
trace = []
-
stack = @stack.map {|e| e.dup}.reverse
-
stack.each_cons(2) {|(e1, e2)| e1[:caller] = e2[:name]; [e1, e2]}
-
stack.each_with_index do |entry, i|
-
msg = "#{i == 0 ? "on" : "from"} line #{entry[:line]}"
-
msg << " of #{entry[:filename] || "an unknown file"}"
-
msg << ", in `#{entry[:caller]}'" if entry[:caller]
-
trace << msg
-
end
-
trace
-
end
-
-
1
def run_interp_no_strip(text)
-
text.map do |r|
-
next r if r.is_a?(String)
-
val = r.perform(@environment)
-
# Interpolated strings should never render with quotes
-
next val.value if val.is_a?(Sass::Script::String)
-
val.to_s
-
end.join
-
end
-
-
1
def run_interp(text)
-
run_interp_no_strip(text).strip
-
end
-
-
1
def handle_include_loop!(node)
-
msg = "An @include loop has been found:"
-
content_count = 0
-
mixins = @stack.reverse.map {|s| s[:name]}.compact.select do |s|
-
if s == '@content'
-
content_count += 1
-
false
-
elsif content_count > 0
-
content_count -= 1
-
false
-
else
-
true
-
end
-
end
-
-
return unless mixins.include?(node.name)
-
raise Sass::SyntaxError.new("#{msg} #{node.name} includes itself") if mixins.size == 1
-
-
msg << "\n" << Sass::Util.enum_cons(mixins.reverse + [node.name], 2).map do |m1, m2|
-
" #{m1} includes #{m2}"
-
end.join("\n")
-
raise Sass::SyntaxError.new(msg)
-
end
-
-
1
def handle_import_loop!(node)
-
msg = "An @import loop has been found:"
-
files = @stack.map {|s| s[:filename]}.compact
-
if node.filename == node.imported_file.options[:filename]
-
raise Sass::SyntaxError.new("#{msg} #{node.filename} imports itself")
-
end
-
-
files << node.filename << node.imported_file.options[:filename]
-
msg << "\n" << Sass::Util.enum_cons(files, 2).map do |m1, m2|
-
" #{m1} imports #{m2}"
-
end.join("\n")
-
raise Sass::SyntaxError.new(msg)
-
end
-
end
-
# A visitor for converting a Sass tree into CSS.
-
1
class Sass::Tree::Visitors::ToCss < Sass::Tree::Visitors::Base
-
1
protected
-
-
1
def initialize
-
@tabs = 0
-
end
-
-
1
def visit(node)
-
super
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
1
def with_tabs(tabs)
-
old_tabs, @tabs = @tabs, tabs
-
yield
-
ensure
-
@tabs = old_tabs
-
end
-
-
1
def visit_root(node)
-
result = String.new
-
node.children.each do |child|
-
next if child.invisible?
-
child_str = visit(child)
-
result << child_str + (node.style == :compressed ? '' : "\n")
-
end
-
result.rstrip!
-
return "" if result.empty?
-
result << "\n"
-
unless Sass::Util.ruby1_8? || result.ascii_only?
-
if node.children.first.is_a?(Sass::Tree::CharsetNode)
-
begin
-
encoding = node.children.first.name
-
# Default to big-endian encoding, because we have to decide somehow
-
encoding << 'BE' if encoding =~ /\Autf-(16|32)\Z/i
-
result = result.encode(Encoding.find(encoding))
-
rescue EncodingError
-
end
-
end
-
-
result = "@charset \"#{result.encoding.name}\";#{
-
node.style == :compressed ? '' : "\n"
-
}".encode(result.encoding) + result
-
end
-
result
-
rescue Sass::SyntaxError => e
-
e.sass_template ||= node.template
-
raise e
-
end
-
-
1
def visit_charset(node)
-
"@charset \"#{node.name}\";"
-
end
-
-
1
def visit_comment(node)
-
return if node.invisible?
-
spaces = (' ' * [@tabs - node.resolved_value[/^ */].size, 0].max)
-
-
content = node.resolved_value.gsub(/^/, spaces)
-
content.gsub!(%r{^(\s*)//(.*)$}) {|md| "#{$1}/*#{$2} */"} if node.type == :silent
-
content.gsub!(/\n +(\* *(?!\/))?/, ' ') if (node.style == :compact || node.style == :compressed) && node.type != :loud
-
content
-
end
-
-
1
def visit_directive(node)
-
was_in_directive = @in_directive
-
tab_str = ' ' * @tabs
-
return tab_str + node.resolved_value + ";" unless node.has_children
-
return tab_str + node.resolved_value + " {}" if node.children.empty?
-
@in_directive = @in_directive || !node.is_a?(Sass::Tree::MediaNode)
-
result = if node.style == :compressed
-
"#{node.resolved_value}{"
-
else
-
"#{tab_str}#{node.resolved_value} {" + (node.style == :compact ? ' ' : "\n")
-
end
-
was_prop = false
-
first = true
-
node.children.each do |child|
-
next if child.invisible?
-
if node.style == :compact
-
if child.is_a?(Sass::Tree::PropNode)
-
with_tabs(first || was_prop ? 0 : @tabs + 1) {result << visit(child) << ' '}
-
else
-
result[-1] = "\n" if was_prop
-
rendered = with_tabs(@tabs + 1) {visit(child).dup}
-
rendered = rendered.lstrip if first
-
result << rendered.rstrip + "\n"
-
end
-
was_prop = child.is_a?(Sass::Tree::PropNode)
-
first = false
-
elsif node.style == :compressed
-
result << (was_prop ? ";" : "") << with_tabs(0) {visit(child)}
-
was_prop = child.is_a?(Sass::Tree::PropNode)
-
else
-
result << with_tabs(@tabs + 1) {visit(child)} + "\n"
-
end
-
end
-
result.rstrip + if node.style == :compressed
-
"}"
-
else
-
(node.style == :expanded ? "\n" : " ") + "}\n"
-
end
-
ensure
-
@in_directive = was_in_directive
-
end
-
-
1
def visit_media(node)
-
str = with_tabs(@tabs + node.tabs) {visit_directive(node)}
-
str.gsub!(/\n\Z/, '') unless node.style == :compressed || node.group_end
-
str
-
end
-
-
1
def visit_supports(node)
-
visit_media(node)
-
end
-
-
1
def visit_cssimport(node)
-
visit_directive(node)
-
end
-
-
1
def visit_prop(node)
-
return if node.resolved_value.empty?
-
tab_str = ' ' * (@tabs + node.tabs)
-
if node.style == :compressed
-
"#{tab_str}#{node.resolved_name}:#{node.resolved_value}"
-
else
-
"#{tab_str}#{node.resolved_name}: #{node.resolved_value};"
-
end
-
end
-
-
1
def visit_rule(node)
-
with_tabs(@tabs + node.tabs) do
-
rule_separator = node.style == :compressed ? ',' : ', '
-
line_separator =
-
case node.style
-
when :nested, :expanded; "\n"
-
when :compressed; ""
-
else; " "
-
end
-
rule_indent = ' ' * @tabs
-
per_rule_indent, total_indent = [:nested, :expanded].include?(node.style) ? [rule_indent, ''] : ['', rule_indent]
-
-
joined_rules = node.resolved_rules.members.map do |seq|
-
next if seq.has_placeholder?
-
rule_part = seq.to_a.join
-
if node.style == :compressed
-
rule_part.gsub!(/([^,])\s*\n\s*/m, '\1 ')
-
rule_part.gsub!(/\s*([,+>])\s*/m, '\1')
-
rule_part.strip!
-
end
-
rule_part
-
end.compact.join(rule_separator)
-
-
joined_rules.sub!(/\A\s*/, per_rule_indent)
-
joined_rules.gsub!(/\s*\n\s*/, "#{line_separator}#{per_rule_indent}")
-
total_rule = total_indent << joined_rules
-
-
to_return = ''
-
old_spaces = ' ' * @tabs
-
if node.style != :compressed
-
if node.options[:debug_info] && !@in_directive
-
to_return << visit(debug_info_rule(node.debug_info, node.options)) << "\n"
-
elsif node.options[:trace_selectors]
-
to_return << "#{old_spaces}/* "
-
to_return << node.stack_trace.join("\n #{old_spaces}")
-
to_return << " */\n"
-
elsif node.options[:line_comments]
-
to_return << "#{old_spaces}/* line #{node.line}"
-
-
if node.filename
-
relative_filename = if node.options[:css_filename]
-
begin
-
Pathname.new(node.filename).relative_path_from(
-
Pathname.new(File.dirname(node.options[:css_filename]))).to_s
-
rescue ArgumentError
-
nil
-
end
-
end
-
relative_filename ||= node.filename
-
to_return << ", #{relative_filename}"
-
end
-
-
to_return << " */\n"
-
end
-
end
-
-
if node.style == :compact
-
properties = with_tabs(0) {node.children.map {|a| visit(a)}.join(' ')}
-
to_return << "#{total_rule} { #{properties} }#{"\n" if node.group_end}"
-
elsif node.style == :compressed
-
properties = with_tabs(0) {node.children.map {|a| visit(a)}.join(';')}
-
to_return << "#{total_rule}{#{properties}}"
-
else
-
properties = with_tabs(@tabs + 1) {node.children.map {|a| visit(a)}.join("\n")}
-
end_props = (node.style == :expanded ? "\n" + old_spaces : ' ')
-
to_return << "#{total_rule} {\n#{properties}#{end_props}}#{"\n" if node.group_end}"
-
end
-
-
to_return
-
end
-
end
-
-
1
private
-
-
1
def debug_info_rule(debug_info, options)
-
node = Sass::Tree::DirectiveNode.resolved("@media -sass-debug-info")
-
Sass::Util.hash_to_a(debug_info.map {|k, v| [k.to_s, v.to_s]}).each do |k, v|
-
rule = Sass::Tree::RuleNode.new([""])
-
rule.resolved_rules = Sass::Selector::CommaSequence.new(
-
[Sass::Selector::Sequence.new(
-
[Sass::Selector::SimpleSequence.new(
-
[Sass::Selector::Element.new(k.to_s.gsub(/[^\w-]/, "\\\\\\0"), nil)],
-
false)
-
])
-
])
-
prop = Sass::Tree::PropNode.new([""], Sass::Script::String.new(''), :new)
-
prop.resolved_name = "font-family"
-
prop.resolved_value = Sass::SCSS::RX.escape_ident(v.to_s)
-
rule << prop
-
node << rule
-
end
-
node.options = options.merge(:debug_info => false, :line_comments => false, :style => :compressed)
-
node
-
end
-
end
-
1
module Sass
-
1
module Tree
-
# A dynamic node representing a Sass `@warn` statement.
-
#
-
# @see Sass::Tree
-
1
class WarnNode < Node
-
# The expression to print.
-
# @return [Script::Node]
-
1
attr_accessor :expr
-
-
# @param expr [Script::Node] The expression to print
-
1
def initialize(expr)
-
@expr = expr
-
super()
-
end
-
end
-
end
-
end
-
1
require 'sass/tree/node'
-
-
1
module Sass::Tree
-
# A dynamic node representing a Sass `@while` loop.
-
#
-
# @see Sass::Tree
-
1
class WhileNode < Node
-
# The parse tree for the continuation expression.
-
# @return [Script::Node]
-
1
attr_accessor :expr
-
-
# @param expr [Script::Node] See \{#expr}
-
1
def initialize(expr)
-
@expr = expr
-
super()
-
end
-
end
-
end
-
1
require 'erb'
-
1
require 'set'
-
1
require 'enumerator'
-
1
require 'stringio'
-
1
require 'rbconfig'
-
1
require 'thread'
-
-
1
require 'sass/root'
-
1
require 'sass/util/subset_map'
-
-
1
module Sass
-
# A module containing various useful functions.
-
1
module Util
-
1
extend self
-
-
# An array of ints representing the Ruby version number.
-
# @api public
-
4
RUBY_VERSION = ::RUBY_VERSION.split(".").map {|s| s.to_i}
-
-
# The Ruby engine we're running under. Defaults to `"ruby"`
-
# if the top-level constant is undefined.
-
# @api public
-
1
RUBY_ENGINE = defined?(::RUBY_ENGINE) ? ::RUBY_ENGINE : "ruby"
-
-
# Returns the path of a file relative to the Sass root directory.
-
#
-
# @param file [String] The filename relative to the Sass root
-
# @return [String] The filename relative to the the working directory
-
1
def scope(file)
-
7
File.join(Sass::ROOT_DIR, file)
-
end
-
-
# Converts an array of `[key, value]` pairs to a hash.
-
#
-
# @example
-
# to_hash([[:foo, "bar"], [:baz, "bang"]])
-
# #=> {:foo => "bar", :baz => "bang"}
-
# @param arr [Array<(Object, Object)>] An array of pairs
-
# @return [Hash] A hash
-
1
def to_hash(arr)
-
5
Hash[arr.compact]
-
end
-
-
# Maps the keys in a hash according to a block.
-
#
-
# @example
-
# map_keys({:foo => "bar", :baz => "bang"}) {|k| k.to_s}
-
# #=> {"foo" => "bar", "baz" => "bang"}
-
# @param hash [Hash] The hash to map
-
# @yield [key] A block in which the keys are transformed
-
# @yieldparam key [Object] The key that should be mapped
-
# @yieldreturn [Object] The new value for the key
-
# @return [Hash] The mapped hash
-
# @see #map_vals
-
# @see #map_hash
-
1
def map_keys(hash)
-
to_hash(hash.map {|k, v| [yield(k), v]})
-
end
-
-
# Maps the values in a hash according to a block.
-
#
-
# @example
-
# map_values({:foo => "bar", :baz => "bang"}) {|v| v.to_sym}
-
# #=> {:foo => :bar, :baz => :bang}
-
# @param hash [Hash] The hash to map
-
# @yield [value] A block in which the values are transformed
-
# @yieldparam value [Object] The value that should be mapped
-
# @yieldreturn [Object] The new value for the value
-
# @return [Hash] The mapped hash
-
# @see #map_keys
-
# @see #map_hash
-
1
def map_vals(hash)
-
147
to_hash(hash.map {|k, v| [k, yield(v)]})
-
end
-
-
# Maps the key-value pairs of a hash according to a block.
-
#
-
# @example
-
# map_hash({:foo => "bar", :baz => "bang"}) {|k, v| [k.to_s, v.to_sym]}
-
# #=> {"foo" => :bar, "baz" => :bang}
-
# @param hash [Hash] The hash to map
-
# @yield [key, value] A block in which the key-value pairs are transformed
-
# @yieldparam [key] The hash key
-
# @yieldparam [value] The hash value
-
# @yieldreturn [(Object, Object)] The new value for the `[key, value]` pair
-
# @return [Hash] The mapped hash
-
# @see #map_keys
-
# @see #map_vals
-
1
def map_hash(hash)
-
# Using &block here completely hoses performance on 1.8.
-
197
to_hash(hash.map {|k, v| yield k, v})
-
end
-
-
# Computes the powerset of the given array.
-
# This is the set of all subsets of the array.
-
#
-
# @example
-
# powerset([1, 2, 3]) #=>
-
# Set[Set[], Set[1], Set[2], Set[3], Set[1, 2], Set[2, 3], Set[1, 3], Set[1, 2, 3]]
-
# @param arr [Enumerable]
-
# @return [Set<Set>] The subsets of `arr`
-
1
def powerset(arr)
-
arr.inject([Set.new].to_set) do |powerset, el|
-
new_powerset = Set.new
-
powerset.each do |subset|
-
new_powerset << subset
-
new_powerset << subset + [el]
-
end
-
new_powerset
-
end
-
end
-
-
# Restricts a number to falling within a given range.
-
# Returns the number if it falls within the range,
-
# or the closest value in the range if it doesn't.
-
#
-
# @param value [Numeric]
-
# @param range [Range<Numeric>]
-
# @return [Numeric]
-
1
def restrict(value, range)
-
[[value, range.first].max, range.last].min
-
end
-
-
# Concatenates all strings that are adjacent in an array,
-
# while leaving other elements as they are.
-
#
-
# @example
-
# merge_adjacent_strings([1, "foo", "bar", 2, "baz"])
-
# #=> [1, "foobar", 2, "baz"]
-
# @param arr [Array]
-
# @return [Array] The enumerable with strings merged
-
1
def merge_adjacent_strings(arr)
-
# Optimize for the common case of one element
-
return arr if arr.size < 2
-
arr.inject([]) do |a, e|
-
if e.is_a?(String)
-
if a.last.is_a?(String)
-
a.last << e
-
else
-
a << e.dup
-
end
-
else
-
a << e
-
end
-
a
-
end
-
end
-
-
# Intersperses a value in an enumerable, as would be done with `Array#join`
-
# but without concatenating the array together afterwards.
-
#
-
# @param enum [Enumerable]
-
# @param val
-
# @return [Array]
-
1
def intersperse(enum, val)
-
enum.inject([]) {|a, e| a << e << val}[0...-1]
-
end
-
-
# Substitutes a sub-array of one array with another sub-array.
-
#
-
# @param ary [Array] The array in which to make the substitution
-
# @param from [Array] The sequence of elements to replace with `to`
-
# @param to [Array] The sequence of elements to replace `from` with
-
1
def substitute(ary, from, to)
-
res = ary.dup
-
i = 0
-
while i < res.size
-
if res[i...i+from.size] == from
-
res[i...i+from.size] = to
-
end
-
i += 1
-
end
-
res
-
end
-
-
# Destructively strips whitespace from the beginning and end
-
# of the first and last elements, respectively,
-
# in the array (if those elements are strings).
-
#
-
# @param arr [Array]
-
# @return [Array] `arr`
-
1
def strip_string_array(arr)
-
arr.first.lstrip! if arr.first.is_a?(String)
-
arr.last.rstrip! if arr.last.is_a?(String)
-
arr
-
end
-
-
# Return an array of all possible paths through the given arrays.
-
#
-
# @param arrs [Array<Array>]
-
# @return [Array<Arrays>]
-
#
-
# @example
-
# paths([[1, 2], [3, 4], [5]]) #=>
-
# # [[1, 3, 5],
-
# # [2, 3, 5],
-
# # [1, 4, 5],
-
# # [2, 4, 5]]
-
1
def paths(arrs)
-
arrs.inject([[]]) do |paths, arr|
-
flatten(arr.map {|e| paths.map {|path| path + [e]}}, 1)
-
end
-
end
-
-
# Computes a single longest common subsequence for `x` and `y`.
-
# If there are more than one longest common subsequences,
-
# the one returned is that which starts first in `x`.
-
#
-
# @param x [Array]
-
# @param y [Array]
-
# @yield [a, b] An optional block to use in place of a check for equality
-
# between elements of `x` and `y`.
-
# @yieldreturn [Object, nil] If the two values register as equal,
-
# this will return the value to use in the LCS array.
-
# @return [Array] The LCS
-
1
def lcs(x, y, &block)
-
x = [nil, *x]
-
y = [nil, *y]
-
block ||= proc {|a, b| a == b && a}
-
lcs_backtrace(lcs_table(x, y, &block), x, y, x.size-1, y.size-1, &block)
-
end
-
-
# Converts a Hash to an Array. This is usually identical to `Hash#to_a`,
-
# with the following exceptions:
-
#
-
# * In Ruby 1.8, `Hash#to_a` is not deterministically ordered, but this is.
-
# * In Ruby 1.9 when running tests, this is ordered in the same way it would
-
# be under Ruby 1.8 (sorted key order rather than insertion order).
-
#
-
# @param hash [Hash]
-
# @return [Array]
-
1
def hash_to_a(hash)
-
1
return hash.to_a unless ruby1_8? || defined?(Test::Unit)
-
return hash.sort_by {|k, v| k}
-
end
-
-
# Performs the equivalent of `enum.group_by.to_a`, but with a guaranteed
-
# order. Unlike [#hash_to_a], the resulting order isn't sorted key order;
-
# instead, it's the same order as `#group_by` has under Ruby 1.9 (key
-
# appearance order).
-
#
-
# @param enum [Enumerable]
-
# @return [Array<[Object, Array]>] An array of pairs.
-
1
def group_by_to_a(enum, &block)
-
return enum.group_by(&block).to_a unless ruby1_8?
-
order = {}
-
arr = []
-
enum.group_by do |e|
-
res = block[e]
-
unless order.include?(res)
-
order[res] = order.size
-
end
-
res
-
end.each do |key, vals|
-
arr[order[key]] = [key, vals]
-
end
-
arr
-
end
-
-
# Returns a sub-array of `minuend` containing only elements that are also in
-
# `subtrahend`. Ensures that the return value has the same order as
-
# `minuend`, even on Rubinius where that's not guaranteed by {Array#-}.
-
#
-
# @param minuend [Array]
-
# @param subtrahend [Array]
-
# @return [Array]
-
1
def array_minus(minuend, subtrahend)
-
return minuend - subtrahend unless rbx?
-
set = Set.new(minuend) - subtrahend
-
minuend.select {|e| set.include?(e)}
-
end
-
-
# Returns a string description of the character that caused an
-
# `Encoding::UndefinedConversionError`.
-
#
-
# @param [Encoding::UndefinedConversionError]
-
# @return [String]
-
1
def undefined_conversion_error_char(e)
-
# Rubinius (as of 2.0.0.rc1) pre-quotes the error character.
-
return e.error_char if rbx?
-
# JRuby (as of 1.7.2) doesn't have an error_char field on
-
# Encoding::UndefinedConversionError.
-
return e.error_char.dump unless jruby?
-
e.message[/^"[^"]+"/] #"
-
end
-
-
# Asserts that `value` falls within `range` (inclusive), leaving
-
# room for slight floating-point errors.
-
#
-
# @param name [String] The name of the value. Used in the error message.
-
# @param range [Range] The allowed range of values.
-
# @param value [Numeric, Sass::Script::Number] The value to check.
-
# @param unit [String] The unit of the value. Used in error reporting.
-
# @return [Numeric] `value` adjusted to fall within range, if it
-
# was outside by a floating-point margin.
-
1
def check_range(name, range, value, unit='')
-
grace = (-0.00001..0.00001)
-
str = value.to_s
-
value = value.value if value.is_a?(Sass::Script::Number)
-
return value if range.include?(value)
-
return range.first if grace.include?(value - range.first)
-
return range.last if grace.include?(value - range.last)
-
raise ArgumentError.new(
-
"#{name} #{str} must be between #{range.first}#{unit} and #{range.last}#{unit}")
-
end
-
-
# Returns whether or not `seq1` is a subsequence of `seq2`. That is, whether
-
# or not `seq2` contains every element in `seq1` in the same order (and
-
# possibly more elements besides).
-
#
-
# @param seq1 [Array]
-
# @param seq2 [Array]
-
# @return [Boolean]
-
1
def subsequence?(seq1, seq2)
-
i = j = 0
-
loop do
-
return true if i == seq1.size
-
return false if j == seq2.size
-
i += 1 if seq1[i] == seq2[j]
-
j += 1
-
end
-
end
-
-
# Returns information about the caller of the previous method.
-
#
-
# @param entry [String] An entry in the `#caller` list, or a similarly formatted string
-
# @return [[String, Fixnum, (String, nil)]] An array containing the filename, line, and method name of the caller.
-
# The method name may be nil
-
1
def caller_info(entry = nil)
-
# JRuby evaluates `caller` incorrectly when it's in an actual default argument.
-
entry ||= caller[1]
-
info = entry.scan(/^(.*?):(-?.*?)(?::.*`(.+)')?$/).first
-
info[1] = info[1].to_i
-
# This is added by Rubinius to designate a block, but we don't care about it.
-
info[2].sub!(/ \{\}\Z/, '') if info[2]
-
info
-
end
-
-
# Returns whether one version string represents a more recent version than another.
-
#
-
# @param v1 [String] A version string.
-
# @param v2 [String] Another version string.
-
# @return [Boolean]
-
1
def version_gt(v1, v2)
-
# Construct an array to make sure the shorter version is padded with nil
-
1
Array.new([v1.length, v2.length].max).zip(v1.split("."), v2.split(".")) do |_, p1, p2|
-
1
p1 ||= "0"
-
1
p2 ||= "0"
-
1
release1 = p1 =~ /^[0-9]+$/
-
1
release2 = p2 =~ /^[0-9]+$/
-
1
if release1 && release2
-
# Integer comparison if both are full releases
-
1
p1, p2 = p1.to_i, p2.to_i
-
1
next if p1 == p2
-
1
return p1 > p2
-
elsif !release1 && !release2
-
# String comparison if both are prereleases
-
next if p1 == p2
-
return p1 > p2
-
else
-
# If only one is a release, that one is newer
-
return release1
-
end
-
end
-
end
-
-
# Returns whether one version string represents the same or a more
-
# recent version than another.
-
#
-
# @param v1 [String] A version string.
-
# @param v2 [String] Another version string.
-
# @return [Boolean]
-
1
def version_geq(v1, v2)
-
1
version_gt(v1, v2) || !version_gt(v2, v1)
-
end
-
-
# Throws a NotImplementedError for an abstract method.
-
#
-
# @param obj [Object] `self`
-
# @raise [NotImplementedError]
-
1
def abstract(obj)
-
raise NotImplementedError.new("#{obj.class} must implement ##{caller_info[2]}")
-
end
-
-
# Silence all output to STDERR within a block.
-
#
-
# @yield A block in which no output will be printed to STDERR
-
1
def silence_warnings
-
the_real_stderr, $stderr = $stderr, StringIO.new
-
yield
-
ensure
-
$stderr = the_real_stderr
-
end
-
-
1
@@silence_warnings = false
-
# Silences all Sass warnings within a block.
-
#
-
# @yield A block in which no Sass warnings will be printed
-
1
def silence_sass_warnings
-
old_level, Sass.logger.log_level = Sass.logger.log_level, :error
-
yield
-
ensure
-
Sass.logger.log_level = old_level
-
end
-
-
# The same as `Kernel#warn`, but is silenced by \{#silence\_sass\_warnings}.
-
#
-
# @param msg [String]
-
1
def sass_warn(msg)
-
msg = msg + "\n" unless ruby1?
-
Sass.logger.warn(msg)
-
end
-
-
## Cross Rails Version Compatibility
-
-
# Returns the root of the Rails application,
-
# if this is running in a Rails context.
-
# Returns `nil` if no such root is defined.
-
#
-
# @return [String, nil]
-
1
def rails_root
-
if defined?(::Rails.root)
-
return ::Rails.root.to_s if ::Rails.root
-
raise "ERROR: Rails.root is nil!"
-
end
-
return RAILS_ROOT.to_s if defined?(RAILS_ROOT)
-
return nil
-
end
-
-
# Returns the environment of the Rails application,
-
# if this is running in a Rails context.
-
# Returns `nil` if no such environment is defined.
-
#
-
# @return [String, nil]
-
1
def rails_env
-
return ::Rails.env.to_s if defined?(::Rails.env)
-
return RAILS_ENV.to_s if defined?(RAILS_ENV)
-
return nil
-
end
-
-
# Returns whether this environment is using ActionPack
-
# version 3.0.0 or greater.
-
#
-
# @return [Boolean]
-
1
def ap_geq_3?
-
ap_geq?("3.0.0.beta1")
-
end
-
-
# Returns whether this environment is using ActionPack
-
# of a version greater than or equal to that specified.
-
#
-
# @param version [String] The string version number to check against.
-
# Should be greater than or equal to Rails 3,
-
# because otherwise ActionPack::VERSION isn't autoloaded
-
# @return [Boolean]
-
1
def ap_geq?(version)
-
# The ActionPack module is always loaded automatically in Rails >= 3
-
1
return false unless defined?(ActionPack) && defined?(ActionPack::VERSION) &&
-
defined?(ActionPack::VERSION::STRING)
-
-
1
version_geq(ActionPack::VERSION::STRING, version)
-
end
-
-
# Returns an ActionView::Template* class.
-
# In pre-3.0 versions of Rails, most of these classes
-
# were of the form `ActionView::TemplateFoo`,
-
# while afterwards they were of the form `ActionView;:Template::Foo`.
-
#
-
# @param name [#to_s] The name of the class to get.
-
# For example, `:Error` will return `ActionView::TemplateError`
-
# or `ActionView::Template::Error`.
-
1
def av_template_class(name)
-
return ActionView.const_get("Template#{name}") if ActionView.const_defined?("Template#{name}")
-
return ActionView::Template.const_get(name.to_s)
-
end
-
-
## Cross-OS Compatibility
-
-
# Whether or not this is running on Windows.
-
#
-
# @return [Boolean]
-
1
def windows?
-
RbConfig::CONFIG['host_os'] =~ /mswin|windows|mingw/i
-
end
-
-
# Whether or not this is running on IronRuby.
-
#
-
# @return [Boolean]
-
1
def ironruby?
-
5
RUBY_ENGINE == "ironruby"
-
end
-
-
# Whether or not this is running on Rubinius.
-
#
-
# @return [Boolean]
-
1
def rbx?
-
1
RUBY_ENGINE == "rbx"
-
end
-
-
# Whether or not this is running on JRuby.
-
#
-
# @return [Boolean]
-
1
def jruby?
-
RUBY_PLATFORM =~ /java/
-
end
-
-
# Returns an array of ints representing the JRuby version number.
-
#
-
# @return [Array<Fixnum>]
-
1
def jruby_version
-
$jruby_version ||= ::JRUBY_VERSION.split(".").map {|s| s.to_i}
-
end
-
-
# Like `Dir.glob`, but works with backslash-separated paths on Windows.
-
#
-
# @param path [String]
-
1
def glob(path, &block)
-
path = path.gsub('\\', '/') if windows?
-
Dir.glob(path, &block)
-
end
-
-
# Prepare a value for a destructuring assignment (e.g. `a, b =
-
# val`). This works around a performance bug when using
-
# ActiveSupport, and only needs to be called when `val` is likely
-
# to be `nil` reasonably often.
-
#
-
# See [this bug report](http://redmine.ruby-lang.org/issues/4917).
-
#
-
# @param val [Object]
-
# @return [Object]
-
1
def destructure(val)
-
val || []
-
end
-
-
## Cross-Ruby-Version Compatibility
-
-
# Whether or not this is running under a Ruby version under 2.0.
-
#
-
# @return [Boolean]
-
1
def ruby1?
-
Sass::Util::RUBY_VERSION[0] <= 1
-
end
-
-
# Whether or not this is running under Ruby 1.8 or lower.
-
#
-
# Note that IronRuby counts as Ruby 1.8,
-
# because it doesn't support the Ruby 1.9 encoding API.
-
#
-
# @return [Boolean]
-
1
def ruby1_8?
-
# IronRuby says its version is 1.9, but doesn't support any of the encoding APIs.
-
# We have to fall back to 1.8 behavior.
-
5
ironruby? || (Sass::Util::RUBY_VERSION[0] == 1 && Sass::Util::RUBY_VERSION[1] < 9)
-
end
-
-
# Whether or not this is running under Ruby 1.8.6 or lower.
-
# Note that lower versions are not officially supported.
-
#
-
# @return [Boolean]
-
1
def ruby1_8_6?
-
ruby1_8? && Sass::Util::RUBY_VERSION[2] < 7
-
end
-
-
# Wehter or not this is running under JRuby 1.6 or lower.
-
1
def jruby1_6?
-
jruby? && jruby_version[0] == 1 && jruby_version[1] < 7
-
end
-
-
# Whether or not this is running under MacRuby.
-
#
-
# @return [Boolean]
-
1
def macruby?
-
1
RUBY_ENGINE == 'macruby'
-
end
-
-
# Checks that the encoding of a string is valid in Ruby 1.9
-
# and cleans up potential encoding gotchas like the UTF-8 BOM.
-
# If it's not, yields an error string describing the invalid character
-
# and the line on which it occurrs.
-
#
-
# @param str [String] The string of which to check the encoding
-
# @yield [msg] A block in which an encoding error can be raised.
-
# Only yields if there is an encoding error
-
# @yieldparam msg [String] The error message to be raised
-
# @return [String] `str`, potentially with encoding gotchas like BOMs removed
-
1
def check_encoding(str)
-
if ruby1_8?
-
return str.gsub(/\A\xEF\xBB\xBF/, '') # Get rid of the UTF-8 BOM
-
elsif str.valid_encoding?
-
# Get rid of the Unicode BOM if possible
-
if str.encoding.name =~ /^UTF-(8|16|32)(BE|LE)?$/
-
return str.gsub(Regexp.new("\\A\uFEFF".encode(str.encoding.name)), '')
-
else
-
return str
-
end
-
end
-
-
encoding = str.encoding
-
newlines = Regexp.new("\r\n|\r|\n".encode(encoding).force_encoding("binary"))
-
str.force_encoding("binary").split(newlines).each_with_index do |line, i|
-
begin
-
line.encode(encoding)
-
rescue Encoding::UndefinedConversionError => e
-
yield <<MSG.rstrip, i + 1
-
Invalid #{encoding.name} character #{undefined_conversion_error_char(e)}
-
MSG
-
end
-
end
-
return str
-
end
-
-
# Like {\#check\_encoding}, but also checks for a `@charset` declaration
-
# at the beginning of the file and uses that encoding if it exists.
-
#
-
# The Sass encoding rules are simple.
-
# If a `@charset` declaration exists,
-
# we assume that that's the original encoding of the document.
-
# Otherwise, we use whatever encoding Ruby has.
-
# Then we convert that to UTF-8 to process internally.
-
# The UTF-8 end result is what's returned by this method.
-
#
-
# @param str [String] The string of which to check the encoding
-
# @yield [msg] A block in which an encoding error can be raised.
-
# Only yields if there is an encoding error
-
# @yieldparam msg [String] The error message to be raised
-
# @return [(String, Encoding)] The original string encoded as UTF-8,
-
# and the source encoding of the string (or `nil` under Ruby 1.8)
-
# @raise [Encoding::UndefinedConversionError] if the source encoding
-
# cannot be converted to UTF-8
-
# @raise [ArgumentError] if the document uses an unknown encoding with `@charset`
-
1
def check_sass_encoding(str, &block)
-
return check_encoding(str, &block), nil if ruby1_8?
-
# We allow any printable ASCII characters but double quotes in the charset decl
-
bin = str.dup.force_encoding("BINARY")
-
encoding = Sass::Util::ENCODINGS_TO_CHECK.find do |enc|
-
re = Sass::Util::CHARSET_REGEXPS[enc]
-
re && bin =~ re
-
end
-
charset, bom = $1, $2
-
if charset
-
charset = charset.force_encoding(encoding).encode("UTF-8")
-
if endianness = encoding[/[BL]E$/]
-
begin
-
Encoding.find(charset + endianness)
-
charset << endianness
-
rescue ArgumentError # Encoding charset + endianness doesn't exist
-
end
-
end
-
str.force_encoding(charset)
-
elsif bom
-
str.force_encoding(encoding)
-
end
-
-
str = check_encoding(str, &block)
-
return str.encode("UTF-8"), str.encoding
-
end
-
-
1
unless ruby1_8?
-
# @private
-
1
def _enc(string, encoding)
-
string.encode(encoding).force_encoding("BINARY")
-
end
-
-
# We could automatically add in any non-ASCII-compatible encodings here,
-
# but there's not really a good way to do that
-
# without manually checking that each encoding
-
# encodes all ASCII characters properly,
-
# which takes long enough to affect the startup time of the CLI.
-
1
ENCODINGS_TO_CHECK = %w[UTF-8 UTF-16BE UTF-16LE UTF-32BE UTF-32LE]
-
-
1
CHARSET_REGEXPS = Hash.new do |h, e|
-
h[e] =
-
begin
-
# /\A(?:\uFEFF)?@charset "(.*?)"|\A(\uFEFF)/
-
Regexp.new(/\A(?:#{_enc("\uFEFF", e)})?#{
-
_enc('@charset "', e)}(.*?)#{_enc('"', e)}|\A(#{
-
_enc("\uFEFF", e)})/)
-
rescue Encoding::ConverterNotFoundError => _
-
nil # JRuby on Java 5 doesn't support UTF-32
-
rescue
-
# /\A@charset "(.*?)"/
-
Regexp.new(/\A#{_enc('@charset "', e)}(.*?)#{_enc('"', e)}/)
-
end
-
end
-
end
-
-
# Checks to see if a class has a given method.
-
# For example:
-
#
-
# Sass::Util.has?(:public_instance_method, String, :gsub) #=> true
-
#
-
# Method collections like `Class#instance_methods`
-
# return strings in Ruby 1.8 and symbols in Ruby 1.9 and on,
-
# so this handles checking for them in a compatible way.
-
#
-
# @param attr [#to_s] The (singular) name of the method-collection method
-
# (e.g. `:instance_methods`, `:private_methods`)
-
# @param klass [Module] The class to check the methods of which to check
-
# @param method [String, Symbol] The name of the method do check for
-
# @return [Boolean] Whether or not the given collection has the given method
-
1
def has?(attr, klass, method)
-
1
klass.send("#{attr}s").include?(ruby1_8? ? method.to_s : method.to_sym)
-
end
-
-
# A version of `Enumerable#enum_with_index` that works in Ruby 1.8 and 1.9.
-
#
-
# @param enum [Enumerable] The enumerable to get the enumerator for
-
# @return [Enumerator] The with-index enumerator
-
1
def enum_with_index(enum)
-
ruby1_8? ? enum.enum_with_index : enum.each_with_index
-
end
-
-
# A version of `Enumerable#enum_cons` that works in Ruby 1.8 and 1.9.
-
#
-
# @param enum [Enumerable] The enumerable to get the enumerator for
-
# @param n [Fixnum] The size of each cons
-
# @return [Enumerator] The consed enumerator
-
1
def enum_cons(enum, n)
-
ruby1_8? ? enum.enum_cons(n) : enum.each_cons(n)
-
end
-
-
# A version of `Enumerable#enum_slice` that works in Ruby 1.8 and 1.9.
-
#
-
# @param enum [Enumerable] The enumerable to get the enumerator for
-
# @param n [Fixnum] The size of each slice
-
# @return [Enumerator] The consed enumerator
-
1
def enum_slice(enum, n)
-
ruby1_8? ? enum.enum_slice(n) : enum.each_slice(n)
-
end
-
-
# Destructively removes all elements from an array that match a block, and
-
# returns the removed elements.
-
#
-
# @param array [Array] The array from which to remove elements.
-
# @yield [el] Called for each element.
-
# @yieldparam el [*] The element to test.
-
# @yieldreturn [Boolean] Whether or not to extract the element.
-
# @return [Array] The extracted elements.
-
1
def extract!(array)
-
out = []
-
array.reject! do |e|
-
next false unless yield e
-
out << e
-
true
-
end
-
out
-
end
-
-
# Returns the ASCII code of the given character.
-
#
-
# @param c [String] All characters but the first are ignored.
-
# @return [Fixnum] The ASCII code of `c`.
-
1
def ord(c)
-
ruby1_8? ? c[0] : c.ord
-
end
-
-
# Flattens the first `n` nested arrays in a cross-version manner.
-
#
-
# @param arr [Array] The array to flatten
-
# @param n [Fixnum] The number of levels to flatten
-
# @return [Array] The flattened array
-
1
def flatten(arr, n)
-
return arr.flatten(n) unless ruby1_8_6?
-
return arr if n == 0
-
arr.inject([]) {|res, e| e.is_a?(Array) ? res.concat(flatten(e, n - 1)) : res << e}
-
end
-
-
# Returns the hash code for a set in a cross-version manner.
-
# Aggravatingly, this is order-dependent in Ruby 1.8.6.
-
#
-
# @param set [Set]
-
# @return [Fixnum] The order-independent hashcode of `set`
-
1
def set_hash(set)
-
return set.hash unless ruby1_8_6?
-
set.map {|e| e.hash}.uniq.sort.hash
-
end
-
-
# Tests the hash-equality of two sets in a cross-version manner.
-
# Aggravatingly, this is order-dependent in Ruby 1.8.6.
-
#
-
# @param set1 [Set]
-
# @param set2 [Set]
-
# @return [Boolean] Whether or not the sets are hashcode equal
-
1
def set_eql?(set1, set2)
-
return set1.eql?(set2) unless ruby1_8_6?
-
set1.to_a.uniq.sort_by {|e| e.hash}.eql?(set2.to_a.uniq.sort_by {|e| e.hash})
-
end
-
-
# Like `Object#inspect`, but preserves non-ASCII characters rather than escaping them under Ruby 1.9.2.
-
# This is necessary so that the precompiled Haml template can be `#encode`d into `@options[:encoding]`
-
# before being evaluated.
-
#
-
# @param obj {Object}
-
# @return {String}
-
1
def inspect_obj(obj)
-
return obj.inspect unless version_geq(::RUBY_VERSION, "1.9.2")
-
return ':' + inspect_obj(obj.to_s) if obj.is_a?(Symbol)
-
return obj.inspect unless obj.is_a?(String)
-
'"' + obj.gsub(/[\x00-\x7F]+/) {|s| s.inspect[1...-1]} + '"'
-
end
-
-
# Extracts the non-string vlaues from an array containing both strings and non-strings.
-
# These values are replaced with escape sequences.
-
# This can be undone using \{#inject\_values}.
-
#
-
# This is useful e.g. when we want to do string manipulation
-
# on an interpolated string.
-
#
-
# The precise format of the resulting string is not guaranteed.
-
# However, it is guaranteed that newlines and whitespace won't be affected.
-
#
-
# @param arr [Array] The array from which values are extracted.
-
# @return [(String, Array)] The resulting string, and an array of extracted values.
-
1
def extract_values(arr)
-
values = []
-
return arr.map do |e|
-
next e.gsub('{', '{{') if e.is_a?(String)
-
values << e
-
next "{#{values.count - 1}}"
-
end.join, values
-
end
-
-
# Undoes \{#extract\_values} by transforming a string with escape sequences
-
# into an array of strings and non-string values.
-
#
-
# @param str [String] The string with escape sequences.
-
# @param values [Array] The array of values to inject.
-
# @return [Array] The array of strings and values.
-
1
def inject_values(str, values)
-
return [str.gsub('{{', '{')] if values.empty?
-
# Add an extra { so that we process the tail end of the string
-
result = (str + '{{').scan(/(.*?)(?:(\{\{)|\{(\d+)\})/m).map do |(pre, esc, n)|
-
[pre, esc ? '{' : '', n ? values[n.to_i] : '']
-
end.flatten(1)
-
result[-2] = '' # Get rid of the extra {
-
merge_adjacent_strings(result).reject {|s| s == ''}
-
end
-
-
# Allows modifications to be performed on the string form
-
# of an array containing both strings and non-strings.
-
#
-
# @param arr [Array] The array from which values are extracted.
-
# @yield [str] A block in which string manipulation can be done to the array.
-
# @yieldparam str [String] The string form of `arr`.
-
# @yieldreturn [String] The modified string.
-
# @return [Array] The modified, interpolated array.
-
1
def with_extracted_values(arr)
-
str, vals = extract_values(arr)
-
str = yield str
-
inject_values(str, vals)
-
end
-
-
## Static Method Stuff
-
-
# The context in which the ERB for \{#def\_static\_method} will be run.
-
1
class StaticConditionalContext
-
# @param set [#include?] The set of variables that are defined for this context.
-
1
def initialize(set)
-
@set = set
-
end
-
-
# Checks whether or not a variable is defined for this context.
-
#
-
# @param name [Symbol] The name of the variable
-
# @return [Boolean]
-
1
def method_missing(name, *args, &block)
-
super unless args.empty? && block.nil?
-
@set.include?(name)
-
end
-
end
-
-
# @private
-
1
ATOMIC_WRITE_MUTEX = Mutex.new
-
-
-
# This creates a temp file and yields it for writing. When the
-
# write is complete, the file is moved into the desired location.
-
# The atomicity of this operation is provided by the filesystem's
-
# rename operation.
-
#
-
# @param filename [String] The file to write to.
-
# @param perms [Integer] The permissions used for creating this file.
-
# Will be masked by the process umask. Defaults to readable/writeable
-
# by all users however the umask usually changes this to only be writable
-
# by the process's user.
-
# @yieldparam tmpfile [Tempfile] The temp file that can be written to.
-
# @return The value returned by the block.
-
1
def atomic_create_and_write_file(filename, perms = 0666)
-
require 'tempfile'
-
tmpfile = Tempfile.new(File.basename(filename), File.dirname(filename))
-
tmpfile.binmode if tmpfile.respond_to?(:binmode)
-
result = yield tmpfile
-
tmpfile.flush # ensure all writes are flushed to the OS
-
begin
-
tmpfile.fsync # ensure all buffered data in the OS is sync'd to disk.
-
rescue NotImplementedError
-
# Not all OSes support fsync
-
end
-
tmpfile.close # Windows cannot rename an open file.
-
# Make file readable and writeable to all but respect umask (usually 022).
-
File.chmod(perms & ~File.umask, tmpfile.path)
-
ATOMIC_WRITE_MUTEX.synchronize do
-
File.rename tmpfile.path, filename
-
end
-
result
-
ensure
-
# close and remove the tempfile if it still exists,
-
# presumably due to an error during write
-
tmpfile.close if tmpfile
-
tmpfile.unlink if tmpfile
-
end
-
-
1
private
-
-
# Calculates the memoization table for the Least Common Subsequence algorithm.
-
# Algorithm from [Wikipedia](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Computing_the_length_of_the_LCS)
-
1
def lcs_table(x, y)
-
c = Array.new(x.size) {[]}
-
x.size.times {|i| c[i][0] = 0}
-
y.size.times {|j| c[0][j] = 0}
-
(1...x.size).each do |i|
-
(1...y.size).each do |j|
-
c[i][j] =
-
if yield x[i], y[j]
-
c[i-1][j-1] + 1
-
else
-
[c[i][j-1], c[i-1][j]].max
-
end
-
end
-
end
-
return c
-
end
-
-
# Computes a single longest common subsequence for arrays x and y.
-
# Algorithm from [Wikipedia](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Reading_out_an_LCS)
-
1
def lcs_backtrace(c, x, y, i, j, &block)
-
return [] if i == 0 || j == 0
-
if v = yield(x[i], y[j])
-
return lcs_backtrace(c, x, y, i-1, j-1, &block) << v
-
end
-
-
return lcs_backtrace(c, x, y, i, j-1, &block) if c[i][j-1] > c[i-1][j]
-
return lcs_backtrace(c, x, y, i-1, j, &block)
-
end
-
end
-
end
-
-
1
require 'sass/util/multibyte_string_scanner'
-
1
require 'strscan'
-
-
1
if Sass::Util.ruby1_8?
-
Sass::Util::MultibyteStringScanner = StringScanner
-
else
-
1
if Sass::Util.rbx?
-
# Rubinius's StringScanner class implements some of its methods in terms of
-
# others, which causes us to double-count bytes in some cases if we do
-
# straightforward inheritance. To work around this, we use a delegate class.
-
require 'delegate'
-
class Sass::Util::MultibyteStringScanner < DelegateClass(StringScanner)
-
def initialize(str)
-
super(StringScanner.new(str))
-
@mb_pos = 0
-
@mb_matched_size = nil
-
@mb_last_pos = nil
-
end
-
-
def is_a?(klass)
-
__getobj__.is_a?(klass) || super
-
end
-
end
-
else
-
1
class Sass::Util::MultibyteStringScanner < StringScanner
-
1
def initialize(str)
-
super
-
@mb_pos = 0
-
@mb_matched_size = nil
-
@mb_last_pos = nil
-
end
-
end
-
end
-
-
# A wrapper of the native StringScanner class that works correctly with
-
# multibyte character encodings. The native class deals only in bytes, not
-
# characters, for methods like [#pos] and [#matched_size]. This class deals
-
# only in characters, instead.
-
1
class Sass::Util::MultibyteStringScanner
-
1
def self.new(str)
-
return StringScanner.new(str) if str.ascii_only?
-
super
-
end
-
-
1
alias_method :byte_pos, :pos
-
1
alias_method :byte_matched_size, :matched_size
-
-
1
def check(pattern); _match super; end
-
1
def check_until(pattern); _matched super; end
-
1
def getch; _forward _match super; end
-
1
def match?(pattern); _size check(pattern); end
-
1
def matched_size; @mb_matched_size; end
-
1
def peek(len); string[@mb_pos, len]; end
-
1
alias_method :peep, :peek
-
1
def pos; @mb_pos; end
-
1
alias_method :pointer, :pos
-
1
def rest_size; rest.size; end
-
1
def scan(pattern); _forward _match super; end
-
1
def scan_until(pattern); _forward _matched super; end
-
1
def skip(pattern); _size scan(pattern); end
-
1
def skip_until(pattern); _matched _size scan_until(pattern); end
-
-
1
def get_byte
-
raise "MultibyteStringScanner doesn't support #get_byte."
-
end
-
-
1
def getbyte
-
raise "MultibyteStringScanner doesn't support #getbyte."
-
end
-
-
1
def pos=(n)
-
@mb_last_pos = nil
-
-
# We set position kind of a lot during parsing, so we want it to be as
-
# efficient as possible. This is complicated by the fact that UTF-8 is a
-
# variable-length encoding, so it's difficult to find the byte length that
-
# corresponds to a given character length.
-
#
-
# Our heuristic here is to try to count the fewest possible characters. So
-
# if the new position is close to the current one, just count the
-
# characters between the two; if the new position is closer to the
-
# beginning of the string, just count the characters from there.
-
if @mb_pos - n < @mb_pos / 2
-
# New position is close to old position
-
byte_delta = @mb_pos > n ? -string[n...@mb_pos].bytesize : string[@mb_pos...n].bytesize
-
super(byte_pos + byte_delta)
-
else
-
# New position is close to BOS
-
super(string[0...n].bytesize)
-
end
-
@mb_pos = n
-
end
-
-
1
def reset
-
@mb_pos = 0
-
@mb_matched_size = nil
-
@mb_last_pos = nil
-
super
-
end
-
-
1
def scan_full(pattern, advance_pointer_p, return_string_p)
-
res = _match super(pattern, advance_pointer_p, true)
-
_forward res if advance_pointer_p
-
return res if return_string_p
-
end
-
-
1
def search_full(pattern, advance_pointer_p, return_string_p)
-
res = super(pattern, advance_pointer_p, true)
-
_forward res if advance_pointer_p
-
_matched((res if return_string_p))
-
end
-
-
1
def string=(str)
-
@mb_pos = 0
-
@mb_matched_size = nil
-
@mb_last_pos = nil
-
super
-
end
-
-
1
def terminate
-
@mb_pos = string.size
-
@mb_matched_size = nil
-
@mb_last_pos = nil
-
super
-
end
-
1
alias_method :clear, :terminate
-
-
1
def unscan
-
super
-
@mb_pos = @mb_last_pos
-
@mb_last_pos = @mb_matched_size = nil
-
end
-
-
1
private
-
-
1
def _size(str)
-
str && str.size
-
end
-
-
1
def _match(str)
-
@mb_matched_size = str && str.size
-
str
-
end
-
-
1
def _matched(res)
-
_match matched
-
res
-
end
-
-
1
def _forward(str)
-
@mb_last_pos = @mb_pos
-
@mb_pos += str.size if str
-
str
-
end
-
end
-
end
-
1
require 'set'
-
-
1
module Sass
-
1
module Util
-
# A map from sets to values.
-
# A value is \{#\[]= set} by providing a set (the "set-set") and a value,
-
# which is then recorded as corresponding to that set.
-
# Values are \{#\[] accessed} by providing a set (the "get-set")
-
# and returning all values that correspond to set-sets
-
# that are subsets of the get-set.
-
#
-
# SubsetMap preserves the order of values as they're inserted.
-
#
-
# @example
-
# ssm = SubsetMap.new
-
# ssm[Set[1, 2]] = "Foo"
-
# ssm[Set[2, 3]] = "Bar"
-
# ssm[Set[1, 2, 3]] = "Baz"
-
#
-
# ssm[Set[1, 2, 3]] #=> ["Foo", "Bar", "Baz"]
-
1
class SubsetMap
-
# Creates a new, empty SubsetMap.
-
1
def initialize
-
@hash = {}
-
@vals = []
-
end
-
-
# Whether or not this SubsetMap has any key-value pairs.
-
#
-
# @return [Boolean]
-
1
def empty?
-
@hash.empty?
-
end
-
-
# Associates a value with a set.
-
# When `set` or any of its supersets is accessed,
-
# `value` will be among the values returned.
-
#
-
# Note that if the same `set` is passed to this method multiple times,
-
# all given `value`s will be associated with that `set`.
-
#
-
# This runs in `O(n)` time, where `n` is the size of `set`.
-
#
-
# @param set [#to_set] The set to use as the map key. May not be empty.
-
# @param value [Object] The value to associate with `set`.
-
# @raise [ArgumentError] If `set` is empty.
-
1
def []=(set, value)
-
raise ArgumentError.new("SubsetMap keys may not be empty.") if set.empty?
-
-
index = @vals.size
-
@vals << value
-
set.each do |k|
-
@hash[k] ||= []
-
@hash[k] << [set, set.to_set, index]
-
end
-
end
-
-
# Returns all values associated with subsets of `set`.
-
#
-
# In the worst case, this runs in `O(m*max(n, log m))` time,
-
# where `n` is the size of `set`
-
# and `m` is the number of assocations in the map.
-
# However, unless many keys in the map overlap with `set`,
-
# `m` will typically be much smaller.
-
#
-
# @param set [Set] The set to use as the map key.
-
# @return [Array<(Object, #to_set)>] An array of pairs,
-
# where the first value is the value associated with a subset of `set`,
-
# and the second value is that subset of `set`
-
# (or whatever `#to_set` object was used to set the value)
-
# This array is in insertion order.
-
# @see #[]
-
1
def get(set)
-
res = set.map do |k|
-
next unless subsets = @hash[k]
-
subsets.map do |subenum, subset, index|
-
next unless subset.subset?(set)
-
[index, subenum]
-
end
-
end
-
res = Sass::Util.flatten(res, 1)
-
res.compact!
-
res.uniq!
-
res.sort!
-
res.map! {|i, s| [@vals[i], s]}
-
return res
-
end
-
-
# Same as \{#get}, but doesn't return the subsets of the argument
-
# for which values were found.
-
#
-
# @param set [Set] The set to use as the map key.
-
# @return [Array] The array of all values
-
# associated with subsets of `set`, in insertion order.
-
# @see #get
-
1
def [](set)
-
get(set).map {|v, _| v}
-
end
-
-
# Iterates over each value in the subset map. Ignores keys completely. If
-
# multiple keys have the same value, this will return them multiple times.
-
#
-
# @yield [Object] Each value in the map.
-
1
def each_value
-
@vals.each {|v| yield v}
-
end
-
end
-
end
-
end
-
1
require 'date'
-
-
# This is necessary for loading Sass when Haml is required in Rails 3.
-
# Once the split is complete, we can remove it.
-
1
require File.dirname(__FILE__) + '/../sass'
-
1
require 'sass/util'
-
-
1
module Sass
-
# Handles Sass version-reporting.
-
# Sass not only reports the standard three version numbers,
-
# but its Git revision hash as well,
-
# if it was installed from Git.
-
1
module Version
-
1
include Sass::Util
-
-
# Returns a hash representing the version of Sass.
-
# The `:major`, `:minor`, and `:teeny` keys have their respective numbers as Fixnums.
-
# The `:name` key has the name of the version.
-
# The `:string` key contains a human-readable string representation of the version.
-
# The `:number` key is the major, minor, and teeny keys separated by periods.
-
# The `:date` key, which is not guaranteed to be defined, is the [DateTime] at which this release was cut.
-
# If Sass is checked out from Git, the `:rev` key will have the revision hash.
-
# For example:
-
#
-
# {
-
# :string => "2.1.0.9616393",
-
# :rev => "9616393b8924ef36639c7e82aa88a51a24d16949",
-
# :number => "2.1.0",
-
# :date => DateTime.parse("Apr 30 13:52:01 2009 -0700"),
-
# :major => 2, :minor => 1, :teeny => 0
-
# }
-
#
-
# If a prerelease version of Sass is being used,
-
# the `:string` and `:number` fields will reflect the full version
-
# (e.g. `"2.2.beta.1"`), and the `:teeny` field will be `-1`.
-
# A `:prerelease` key will contain the name of the prerelease (e.g. `"beta"`),
-
# and a `:prerelease_number` key will contain the rerelease number.
-
# For example:
-
#
-
# {
-
# :string => "3.0.beta.1",
-
# :number => "3.0.beta.1",
-
# :date => DateTime.parse("Mar 31 00:38:04 2010 -0700"),
-
# :major => 3, :minor => 0, :teeny => -1,
-
# :prerelease => "beta",
-
# :prerelease_number => 1
-
# }
-
#
-
# @return [{Symbol => String/Fixnum}] The version hash
-
1
def version
-
1
return @@version if defined?(@@version)
-
-
1
numbers = File.read(scope('VERSION')).strip.split('.').
-
3
map {|n| n =~ /^[0-9]+$/ ? n.to_i : n}
-
1
name = File.read(scope('VERSION_NAME')).strip
-
1
@@version = {
-
:major => numbers[0],
-
:minor => numbers[1],
-
:teeny => numbers[2],
-
:name => name
-
}
-
-
1
if date = version_date
-
1
@@version[:date] = date
-
end
-
-
1
if numbers[3].is_a?(String)
-
@@version[:teeny] = -1
-
@@version[:prerelease] = numbers[3]
-
@@version[:prerelease_number] = numbers[4]
-
end
-
-
1
@@version[:number] = numbers.join('.')
-
1
@@version[:string] = @@version[:number].dup
-
-
1
if rev = revision_number
-
@@version[:rev] = rev
-
unless rev[0] == ?(
-
@@version[:string] << "." << rev[0...7]
-
end
-
end
-
-
1
@@version[:string] << " (#{name})"
-
1
@@version
-
end
-
-
1
private
-
-
1
def revision_number
-
1
if File.exists?(scope('REVISION'))
-
1
rev = File.read(scope('REVISION')).strip
-
1
return rev unless rev =~ /^([a-f0-9]+|\(.*\))$/ || rev == '(unknown)'
-
end
-
-
1
return unless File.exists?(scope('.git/HEAD'))
-
rev = File.read(scope('.git/HEAD')).strip
-
return rev unless rev =~ /^ref: (.*)$/
-
-
ref_name = $1
-
ref_file = scope(".git/#{ref_name}")
-
info_file = scope(".git/info/refs")
-
return File.read(ref_file).strip if File.exists?(ref_file)
-
return unless File.exists?(info_file)
-
File.open(info_file) do |f|
-
f.each do |l|
-
sha, ref = l.strip.split("\t", 2)
-
next unless ref == ref_name
-
return sha
-
end
-
end
-
return nil
-
end
-
-
1
def version_date
-
1
return unless File.exists?(scope('VERSION_DATE'))
-
1
return DateTime.parse(File.read(scope('VERSION_DATE')).strip)
-
end
-
end
-
-
1
extend Sass::Version
-
-
# A string representing the version of Sass.
-
# A more fine-grained representation is available from Sass.version.
-
# @api public
-
1
VERSION = version[:string] unless defined?(Sass::VERSION)
-
end
-
1
module Sass
-
1
module Rails
-
1
autoload :Logger, 'sass/rails/logger'
-
end
-
end
-
-
1
require 'sass/rails/version'
-
1
require 'sass/rails/helpers'
-
1
require 'sass/rails/importer'
-
1
require 'sass/rails/template'
-
1
require 'sass/rails/railtie'
-
1
require 'sprockets/sass_functions'
-
1
require 'active_support/deprecation'
-
-
1
module Sprockets
-
1
module SassFunctions
-
1
if instance_methods.map(&:to_sym).include?(:asset_path)
-
1
undef_method :asset_path
-
end
-
-
1
def asset_path(path, kind = nil)
-
ActiveSupport::Deprecation.warn "asset_path with two arguments is deprecated. Use asset_path(#{path}) instead." if kind
-
-
Sass::Script::String.new(sprockets_context.asset_path(path.value), :string)
-
end
-
-
1
if instance_methods.map(&:to_sym).include?(:asset_url)
-
1
undef_method :asset_url
-
end
-
-
1
def asset_url(path, kind = nil)
-
ActiveSupport::Deprecation.warn "asset_url with two arguments is deprecated. Use asset_url(#{path}) instead." if kind
-
-
Sass::Script::String.new("url(" + sprockets_context.asset_path(path.value) + ")")
-
end
-
-
1
def asset_data_url(path)
-
Sass::Script::String.new("url(" + sprockets_context.asset_data_uri(path.value) + ")")
-
end
-
end
-
end
-
1
require 'sprockets/sass_importer'
-
-
1
module Sprockets
-
1
class SassImporter < Sass::Importers::Filesystem
-
1
GLOB = /\*|\[.+\]/
-
-
1
attr_reader :context
-
1
private :context
-
-
1
def extensions
-
{
-
'css' => :scss,
-
'css.scss' => :scss,
-
'css.sass' => :sass,
-
'css.erb' => :scss,
-
'scss.erb' => :scss,
-
'sass.erb' => :sass,
-
'css.scss.erb' => :scss,
-
'css.sass.erb' => :sass
-
}.merge!(super)
-
end
-
-
1
def find_relative(name, base, options)
-
if name =~ GLOB
-
glob_imports(name, Pathname.new(base), options)
-
else
-
engine_from_path(name, File.dirname(base), options)
-
end
-
end
-
-
1
def find(name, options)
-
if name =~ GLOB
-
nil # globs must be relative
-
else
-
engine_from_path(name, root, options)
-
end
-
end
-
-
1
def each_globbed_file(glob, base_pathname, options)
-
Dir["#{base_pathname}/#{glob}"].sort.each do |filename|
-
next if filename == options[:filename]
-
yield filename if File.directory?(filename) || context.asset_requirable?(filename)
-
end
-
end
-
-
1
def glob_imports(glob, base_pathname, options)
-
contents = ""
-
each_globbed_file(glob, base_pathname.dirname, options) do |filename|
-
if File.directory?(filename)
-
depend_on(filename)
-
elsif context.asset_requirable?(filename)
-
depend_on(filename)
-
contents << "@import #{Pathname.new(filename).relative_path_from(base_pathname.dirname).to_s.inspect};\n"
-
end
-
end
-
return nil if contents.empty?
-
Sass::Engine.new(contents, options.merge(
-
:filename => base_pathname.to_s,
-
:importer => self,
-
:syntax => :scss
-
))
-
end
-
-
1
private
-
-
1
def depend_on(filename)
-
context.depend_on(filename)
-
context.depend_on(globbed_file_parent(filename))
-
end
-
-
1
def globbed_file_parent(filename)
-
if File.directory?(filename)
-
File.expand_path('..', filename)
-
else
-
File.dirname(filename)
-
end
-
end
-
-
1
def engine_from_path(name, dir, options)
-
full_filename, syntax = Sass::Util.destructure(find_real_file(dir, name, options))
-
return unless full_filename && File.readable?(full_filename)
-
-
engine = Sass::Engine.new(evaluate(full_filename), options.merge(
-
syntax: syntax,
-
filename: full_filename,
-
importer: self
-
))
-
-
if engine && (filename = engine.options[:filename])
-
@context.depend_on(filename)
-
end
-
-
engine
-
end
-
-
1
def evaluate(filename)
-
attributes = context.environment.attributes_for(filename)
-
processors = context.environment.preprocessors(attributes.content_type) +
-
attributes.engines.reverse - [Sprockets::ScssTemplate, Sprockets::SassTemplate]
-
-
context.evaluate(filename, processors: processors)
-
end
-
end
-
end
-
1
require 'sass/logger'
-
-
1
module Sass
-
1
module Rails
-
1
class Logger < Sass::Logger::Base
-
1
def _log(level, message)
-
-
case level
-
when :trace, :debug
-
::Rails.logger.debug message
-
when :warn
-
::Rails.logger.warn message
-
when :error
-
::Rails.logger.error message
-
when :info
-
::Rails.logger.info message
-
end
-
end
-
end
-
end
-
end
-
1
require 'sprockets/railtie'
-
-
1
module Sass::Rails
-
1
class Railtie < ::Rails::Railtie
-
1
module SassContext
-
1
attr_accessor :sass_config
-
end
-
-
1
config.sass = ActiveSupport::OrderedOptions.new
-
-
# Establish static configuration defaults
-
# Emit scss files during stylesheet generation of scaffold
-
1
config.sass.preferred_syntax = :scss
-
# Write sass cache files for performance
-
1
config.sass.cache = true
-
# Read sass cache files for performance
-
1
config.sass.read_cache = true
-
# Display line comments above each selector as a debugging aid
-
1
config.sass.line_comments = true
-
# Initialize the load paths to an empty array
-
1
config.sass.load_paths = []
-
# Send Sass logs to Rails.logger
-
1
config.sass.logger = Sass::Rails::Logger.new
-
-
# Set the default stylesheet engine
-
# It can be overridedden by passing:
-
# --stylesheet_engine=sass
-
# to the rails generate command
-
1
config.app_generators.stylesheet_engine config.sass.preferred_syntax
-
-
# Remove the sass middleware if it gets inadvertently enabled by applications.
-
1
config.after_initialize do |app|
-
1
app.config.middleware.delete(Sass::Plugin::Rack) if defined?(Sass::Plugin::Rack)
-
end
-
-
1
initializer :setup_sass, group: :all do |app|
-
# Only emit one kind of syntax because though we have registered two kinds of generators
-
1
syntax = app.config.sass.preferred_syntax.to_sym
-
1
alt_syntax = syntax == :sass ? "scss" : "sass"
-
1
app.config.generators.hide_namespace alt_syntax
-
-
# Override stylesheet engine to the preferred syntax
-
1
config.app_generators.stylesheet_engine syntax
-
-
# Set the sass cache location
-
1
config.sass.cache_location = File.join(Rails.root, "tmp/cache/sass")
-
-
# Establish configuration defaults that are evironmental in nature
-
1
if config.sass.full_exception.nil?
-
# Display a stack trace in the css output when in development-like environments.
-
1
config.sass.full_exception = app.config.consider_all_requests_local
-
end
-
-
1
if app.assets
-
1
app.assets.context_class.extend(SassContext)
-
1
app.assets.context_class.sass_config = app.config.sass
-
end
-
-
1
Sass.logger = app.config.sass.logger
-
end
-
-
1
initializer :setup_compression, group: :all do |app|
-
1
unless Rails.env.development?
-
1
app.config.assets.css_compressor ||= :sass
-
else
-
# Use expanded output instead of the sass default of :nested unless specified
-
app.config.sass.style ||= :expanded
-
end
-
end
-
end
-
end
-
1
require "sprockets/sass_template"
-
-
1
module Sprockets
-
1
class SassTemplate
-
1
def evaluate(context, locals, &block)
-
cache_store = SassCacheStore.new(context.environment)
-
-
options = {
-
:filename => eval_file,
-
:line => line,
-
:syntax => syntax,
-
:cache_store => cache_store,
-
:importer => SassImporter.new(context, context.pathname),
-
:load_paths => context.environment.paths.map { |path| SassImporter.new(context, path) },
-
:sprockets => {
-
:context => context,
-
:environment => context.environment
-
}
-
}
-
-
sass_config = context.environment.context_class.sass_config.merge(options)
-
::Sass::Engine.new(data, sass_config).render
-
rescue ::Sass::SyntaxError => e
-
context.__LINE__ = e.sass_backtrace.first[:line]
-
raise e
-
end
-
end
-
end
-
1
module Sass
-
1
module Rails
-
1
VERSION = "4.0.3"
-
end
-
end
-
1
require 'sprockets/version'
-
-
1
module Sprockets
-
# Environment
-
1
autoload :Base, "sprockets/base"
-
1
autoload :Environment, "sprockets/environment"
-
1
autoload :Index, "sprockets/index"
-
1
autoload :Manifest, "sprockets/manifest"
-
-
# Assets
-
1
autoload :Asset, "sprockets/asset"
-
1
autoload :BundledAsset, "sprockets/bundled_asset"
-
1
autoload :ProcessedAsset, "sprockets/processed_asset"
-
1
autoload :StaticAsset, "sprockets/static_asset"
-
-
# Processing
-
1
autoload :Context, "sprockets/context"
-
1
autoload :EcoTemplate, "sprockets/eco_template"
-
1
autoload :EjsTemplate, "sprockets/ejs_template"
-
1
autoload :JstProcessor, "sprockets/jst_processor"
-
1
autoload :Processor, "sprockets/processor"
-
1
autoload :SassCacheStore, "sprockets/sass_cache_store"
-
1
autoload :SassFunctions, "sprockets/sass_functions"
-
1
autoload :SassImporter, "sprockets/sass_importer"
-
1
autoload :SassTemplate, "sprockets/sass_template"
-
1
autoload :ScssTemplate, "sprockets/scss_template"
-
-
# Internal utilities
-
1
autoload :ArgumentError, "sprockets/errors"
-
1
autoload :AssetAttributes, "sprockets/asset_attributes"
-
1
autoload :CircularDependencyError, "sprockets/errors"
-
1
autoload :ContentTypeMismatch, "sprockets/errors"
-
1
autoload :EngineError, "sprockets/errors"
-
1
autoload :Error, "sprockets/errors"
-
1
autoload :FileNotFound, "sprockets/errors"
-
1
autoload :Utils, "sprockets/utils"
-
-
1
module Cache
-
1
autoload :FileStore, "sprockets/cache/file_store"
-
end
-
-
# Extend Sprockets module to provide global registry
-
1
require 'hike'
-
1
require 'sprockets/engines'
-
1
require 'sprockets/mime'
-
1
require 'sprockets/processing'
-
1
require 'sprockets/compressing'
-
1
require 'sprockets/paths'
-
1
extend Engines, Mime, Processing, Compressing, Paths
-
-
1
@trail = Hike::Trail.new(File.expand_path('..', __FILE__))
-
1
@mime_types = {}
-
1
@engines = {}
-
3
@preprocessors = Hash.new { |h, k| h[k] = [] }
-
2
@postprocessors = Hash.new { |h, k| h[k] = [] }
-
2
@bundle_processors = Hash.new { |h, k| h[k] = [] }
-
3
@compressors = Hash.new { |h, k| h[k] = {} }
-
-
1
register_mime_type 'text/css', '.css'
-
1
register_mime_type 'application/javascript', '.js'
-
-
1
require 'sprockets/directive_processor'
-
1
register_preprocessor 'text/css', DirectiveProcessor
-
1
register_preprocessor 'application/javascript', DirectiveProcessor
-
-
1
require 'sprockets/safety_colons'
-
1
register_postprocessor 'application/javascript', SafetyColons
-
-
1
require 'sprockets/charset_normalizer'
-
1
register_bundle_processor 'text/css', CharsetNormalizer
-
-
1
require 'sprockets/sass_compressor'
-
1
register_compressor 'text/css', :sass, SassCompressor
-
1
register_compressor 'text/css', :scss, SassCompressor
-
-
1
require 'sprockets/yui_compressor'
-
1
register_compressor 'text/css', :yui, YUICompressor
-
-
1
require 'sprockets/closure_compressor'
-
1
register_compressor 'application/javascript', :closure, ClosureCompressor
-
-
1
require 'sprockets/uglifier_compressor'
-
1
register_compressor 'application/javascript', :uglifier, UglifierCompressor
-
1
register_compressor 'application/javascript', :uglify, UglifierCompressor
-
-
1
require 'sprockets/yui_compressor'
-
1
register_compressor 'application/javascript', :yui, YUICompressor
-
-
# Cherry pick the default Tilt engines that make sense for
-
# Sprockets. We don't need ones that only generate html like HAML.
-
-
# Mmm, CoffeeScript
-
1
register_engine '.coffee', Tilt::CoffeeScriptTemplate
-
-
# JST engines
-
1
register_engine '.jst', JstProcessor
-
1
register_engine '.eco', EcoTemplate
-
1
register_engine '.ejs', EjsTemplate
-
-
# CSS engines
-
1
register_engine '.less', Tilt::LessTemplate
-
1
register_engine '.sass', SassTemplate
-
1
register_engine '.scss', ScssTemplate
-
-
# Other
-
1
register_engine '.erb', Tilt::ERBTemplate
-
1
register_engine '.str', Tilt::StringTemplate
-
end
-
1
require 'time'
-
1
require 'set'
-
-
1
module Sprockets
-
# `Asset` is the base class for `BundledAsset` and `StaticAsset`.
-
1
class Asset
-
# Internal initializer to load `Asset` from serialized `Hash`.
-
1
def self.from_hash(environment, hash)
-
return unless hash.is_a?(Hash)
-
-
klass = case hash['class']
-
when 'BundledAsset'
-
BundledAsset
-
when 'ProcessedAsset'
-
ProcessedAsset
-
when 'StaticAsset'
-
StaticAsset
-
else
-
nil
-
end
-
-
if klass
-
asset = klass.allocate
-
asset.init_with(environment, hash)
-
asset
-
end
-
rescue UnserializeError
-
nil
-
end
-
-
1
attr_reader :logical_path, :pathname
-
1
attr_reader :content_type, :mtime, :length, :digest
-
1
alias_method :bytesize, :length
-
-
1
def initialize(environment, logical_path, pathname)
-
raise ArgumentError, "Asset logical path has no extension: #{logical_path}" if File.extname(logical_path) == ""
-
-
@root = environment.root
-
@logical_path = logical_path.to_s
-
@pathname = Pathname.new(pathname)
-
@content_type = environment.content_type_of(pathname)
-
# drop precision to 1 second, same pattern followed elsewhere
-
@mtime = Time.at(environment.stat(pathname).mtime.to_i)
-
@length = environment.stat(pathname).size
-
@digest = environment.file_digest(pathname).hexdigest
-
end
-
-
# Initialize `Asset` from serialized `Hash`.
-
1
def init_with(environment, coder)
-
@root = environment.root
-
-
@logical_path = coder['logical_path']
-
@content_type = coder['content_type']
-
@digest = coder['digest']
-
-
if pathname = coder['pathname']
-
# Expand `$root` placeholder and wrapper string in a `Pathname`
-
@pathname = Pathname.new(expand_root_path(pathname))
-
end
-
-
if mtime = coder['mtime']
-
@mtime = Time.at(mtime)
-
end
-
-
if length = coder['length']
-
# Convert length to an `Integer`
-
@length = Integer(length)
-
end
-
end
-
-
# Copy serialized attributes to the coder object
-
1
def encode_with(coder)
-
coder['class'] = self.class.name.sub(/Sprockets::/, '')
-
coder['logical_path'] = logical_path
-
coder['pathname'] = relativize_root_path(pathname).to_s
-
coder['content_type'] = content_type
-
coder['mtime'] = mtime.to_i
-
coder['length'] = length
-
coder['digest'] = digest
-
end
-
-
# Return logical path with digest spliced in.
-
#
-
# "foo/bar-37b51d194a7513e45b56f6524f2d51f2.js"
-
#
-
1
def digest_path
-
logical_path.sub(/\.(\w+)$/) { |ext| "-#{digest}#{ext}" }
-
end
-
-
# Return an `Array` of `Asset` files that are declared dependencies.
-
1
def dependencies
-
[]
-
end
-
-
# Expand asset into an `Array` of parts.
-
#
-
# Appending all of an assets body parts together should give you
-
# the asset's contents as a whole.
-
#
-
# This allows you to link to individual files for debugging
-
# purposes.
-
1
def to_a
-
[self]
-
end
-
-
# `body` is aliased to source by default if it can't have any dependencies.
-
1
def body
-
source
-
end
-
-
# Return `String` of concatenated source.
-
1
def to_s
-
source
-
end
-
-
# Add enumerator to allow `Asset` instances to be used as Rack
-
# compatible body objects.
-
1
def each
-
yield to_s
-
end
-
-
# Checks if Asset is fresh by comparing the actual mtime and
-
# digest to the inmemory model.
-
#
-
# Used to test if cached models need to be rebuilt.
-
1
def fresh?(environment)
-
# Check current mtime and digest
-
dependency_fresh?(environment, self)
-
end
-
-
# Checks if Asset is stale by comparing the actual mtime and
-
# digest to the inmemory model.
-
#
-
# Subclass must override `fresh?` or `stale?`.
-
1
def stale?(environment)
-
!fresh?(environment)
-
end
-
-
# Save asset to disk.
-
1
def write_to(filename, options = {})
-
# Gzip contents if filename has '.gz'
-
options[:compress] ||= File.extname(filename) == '.gz'
-
-
FileUtils.mkdir_p File.dirname(filename)
-
-
File.open("#{filename}+", 'wb') do |f|
-
if options[:compress]
-
# Run contents through `Zlib`
-
gz = Zlib::GzipWriter.new(f, Zlib::BEST_COMPRESSION)
-
gz.mtime = mtime.to_i
-
gz.write to_s
-
gz.close
-
else
-
# Write out as is
-
f.write to_s
-
end
-
end
-
-
# Atomic write
-
FileUtils.mv("#{filename}+", filename)
-
-
# Set mtime correctly
-
File.utime(mtime, mtime, filename)
-
-
nil
-
ensure
-
# Ensure tmp file gets cleaned up
-
FileUtils.rm("#{filename}+") if File.exist?("#{filename}+")
-
end
-
-
# Pretty inspect
-
1
def inspect
-
"#<#{self.class}:0x#{object_id.to_s(16)} " +
-
"pathname=#{pathname.to_s.inspect}, " +
-
"mtime=#{mtime.inspect}, " +
-
"digest=#{digest.inspect}" +
-
">"
-
end
-
-
1
def hash
-
digest.hash
-
end
-
-
# Assets are equal if they share the same path, mtime and digest.
-
1
def eql?(other)
-
other.class == self.class &&
-
other.logical_path == self.logical_path &&
-
other.mtime.to_i == self.mtime.to_i &&
-
other.digest == self.digest
-
end
-
1
alias_method :==, :eql?
-
-
1
protected
-
# Internal: String paths that are marked as dependencies after processing.
-
#
-
# Default to an empty `Array`.
-
1
def dependency_paths
-
@dependency_paths ||= []
-
end
-
-
# Internal: `ProccessedAsset`s that are required after processing.
-
#
-
# Default to an empty `Array`.
-
1
def required_assets
-
@required_assets ||= []
-
end
-
-
# Get pathname with its root stripped.
-
1
def relative_pathname
-
@relative_pathname ||= Pathname.new(relativize_root_path(pathname))
-
end
-
-
# Replace `$root` placeholder with actual environment root.
-
1
def expand_root_path(path)
-
path.to_s.sub(/^\$root/, @root)
-
end
-
-
# Replace actual environment root with `$root` placeholder.
-
1
def relativize_root_path(path)
-
path.to_s.sub(/^#{Regexp.escape(@root)}/, '$root')
-
end
-
-
# Check if dependency is fresh.
-
#
-
# `dep` is a `Hash` with `path`, `mtime` and `hexdigest` keys.
-
#
-
# A `Hash` is used rather than other `Asset` object because we
-
# want to test non-asset files and directories.
-
1
def dependency_fresh?(environment, dep)
-
path, mtime, hexdigest = dep.pathname.to_s, dep.mtime, dep.digest
-
-
stat = environment.stat(path)
-
-
# If path no longer exists, its definitely stale.
-
if stat.nil?
-
return false
-
end
-
-
# Compare dependency mtime to the actual mtime. If the
-
# dependency mtime is newer than the actual mtime, the file
-
# hasn't changed since we created this `Asset` instance.
-
#
-
# However, if the mtime is newer it doesn't mean the asset is
-
# stale. Many deployment environments may recopy or recheckout
-
# assets on each deploy. In this case the mtime would be the
-
# time of deploy rather than modified time.
-
#
-
# Note: to_i is used in eql? and write_to we assume fidelity of 1 second
-
# if people save files more frequently than 1 second sprockets may
-
# not pick it up, by design
-
if mtime.to_i >= stat.mtime.to_i
-
return true
-
end
-
-
digest = environment.file_digest(path)
-
-
# If the mtime is newer, do a full digest comparsion. Return
-
# fresh if the digests match.
-
if hexdigest == digest.hexdigest
-
return true
-
end
-
-
# Otherwise, its stale.
-
false
-
end
-
end
-
end
-
1
require 'pathname'
-
-
1
module Sprockets
-
# `AssetAttributes` is a wrapper similar to `Pathname` that provides
-
# some helper accessors.
-
#
-
# These methods should be considered internalish.
-
1
class AssetAttributes
-
1
attr_reader :environment, :pathname
-
-
1
def initialize(environment, path)
-
@environment = environment
-
@pathname = path.is_a?(Pathname) ? path : Pathname.new(path.to_s)
-
end
-
-
# Returns paths search the load path for.
-
1
def search_paths
-
paths = [pathname.to_s]
-
-
extension = format_extension
-
path_without_extension = extension ?
-
pathname.sub(extension, '') :
-
pathname
-
-
# optimization: bower.json can only be nested one level deep
-
if !path_without_extension.to_s.index('/')
-
paths << path_without_extension.join(".bower.json").to_s
-
paths << path_without_extension.join("bower.json").to_s
-
# DEPRECATED bower configuration file
-
paths << path_without_extension.join("component.json").to_s
-
end
-
-
if pathname.basename(extension.to_s).to_s != 'index'
-
paths << path_without_extension.join("index#{extension}").to_s
-
end
-
-
paths
-
end
-
-
# Reverse guess logical path for fully expanded path.
-
#
-
# This has some known issues. For an example if a file is
-
# shaddowed in the path, but is required relatively, its logical
-
# path will be incorrect.
-
1
def logical_path
-
if root_path = environment.paths.detect { |path| pathname.to_s[path] }
-
path = pathname.to_s.sub("#{root_path}/", '')
-
path = pathname.relative_path_from(Pathname.new(root_path)).to_s
-
path = engine_extensions.inject(path) { |p, ext| p.sub(ext, '') }
-
path = "#{path}#{engine_format_extension}" unless format_extension
-
path
-
else
-
raise FileOutsidePaths, "#{pathname} isn't in paths: #{environment.paths.join(', ')}"
-
end
-
end
-
-
# Returns `Array` of extension `String`s.
-
#
-
# "foo.js.coffee"
-
# # => [".js", ".coffee"]
-
#
-
1
def extensions
-
@extensions ||= @pathname.basename.to_s.scan(/\.[^.]+/)
-
end
-
-
# Returns the format extension.
-
#
-
# "foo.js.coffee"
-
# # => ".js"
-
#
-
1
def format_extension
-
extensions.reverse.detect { |ext|
-
@environment.mime_types(ext) && !@environment.engines(ext)
-
}
-
end
-
-
# Returns an `Array` of engine extensions.
-
#
-
# "foo.js.coffee.erb"
-
# # => [".coffee", ".erb"]
-
#
-
1
def engine_extensions
-
exts = extensions
-
-
if offset = extensions.index(format_extension)
-
exts = extensions[offset+1..-1]
-
end
-
-
exts.select { |ext| @environment.engines(ext) }
-
end
-
-
# Returns engine classes.
-
1
def engines
-
engine_extensions.map { |ext| @environment.engines(ext) }
-
end
-
-
# Returns all processors to run on the path.
-
1
def processors
-
environment.preprocessors(content_type) +
-
engines.reverse +
-
environment.postprocessors(content_type)
-
end
-
-
# Returns the content type for the pathname. Falls back to `application/octet-stream`.
-
1
def content_type
-
@content_type ||= begin
-
if format_extension.nil?
-
engine_content_type || 'application/octet-stream'
-
else
-
@environment.mime_types(format_extension) ||
-
engine_content_type ||
-
'application/octet-stream'
-
end
-
end
-
end
-
-
1
private
-
# Returns implicit engine content type.
-
#
-
# `.coffee` files carry an implicit `application/javascript`
-
# content type.
-
1
def engine_content_type
-
engines.reverse.each do |engine|
-
if engine.respond_to?(:default_mime_type) && engine.default_mime_type
-
return engine.default_mime_type
-
end
-
end
-
nil
-
end
-
-
1
def engine_format_extension
-
if content_type = engine_content_type
-
environment.extension_for_mime_type(content_type)
-
end
-
end
-
end
-
end
-
1
require 'sprockets/asset_attributes'
-
1
require 'sprockets/bundled_asset'
-
1
require 'sprockets/caching'
-
1
require 'sprockets/errors'
-
1
require 'sprockets/processed_asset'
-
1
require 'sprockets/server'
-
1
require 'sprockets/static_asset'
-
1
require 'multi_json'
-
1
require 'pathname'
-
-
1
module Sprockets
-
# `Base` class for `Environment` and `Index`.
-
1
class Base
-
1
include Caching, Paths, Mime, Processing, Compressing, Engines, Server
-
-
# Returns a `Digest` implementation class.
-
#
-
# Defaults to `Digest::MD5`.
-
1
attr_reader :digest_class
-
-
# Assign a `Digest` implementation class. This maybe any Ruby
-
# `Digest::` implementation such as `Digest::MD5` or
-
# `Digest::SHA1`.
-
#
-
# environment.digest_class = Digest::SHA1
-
#
-
1
def digest_class=(klass)
-
expire_index!
-
@digest_class = klass
-
end
-
-
# The `Environment#version` is a custom value used for manually
-
# expiring all asset caches.
-
#
-
# Sprockets is able to track most file and directory changes and
-
# will take care of expiring the cache for you. However, its
-
# impossible to know when any custom helpers change that you mix
-
# into the `Context`.
-
#
-
# It would be wise to increment this value anytime you make a
-
# configuration change to the `Environment` object.
-
1
attr_reader :version
-
-
# Assign an environment version.
-
#
-
# environment.version = '2.0'
-
#
-
1
def version=(version)
-
2
expire_index!
-
2
@version = version
-
end
-
-
# Returns a `Digest` instance for the `Environment`.
-
#
-
# This value serves two purposes. If two `Environment`s have the
-
# same digest value they can be treated as equal. This is more
-
# useful for comparing environment states between processes rather
-
# than in the same. Two equal `Environment`s can share the same
-
# cached assets.
-
#
-
# The value also provides a seed digest for all `Asset`
-
# digests. Any change in the environment digest will affect all of
-
# its assets.
-
1
def digest
-
# Compute the initial digest using the implementation class. The
-
# Sprockets release version and custom environment version are
-
# mixed in. So any new releases will affect all your assets.
-
1
@digest ||= digest_class.new.update(VERSION).update(version.to_s)
-
-
# Returned a dupped copy so the caller can safely mutate it with `.update`
-
1
@digest.dup
-
end
-
-
# Get and set `Logger` instance.
-
1
attr_accessor :logger
-
-
# Get `Context` class.
-
#
-
# This class maybe mutated and mixed in with custom helpers.
-
#
-
# environment.context_class.instance_eval do
-
# include MyHelpers
-
# def asset_url; end
-
# end
-
#
-
1
attr_reader :context_class
-
-
# Get persistent cache store
-
1
attr_reader :cache
-
-
# Set persistent cache store
-
#
-
# The cache store must implement a pair of getters and
-
# setters. Either `get(key)`/`set(key, value)`,
-
# `[key]`/`[key]=value`, `read(key)`/`write(key, value)`.
-
1
def cache=(cache)
-
1
expire_index!
-
1
@cache = cache
-
end
-
-
1
def prepend_path(path)
-
# Overrides the global behavior to expire the index
-
expire_index!
-
super
-
end
-
-
1
def append_path(path)
-
# Overrides the global behavior to expire the index
-
28
expire_index!
-
28
super
-
end
-
-
1
def clear_paths
-
# Overrides the global behavior to expire the index
-
expire_index!
-
super
-
end
-
-
# Finds the expanded real path for a given logical path by
-
# searching the environment's paths.
-
#
-
# resolve("application.js")
-
# # => "/path/to/app/javascripts/application.js.coffee"
-
#
-
# A `FileNotFound` exception is raised if the file does not exist.
-
1
def resolve(logical_path, options = {})
-
# If a block is given, preform an iterable search
-
if block_given?
-
args = attributes_for(logical_path).search_paths + [options]
-
@trail.find(*args) do |path|
-
pathname = Pathname.new(path)
-
if %w( .bower.json bower.json component.json ).include?(pathname.basename.to_s)
-
bower = json_decode(pathname.read)
-
case bower['main']
-
when String
-
yield pathname.dirname.join(bower['main'])
-
when Array
-
extname = File.extname(logical_path)
-
bower['main'].each do |fn|
-
if extname == "" || extname == File.extname(fn)
-
yield pathname.dirname.join(fn)
-
end
-
end
-
end
-
else
-
yield pathname
-
end
-
end
-
else
-
resolve(logical_path, options) do |pathname|
-
return pathname
-
end
-
raise FileNotFound, "couldn't find file '#{logical_path}'"
-
end
-
end
-
-
# Register a new mime type.
-
1
def register_mime_type(mime_type, ext)
-
# Overrides the global behavior to expire the index
-
expire_index!
-
@trail.append_extension(ext)
-
super
-
end
-
-
# Registers a new Engine `klass` for `ext`.
-
1
def register_engine(ext, klass)
-
# Overrides the global behavior to expire the index
-
2
expire_index!
-
2
add_engine_to_trail(ext, klass)
-
2
super
-
end
-
-
1
def register_preprocessor(mime_type, klass, &block)
-
# Overrides the global behavior to expire the index
-
expire_index!
-
super
-
end
-
-
1
def unregister_preprocessor(mime_type, klass)
-
# Overrides the global behavior to expire the index
-
expire_index!
-
super
-
end
-
-
1
def register_postprocessor(mime_type, klass, &block)
-
# Overrides the global behavior to expire the index
-
expire_index!
-
super
-
end
-
-
1
def unregister_postprocessor(mime_type, klass)
-
# Overrides the global behavior to expire the index
-
expire_index!
-
super
-
end
-
-
1
def register_bundle_processor(mime_type, klass, &block)
-
# Overrides the global behavior to expire the index
-
1
expire_index!
-
1
super
-
end
-
-
1
def unregister_bundle_processor(mime_type, klass)
-
# Overrides the global behavior to expire the index
-
expire_index!
-
super
-
end
-
-
# Return an `Index`. Must be implemented by the subclass.
-
1
def index
-
raise NotImplementedError
-
end
-
-
1
if defined? Encoding.default_external
-
# Define `default_external_encoding` accessor on 1.9.
-
# Defaults to UTF-8.
-
1
attr_accessor :default_external_encoding
-
end
-
-
# Works like `Dir.entries`.
-
#
-
# Subclasses may cache this method.
-
1
def entries(pathname)
-
@trail.entries(pathname)
-
end
-
-
# Works like `File.stat`.
-
#
-
# Subclasses may cache this method.
-
1
def stat(path)
-
@trail.stat(path)
-
end
-
-
# Read and compute digest of filename.
-
#
-
# Subclasses may cache this method.
-
1
def file_digest(path)
-
if stat = self.stat(path)
-
# If its a file, digest the contents
-
if stat.file?
-
digest.file(path.to_s)
-
-
# If its a directive, digest the list of filenames
-
elsif stat.directory?
-
contents = self.entries(path).join(',')
-
digest.update(contents)
-
end
-
end
-
end
-
-
# Internal. Return a `AssetAttributes` for `path`.
-
1
def attributes_for(path)
-
AssetAttributes.new(self, path)
-
end
-
-
# Internal. Return content type of `path`.
-
1
def content_type_of(path)
-
attributes_for(path).content_type
-
end
-
-
# Find asset by logical path or expanded path.
-
1
def find_asset(path, options = {})
-
logical_path = path
-
pathname = Pathname.new(path)
-
-
if pathname.absolute?
-
return unless stat(pathname)
-
logical_path = attributes_for(pathname).logical_path
-
else
-
begin
-
pathname = resolve(logical_path)
-
-
# If logical path is missing a mime type extension, append
-
# the absolute path extname so it has one.
-
#
-
# Ensures some consistency between finding "foo/bar" vs
-
# "foo/bar.js".
-
if File.extname(logical_path) == ""
-
expanded_logical_path = attributes_for(pathname).logical_path
-
logical_path += File.extname(expanded_logical_path)
-
end
-
rescue FileNotFound
-
return nil
-
end
-
end
-
-
build_asset(logical_path, pathname, options)
-
end
-
-
# Preferred `find_asset` shorthand.
-
#
-
# environment['application.js']
-
#
-
1
def [](*args)
-
find_asset(*args)
-
end
-
-
1
def each_entry(root, &block)
-
return to_enum(__method__, root) unless block_given?
-
root = Pathname.new(root) unless root.is_a?(Pathname)
-
-
paths = []
-
entries(root).sort.each do |filename|
-
path = root.join(filename)
-
paths << path
-
-
if stat(path).directory?
-
each_entry(path) do |subpath|
-
paths << subpath
-
end
-
end
-
end
-
-
paths.sort_by(&:to_s).each(&block)
-
-
nil
-
end
-
-
1
def each_file
-
return to_enum(__method__) unless block_given?
-
paths.each do |root|
-
each_entry(root) do |path|
-
if !stat(path).directory?
-
yield path
-
end
-
end
-
end
-
nil
-
end
-
-
1
def each_logical_path(*args, &block)
-
return to_enum(__method__, *args) unless block_given?
-
filters = args.flatten
-
files = {}
-
each_file do |filename|
-
if logical_path = logical_path_for_filename(filename, filters)
-
unless files[logical_path]
-
if block.arity == 2
-
yield logical_path, filename.to_s
-
else
-
yield logical_path
-
end
-
end
-
-
files[logical_path] = true
-
end
-
end
-
nil
-
end
-
-
# Pretty inspect
-
1
def inspect
-
"#<#{self.class}:0x#{object_id.to_s(16)} " +
-
"root=#{root.to_s.inspect}, " +
-
"paths=#{paths.inspect}, " +
-
"digest=#{digest.to_s.inspect}" +
-
">"
-
end
-
-
1
protected
-
# Clear index after mutating state. Must be implemented by the subclass.
-
1
def expire_index!
-
raise NotImplementedError
-
end
-
-
1
def build_asset(logical_path, pathname, options)
-
pathname = Pathname.new(pathname)
-
-
# If there are any processors to run on the pathname, use
-
# `BundledAsset`. Otherwise use `StaticAsset` and treat is as binary.
-
if attributes_for(pathname).processors.any?
-
if options[:bundle] == false
-
circular_call_protection(pathname.to_s) do
-
ProcessedAsset.new(index, logical_path, pathname)
-
end
-
else
-
BundledAsset.new(index, logical_path, pathname)
-
end
-
else
-
StaticAsset.new(index, logical_path, pathname)
-
end
-
end
-
-
1
def cache_key_for(path, options)
-
"#{path}:#{options[:bundle] ? '1' : '0'}"
-
end
-
-
1
def circular_call_protection(path)
-
reset = Thread.current[:sprockets_circular_calls].nil?
-
calls = Thread.current[:sprockets_circular_calls] ||= Set.new
-
if calls.include?(path)
-
raise CircularDependencyError, "#{path} has already been required"
-
end
-
calls << path
-
yield
-
ensure
-
Thread.current[:sprockets_circular_calls] = nil if reset
-
end
-
-
1
def logical_path_for_filename(filename, filters)
-
logical_path = attributes_for(filename).logical_path.to_s
-
-
if matches_filter(filters, logical_path, filename)
-
return logical_path
-
end
-
-
# If filename is an index file, retest with alias
-
if File.basename(logical_path)[/[^\.]+/, 0] == 'index'
-
path = logical_path.sub(/\/index\./, '.')
-
if matches_filter(filters, path, filename)
-
return path
-
end
-
end
-
-
nil
-
end
-
-
1
def matches_filter(filters, logical_path, filename)
-
return true if filters.empty?
-
-
filters.any? do |filter|
-
if filter.is_a?(Regexp)
-
filter.match(logical_path)
-
elsif filter.respond_to?(:call)
-
if filter.arity == 1
-
filter.call(logical_path)
-
else
-
filter.call(logical_path, filename.to_s)
-
end
-
else
-
File.fnmatch(filter.to_s, logical_path)
-
end
-
end
-
end
-
-
# Feature detect newer MultiJson API
-
1
if MultiJson.respond_to?(:dump)
-
1
def json_decode(obj)
-
MultiJson.load(obj)
-
end
-
else
-
def json_decode(obj)
-
MultiJson.decode(obj)
-
end
-
end
-
end
-
end
-
1
require 'sprockets/asset'
-
1
require 'sprockets/errors'
-
1
require 'fileutils'
-
1
require 'set'
-
1
require 'zlib'
-
-
1
module Sprockets
-
# `BundledAsset`s are used for files that need to be processed and
-
# concatenated with other assets. Use for `.js` and `.css` files.
-
1
class BundledAsset < Asset
-
1
attr_reader :source
-
-
1
def initialize(environment, logical_path, pathname)
-
super(environment, logical_path, pathname)
-
-
@processed_asset = environment.find_asset(pathname, :bundle => false)
-
@required_assets = @processed_asset.required_assets
-
@dependency_paths = @processed_asset.dependency_paths
-
-
# Explode Asset into parts and gather the dependency bodies
-
@source = to_a.map { |dependency| dependency.to_s }.join
-
-
# Run bundle processors on concatenated source
-
context = environment.context_class.new(environment, logical_path, pathname)
-
@source = context.evaluate(pathname, :data => @source,
-
:processors => environment.bundle_processors(content_type))
-
-
@mtime = (to_a + @dependency_paths).map(&:mtime).max
-
@length = Rack::Utils.bytesize(source)
-
@digest = environment.digest.update(source).hexdigest
-
end
-
-
# Initialize `BundledAsset` from serialized `Hash`.
-
1
def init_with(environment, coder)
-
super
-
-
@processed_asset = environment.find_asset(pathname, :bundle => false)
-
@required_assets = @processed_asset.required_assets
-
-
if @processed_asset.dependency_digest != coder['required_assets_digest']
-
raise UnserializeError, "processed asset belongs to a stale environment"
-
end
-
-
@source = coder['source']
-
end
-
-
# Serialize custom attributes in `BundledAsset`.
-
1
def encode_with(coder)
-
super
-
-
coder['source'] = source
-
coder['required_assets_digest'] = @processed_asset.dependency_digest
-
end
-
-
# Get asset's own processed contents. Excludes any of its required
-
# dependencies but does run any processors or engines on the
-
# original file.
-
1
def body
-
@processed_asset.source
-
end
-
-
# Return an `Array` of `Asset` files that are declared dependencies.
-
1
def dependencies
-
to_a.reject { |a| a.eql?(@processed_asset) }
-
end
-
-
# Expand asset into an `Array` of parts.
-
1
def to_a
-
required_assets
-
end
-
-
# Checks if Asset is stale by comparing the actual mtime and
-
# digest to the inmemory model.
-
1
def fresh?(environment)
-
@processed_asset.fresh?(environment)
-
end
-
end
-
end
-
1
require 'digest/md5'
-
1
require 'fileutils'
-
1
require 'pathname'
-
-
1
module Sprockets
-
1
module Cache
-
# A simple file system cache store.
-
#
-
# environment.cache = Sprockets::Cache::FileStore.new("/tmp")
-
#
-
1
class FileStore
-
1
def initialize(root)
-
1
@root = Pathname.new(root)
-
end
-
-
# Lookup value in cache
-
1
def [](key)
-
pathname = @root.join(key)
-
pathname.exist? ? pathname.open('rb') { |f| Marshal.load(f) } : nil
-
end
-
-
# Save value to cache
-
1
def []=(key, value)
-
# Ensure directory exists
-
FileUtils.mkdir_p @root.join(key).dirname
-
-
@root.join(key).open('w') { |f| Marshal.dump(value, f)}
-
value
-
end
-
end
-
end
-
end
-
1
module Sprockets
-
# `Caching` is an internal mixin whose public methods are exposed on
-
# the `Environment` and `Index` classes.
-
1
module Caching
-
# Low level cache getter for `key`. Checks a number of supported
-
# cache interfaces.
-
1
def cache_get(key)
-
# `Cache#get(key)` for Memcache
-
if cache.respond_to?(:get)
-
cache.get(key)
-
-
# `Cache#[key]` so `Hash` can be used
-
elsif cache.respond_to?(:[])
-
cache[key]
-
-
# `Cache#read(key)` for `ActiveSupport::Cache` support
-
elsif cache.respond_to?(:read)
-
cache.read(key)
-
-
else
-
nil
-
end
-
end
-
-
# Low level cache setter for `key`. Checks a number of supported
-
# cache interfaces.
-
1
def cache_set(key, value)
-
# `Cache#set(key, value)` for Memcache
-
if cache.respond_to?(:set)
-
cache.set(key, value)
-
-
# `Cache#[key]=value` so `Hash` can be used
-
elsif cache.respond_to?(:[]=)
-
cache[key] = value
-
-
# `Cache#write(key, value)` for `ActiveSupport::Cache` support
-
elsif cache.respond_to?(:write)
-
cache.write(key, value)
-
end
-
-
value
-
end
-
-
1
protected
-
# Cache helper method. Takes a `path` argument which maybe a
-
# logical path or fully expanded path. The `&block` is passed
-
# for finding and building the asset if its not in cache.
-
1
def cache_asset(path)
-
# If `cache` is not set, return fast
-
if cache.nil?
-
yield
-
-
# Check cache for `path`
-
elsif (asset = Asset.from_hash(self, cache_get_hash(path.to_s))) && asset.fresh?(self)
-
asset
-
-
# Otherwise yield block that slowly finds and builds the asset
-
elsif asset = yield
-
hash = {}
-
asset.encode_with(hash)
-
-
# Save the asset to its path
-
cache_set_hash(path.to_s, hash)
-
-
# Since path maybe a logical or full pathname, save the
-
# asset its its full path too
-
if path.to_s != asset.pathname.to_s
-
cache_set_hash(asset.pathname.to_s, hash)
-
end
-
-
asset
-
end
-
end
-
-
1
private
-
# Strips `Environment#root` from key to make the key work
-
# consisently across different servers. The key is also hashed
-
# so it does not exceed 250 characters.
-
1
def expand_cache_key(key)
-
File.join('sprockets', digest_class.hexdigest(key.sub(root, '')))
-
end
-
-
1
def cache_get_hash(key)
-
hash = cache_get(expand_cache_key(key))
-
if hash.is_a?(Hash) && digest.hexdigest == hash['_version']
-
hash
-
end
-
end
-
-
1
def cache_set_hash(key, hash)
-
hash['_version'] = digest.hexdigest
-
cache_set(expand_cache_key(key), hash)
-
hash
-
end
-
end
-
end
-
1
require 'tilt'
-
-
1
module Sprockets
-
# Some browsers have issues with stylesheets that contain multiple
-
# `@charset` definitions. The issue surfaces while using Sass since
-
# it inserts a `@charset` at the top of each file. Then Sprockets
-
# concatenates them together.
-
#
-
# The `CharsetNormalizer` processor strips out multiple `@charset`
-
# definitions.
-
#
-
# The current implementation is naive. It picks the first `@charset`
-
# it sees and strips the others. This works for most people because
-
# the other definitions are usually `UTF-8`. A more sophisticated
-
# approach would be to re-encode stylesheets with mixed encodings.
-
#
-
# This behavior can be disabled with:
-
#
-
# environment.unregister_bundle_processor 'text/css', Sprockets::CharsetNormalizer
-
#
-
1
class CharsetNormalizer < Tilt::Template
-
1
def prepare
-
end
-
-
1
def evaluate(context, locals, &block)
-
charset = nil
-
-
# Find and strip out any `@charset` definitions
-
filtered_data = data.gsub(/^@charset "([^"]+)";$/) {
-
charset ||= $1; ""
-
}
-
-
if charset
-
# If there was a charset, move it to the top
-
"@charset \"#{charset}\";#{filtered_data}"
-
else
-
data
-
end
-
end
-
end
-
end
-
1
require 'tilt'
-
-
1
module Sprockets
-
1
class ClosureCompressor < Tilt::Template
-
1
self.default_mime_type = 'application/javascript'
-
-
1
def self.engine_initialized?
-
defined?(::Closure::Compiler)
-
end
-
-
1
def initialize_engine
-
require_template_library 'closure-compiler'
-
end
-
-
1
def prepare
-
end
-
-
1
def evaluate(context, locals, &block)
-
Closure::Compiler.new.compile(data)
-
end
-
end
-
end
-
1
module Sprockets
-
# `Compressing` is an internal mixin whose public methods are exposed on
-
# the `Environment` and `Index` classes.
-
1
module Compressing
-
1
def compressors
-
3
deep_copy_hash(@compressors)
-
end
-
-
1
def register_compressor(mime_type, sym, klass)
-
7
@compressors[mime_type][sym] = klass
-
end
-
-
# Return CSS compressor or nil if none is set
-
1
def css_compressor
-
1
@css_compressor if defined? @css_compressor
-
end
-
-
# Assign a compressor to run on `text/css` assets.
-
#
-
# The compressor object must respond to `compress`.
-
1
def css_compressor=(compressor)
-
1
unregister_bundle_processor 'text/css', css_compressor if css_compressor
-
1
@css_compressor = nil
-
1
return unless compressor
-
-
1
if compressor.is_a?(Symbol)
-
1
compressor = compressors['text/css'][compressor] || raise(Error, "unknown compressor: #{compressor}")
-
end
-
-
1
if compressor.respond_to?(:compress)
-
klass = Class.new(Processor) do
-
@name = "css_compressor"
-
@processor = proc { |context, data| compressor.compress(data) }
-
end
-
@css_compressor = :css_compressor
-
else
-
1
@css_compressor = klass = compressor
-
end
-
-
1
register_bundle_processor 'text/css', klass
-
end
-
-
# Return JS compressor or nil if none is set
-
1
def js_compressor
-
1
@js_compressor if defined? @js_compressor
-
end
-
-
# Assign a compressor to run on `application/javascript` assets.
-
#
-
# The compressor object must respond to `compress`.
-
1
def js_compressor=(compressor)
-
1
unregister_bundle_processor 'application/javascript', js_compressor if js_compressor
-
1
@js_compressor = nil
-
1
return unless compressor
-
-
if compressor.is_a?(Symbol)
-
compressor = compressors['application/javascript'][compressor] || raise(Error, "unknown compressor: #{compressor}")
-
end
-
-
if compressor.respond_to?(:compress)
-
klass = Class.new(Processor) do
-
@name = "js_compressor"
-
@processor = proc { |context, data| compressor.compress(data) }
-
end
-
@js_compressor = :js_compressor
-
else
-
@js_compressor = klass = compressor
-
end
-
-
register_bundle_processor 'application/javascript', klass
-
end
-
end
-
end
-
1
require 'base64'
-
1
require 'rack/utils'
-
1
require 'sprockets/errors'
-
1
require 'sprockets/utils'
-
1
require 'pathname'
-
1
require 'set'
-
-
1
module Sprockets
-
# `Context` provides helper methods to all `Tilt` processors. They
-
# are typically accessed by ERB templates. You can mix in custom
-
# helpers by injecting them into `Environment#context_class`. Do not
-
# mix them into `Context` directly.
-
#
-
# environment.context_class.class_eval do
-
# include MyHelper
-
# def asset_url; end
-
# end
-
#
-
# <%= asset_url "foo.png" %>
-
#
-
# The `Context` also collects dependencies declared by
-
# assets. See `DirectiveProcessor` for an example of this.
-
1
class Context
-
1
attr_reader :environment, :pathname
-
1
attr_reader :_required_paths, :_stubbed_assets
-
1
attr_reader :_dependency_paths, :_dependency_assets
-
1
attr_writer :__LINE__
-
-
1
def initialize(environment, logical_path, pathname)
-
@environment = environment
-
@logical_path = logical_path
-
@pathname = pathname
-
@__LINE__ = nil
-
-
@_required_paths = []
-
@_stubbed_assets = Set.new
-
@_dependency_paths = Set.new
-
@_dependency_assets = Set.new([pathname.to_s])
-
end
-
-
# Returns the environment path that contains the file.
-
#
-
# If `app/javascripts` and `app/stylesheets` are in your path, and
-
# current file is `app/javascripts/foo/bar.js`, `root_path` would
-
# return `app/javascripts`.
-
1
def root_path
-
environment.paths.detect { |path| pathname.to_s[path] }
-
end
-
-
# Returns logical path without any file extensions.
-
#
-
# 'app/javascripts/application.js'
-
# # => 'application'
-
#
-
1
def logical_path
-
@logical_path.chomp(File.extname(@logical_path))
-
end
-
-
# Returns content type of file
-
#
-
# 'application/javascript'
-
# 'text/css'
-
#
-
1
def content_type
-
environment.content_type_of(pathname)
-
end
-
-
# Given a logical path, `resolve` will find and return the fully
-
# expanded path. Relative paths will also be resolved. An optional
-
# `:content_type` restriction can be supplied to restrict the
-
# search.
-
#
-
# resolve("foo.js")
-
# # => "/path/to/app/javascripts/foo.js"
-
#
-
# resolve("./bar.js")
-
# # => "/path/to/app/javascripts/bar.js"
-
#
-
1
def resolve(path, options = {}, &block)
-
pathname = Pathname.new(path)
-
attributes = environment.attributes_for(pathname)
-
-
if pathname.absolute?
-
if environment.stat(pathname)
-
pathname
-
else
-
raise FileNotFound, "couldn't find file '#{pathname}'"
-
end
-
-
elsif content_type = options[:content_type]
-
content_type = self.content_type if content_type == :self
-
-
if attributes.format_extension
-
if content_type != attributes.content_type
-
raise ContentTypeMismatch, "#{path} is " +
-
"'#{attributes.content_type}', not '#{content_type}'"
-
end
-
end
-
-
resolve(path) do |candidate|
-
if self.content_type == environment.content_type_of(candidate)
-
return candidate
-
end
-
end
-
-
raise FileNotFound, "couldn't find file '#{path}'"
-
else
-
environment.resolve(path, {:base_path => self.pathname.dirname}.merge(options), &block)
-
end
-
end
-
-
# `depend_on` allows you to state a dependency on a file without
-
# including it.
-
#
-
# This is used for caching purposes. Any changes made to
-
# the dependency file with invalidate the cache of the
-
# source file.
-
1
def depend_on(path)
-
@_dependency_paths << resolve(path).to_s
-
nil
-
end
-
-
# `depend_on_asset` allows you to state an asset dependency
-
# without including it.
-
#
-
# This is used for caching purposes. Any changes that would
-
# invalidate the dependency asset will invalidate the source
-
# file. Unlike `depend_on`, this will include recursively include
-
# the target asset's dependencies.
-
1
def depend_on_asset(path)
-
filename = resolve(path).to_s
-
@_dependency_assets << filename
-
nil
-
end
-
-
# `require_asset` declares `path` as a dependency of the file. The
-
# dependency will be inserted before the file and will only be
-
# included once.
-
#
-
# If ERB processing is enabled, you can use it to dynamically
-
# require assets.
-
#
-
# <%= require_asset "#{framework}.js" %>
-
#
-
1
def require_asset(path)
-
pathname = resolve(path, :content_type => :self)
-
depend_on_asset(pathname)
-
@_required_paths << pathname.to_s
-
nil
-
end
-
-
# `stub_asset` blacklists `path` from being included in the bundle.
-
# `path` must be an asset which may or may not already be included
-
# in the bundle.
-
1
def stub_asset(path)
-
@_stubbed_assets << resolve(path, :content_type => :self).to_s
-
nil
-
end
-
-
# Tests if target path is able to be safely required into the
-
# current concatenation.
-
1
def asset_requirable?(path)
-
pathname = resolve(path)
-
content_type = environment.content_type_of(pathname)
-
stat = environment.stat(path)
-
return false unless stat && stat.file?
-
self.content_type.nil? || self.content_type == content_type
-
end
-
-
# Reads `path` and runs processors on the file.
-
#
-
# This allows you to capture the result of an asset and include it
-
# directly in another.
-
#
-
# <%= evaluate "bar.js" %>
-
#
-
1
def evaluate(path, options = {})
-
pathname = resolve(path)
-
attributes = environment.attributes_for(pathname)
-
processors = options[:processors] || attributes.processors
-
-
if options[:data]
-
result = options[:data]
-
else
-
if environment.respond_to?(:default_external_encoding)
-
mime_type = environment.mime_types(pathname.extname)
-
encoding = environment.encoding_for_mime_type(mime_type)
-
result = Sprockets::Utils.read_unicode(pathname, encoding)
-
else
-
result = Sprockets::Utils.read_unicode(pathname)
-
end
-
end
-
-
processors.each do |processor|
-
begin
-
template = processor.new(pathname.to_s) { result }
-
result = template.render(self, {})
-
rescue Exception => e
-
annotate_exception! e
-
raise
-
end
-
end
-
-
result
-
end
-
-
# Returns a Base64-encoded `data:` URI with the contents of the
-
# asset at the specified path, and marks that path as a dependency
-
# of the current file.
-
#
-
# Use `asset_data_uri` from ERB with CSS or JavaScript assets:
-
#
-
# #logo { background: url(<%= asset_data_uri 'logo.png' %>) }
-
#
-
# $('<img>').attr('src', '<%= asset_data_uri 'avatar.jpg' %>')
-
#
-
1
def asset_data_uri(path)
-
depend_on_asset(path)
-
asset = environment.find_asset(path)
-
base64 = Base64.encode64(asset.to_s).gsub(/\s+/, "")
-
"data:#{asset.content_type};base64,#{Rack::Utils.escape(base64)}"
-
end
-
-
# Expands logical path to full url to asset.
-
#
-
# NOTE: This helper is currently not implemented and should be
-
# customized by the application. Though, in the future, some
-
# basics implemention may be provided with different methods that
-
# are required to be overridden.
-
1
def asset_path(path, options = {})
-
message = <<-EOS
-
Custom asset_path helper is not implemented
-
-
Extend your environment context with a custom method.
-
-
environment.context_class.class_eval do
-
def asset_path(path, options = {})
-
end
-
end
-
EOS
-
raise NotImplementedError, message
-
end
-
-
# Expand logical image asset path.
-
1
def image_path(path)
-
asset_path(path, :type => :image)
-
end
-
-
# Expand logical video asset path.
-
1
def video_path(path)
-
asset_path(path, :type => :video)
-
end
-
-
# Expand logical audio asset path.
-
1
def audio_path(path)
-
asset_path(path, :type => :audio)
-
end
-
-
# Expand logical font asset path.
-
1
def font_path(path)
-
asset_path(path, :type => :font)
-
end
-
-
# Expand logical javascript asset path.
-
1
def javascript_path(path)
-
asset_path(path, :type => :javascript)
-
end
-
-
# Expand logical stylesheet asset path.
-
1
def stylesheet_path(path)
-
asset_path(path, :type => :stylesheet)
-
end
-
-
1
private
-
# Annotates exception backtrace with the original template that
-
# the exception was raised in.
-
1
def annotate_exception!(exception)
-
location = pathname.to_s
-
location << ":#{@__LINE__}" if @__LINE__
-
-
exception.extend(Sprockets::EngineError)
-
exception.sprockets_annotation = " (in #{location})"
-
end
-
-
1
def logger
-
environment.logger
-
end
-
end
-
end
-
1
require 'pathname'
-
1
require 'shellwords'
-
1
require 'tilt'
-
1
require 'yaml'
-
-
1
module Sprockets
-
# The `DirectiveProcessor` is responsible for parsing and evaluating
-
# directive comments in a source file.
-
#
-
# A directive comment starts with a comment prefix, followed by an "=",
-
# then the directive name, then any arguments.
-
#
-
# // JavaScript
-
# //= require "foo"
-
#
-
# # CoffeeScript
-
# #= require "bar"
-
#
-
# /* CSS
-
# *= require "baz"
-
# */
-
#
-
# The Processor is implemented as a `Tilt::Template` and is loosely
-
# coupled to Sprockets. This makes it possible to disable or modify
-
# the processor to do whatever you'd like. You could add your own
-
# custom directives or invent your own directive syntax.
-
#
-
# `Environment#processors` includes `DirectiveProcessor` by default.
-
#
-
# To remove the processor entirely:
-
#
-
# env.unregister_processor('text/css', Sprockets::DirectiveProcessor)
-
# env.unregister_processor('application/javascript', Sprockets::DirectiveProcessor)
-
#
-
# Then inject your own preprocessor:
-
#
-
# env.register_processor('text/css', MyProcessor)
-
#
-
1
class DirectiveProcessor < Tilt::Template
-
# Directives will only be picked up if they are in the header
-
# of the source file. C style (/* */), JavaScript (//), and
-
# Ruby (#) comments are supported.
-
#
-
# Directives in comments after the first non-whitespace line
-
# of code will not be processed.
-
#
-
1
HEADER_PATTERN = /
-
\A (
-
(?m:\s*) (
-
(\/\* (?m:.*?) \*\/) |
-
(\#\#\# (?m:.*?) \#\#\#) |
-
(\/\/ .* \n?)+ |
-
(\# .* \n?)+
-
)
-
)+
-
/x
-
-
# Directives are denoted by a `=` followed by the name, then
-
# argument list.
-
#
-
# A few different styles are allowed:
-
#
-
# // =require foo
-
# //= require foo
-
# //= require "foo"
-
#
-
1
DIRECTIVE_PATTERN = /
-
^ \W* = \s* (\w+.*?) (\*\/)? $
-
/x
-
-
1
attr_reader :pathname
-
1
attr_reader :header, :body
-
-
1
def prepare
-
@pathname = Pathname.new(file)
-
-
@header = data[HEADER_PATTERN, 0] || ""
-
@body = $' || data
-
# Ensure body ends in a new line
-
@body += "\n" if @body != "" && @body !~ /\n\Z/m
-
-
@included_pathnames = []
-
@compat = false
-
end
-
-
# Implemented for Tilt#render.
-
#
-
# `context` is a `Context` instance with methods that allow you to
-
# access the environment and append to the bundle. See `Context`
-
# for the complete API.
-
1
def evaluate(context, locals, &block)
-
@context = context
-
-
@result = ""
-
@result.force_encoding(body.encoding) if body.respond_to?(:encoding)
-
-
@has_written_body = false
-
-
process_directives
-
process_source
-
-
@result
-
end
-
-
# Returns the header String with any directives stripped.
-
1
def processed_header
-
lineno = 0
-
@processed_header ||= header.lines.map { |line|
-
lineno += 1
-
# Replace directive line with a clean break
-
directives.assoc(lineno) ? "\n" : line
-
}.join.chomp
-
end
-
-
# Returns the source String with any directives stripped.
-
1
def processed_source
-
@processed_source ||= processed_header + body
-
end
-
-
# Returns an Array of directive structures. Each structure
-
# is an Array with the line number as the first element, the
-
# directive name as the second element, followed by any
-
# arguments.
-
#
-
# [[1, "require", "foo"], [2, "require", "bar"]]
-
#
-
1
def directives
-
@directives ||= header.lines.each_with_index.map { |line, index|
-
if directive = line[DIRECTIVE_PATTERN, 1]
-
name, *args = Shellwords.shellwords(directive)
-
if respond_to?("process_#{name}_directive", true)
-
[index + 1, name, *args]
-
end
-
end
-
}.compact
-
end
-
-
1
protected
-
1
attr_reader :included_pathnames
-
1
attr_reader :context
-
-
# Gathers comment directives in the source and processes them.
-
# Any directive method matching `process_*_directive` will
-
# automatically be available. This makes it easy to extend the
-
# processor.
-
#
-
# To implement a custom directive called `require_glob`, subclass
-
# `Sprockets::DirectiveProcessor`, then add a method called
-
# `process_require_glob_directive`.
-
#
-
# class DirectiveProcessor < Sprockets::DirectiveProcessor
-
# def process_require_glob_directive
-
# Dir["#{pathname.dirname}/#{glob}"].sort.each do |filename|
-
# require(filename)
-
# end
-
# end
-
# end
-
#
-
# Replace the current processor on the environment with your own:
-
#
-
# env.unregister_processor('text/css', Sprockets::DirectiveProcessor)
-
# env.register_processor('text/css', DirectiveProcessor)
-
#
-
1
def process_directives
-
directives.each do |line_number, name, *args|
-
context.__LINE__ = line_number
-
send("process_#{name}_directive", *args)
-
context.__LINE__ = nil
-
end
-
end
-
-
1
def process_source
-
unless @has_written_body || processed_header.empty?
-
@result << processed_header << "\n"
-
end
-
-
included_pathnames.each do |pathname|
-
@result << context.evaluate(pathname)
-
end
-
-
unless @has_written_body
-
@result << body
-
end
-
-
if compat? && constants.any?
-
@result.gsub!(/<%=(.*?)%>/) { constants[$1.strip] }
-
end
-
end
-
-
# The `require` directive functions similar to Ruby's own `require`.
-
# It provides a way to declare a dependency on a file in your path
-
# and ensures its only loaded once before the source file.
-
#
-
# `require` works with files in the environment path:
-
#
-
# //= require "foo.js"
-
#
-
# Extensions are optional. If your source file is ".js", it
-
# assumes you are requiring another ".js".
-
#
-
# //= require "foo"
-
#
-
# Relative paths work too. Use a leading `./` to denote a relative
-
# path:
-
#
-
# //= require "./bar"
-
#
-
1
def process_require_directive(path)
-
if @compat
-
if path =~ /<([^>]+)>/
-
path = $1
-
else
-
path = "./#{path}" unless relative?(path)
-
end
-
end
-
-
context.require_asset(path)
-
end
-
-
# `require_self` causes the body of the current file to be
-
# inserted before any subsequent `require` or `include`
-
# directives. Useful in CSS files, where it's common for the
-
# index file to contain global styles that need to be defined
-
# before other dependencies are loaded.
-
#
-
# /*= require "reset"
-
# *= require_self
-
# *= require_tree .
-
# */
-
#
-
1
def process_require_self_directive
-
if @has_written_body
-
raise ArgumentError, "require_self can only be called once per source file"
-
end
-
-
context.require_asset(pathname)
-
process_source
-
included_pathnames.clear
-
@has_written_body = true
-
end
-
-
# The `include` directive works similar to `require` but
-
# inserts the contents of the dependency even if it already
-
# has been required.
-
#
-
# //= include "header"
-
#
-
1
def process_include_directive(path)
-
pathname = context.resolve(path)
-
context.depend_on_asset(pathname)
-
included_pathnames << pathname
-
end
-
-
# `require_directory` requires all the files inside a single
-
# directory. It's similar to `path/*` since it does not follow
-
# nested directories.
-
#
-
# //= require_directory "./javascripts"
-
#
-
1
def process_require_directory_directive(path = ".")
-
if relative?(path)
-
root = pathname.dirname.join(path).expand_path
-
-
unless (stats = stat(root)) && stats.directory?
-
raise ArgumentError, "require_directory argument must be a directory"
-
end
-
-
context.depend_on(root)
-
-
entries(root).each do |pathname|
-
pathname = root.join(pathname)
-
if pathname.to_s == self.file
-
next
-
elsif context.asset_requirable?(pathname)
-
context.require_asset(pathname)
-
end
-
end
-
else
-
# The path must be relative and start with a `./`.
-
raise ArgumentError, "require_directory argument must be a relative path"
-
end
-
end
-
-
# `require_tree` requires all the nested files in a directory.
-
# Its glob equivalent is `path/**/*`.
-
#
-
# //= require_tree "./public"
-
#
-
1
def process_require_tree_directive(path = ".")
-
if relative?(path)
-
root = pathname.dirname.join(path).expand_path
-
-
unless (stats = stat(root)) && stats.directory?
-
raise ArgumentError, "require_tree argument must be a directory"
-
end
-
-
context.depend_on(root)
-
-
each_entry(root) do |pathname|
-
if pathname.to_s == self.file
-
next
-
elsif stat(pathname).directory?
-
context.depend_on(pathname)
-
elsif context.asset_requirable?(pathname)
-
context.require_asset(pathname)
-
end
-
end
-
else
-
# The path must be relative and start with a `./`.
-
raise ArgumentError, "require_tree argument must be a relative path"
-
end
-
end
-
-
# Allows you to state a dependency on a file without
-
# including it.
-
#
-
# This is used for caching purposes. Any changes made to
-
# the dependency file will invalidate the cache of the
-
# source file.
-
#
-
# This is useful if you are using ERB and File.read to pull
-
# in contents from another file.
-
#
-
# //= depend_on "foo.png"
-
#
-
1
def process_depend_on_directive(path)
-
context.depend_on(path)
-
end
-
-
# Allows you to state a dependency on an asset without including
-
# it.
-
#
-
# This is used for caching purposes. Any changes that would
-
# invalid the asset dependency will invalidate the cache our the
-
# source file.
-
#
-
# Unlike `depend_on`, the path must be a requirable asset.
-
#
-
# //= depend_on_asset "bar.js"
-
#
-
1
def process_depend_on_asset_directive(path)
-
context.depend_on_asset(path)
-
end
-
-
# Allows dependency to be excluded from the asset bundle.
-
#
-
# The `path` must be a valid asset and may or may not already
-
# be part of the bundle. Once stubbed, it is blacklisted and
-
# can't be brought back by any other `require`.
-
#
-
# //= stub "jquery"
-
#
-
1
def process_stub_directive(path)
-
context.stub_asset(path)
-
end
-
-
# Enable Sprockets 1.x compat mode.
-
#
-
# Makes it possible to use the same JavaScript source
-
# file in both Sprockets 1 and 2.
-
#
-
# //= compat
-
#
-
1
def process_compat_directive
-
@compat = true
-
end
-
-
# Checks if Sprockets 1.x compat mode enabled
-
1
def compat?
-
@compat
-
end
-
-
# Sprockets 1.x allowed for constant interpolation if a
-
# constants.yml was present. This is only available if
-
# compat mode is on.
-
1
def constants
-
if compat?
-
pathname = Pathname.new(context.root_path).join("constants.yml")
-
stat(pathname) ? YAML.load_file(pathname) : {}
-
else
-
{}
-
end
-
end
-
-
# `provide` is stubbed out for Sprockets 1.x compat.
-
# Mutating the path when an asset is being built is
-
# not permitted.
-
1
def process_provide_directive(path)
-
end
-
-
1
private
-
1
def relative?(path)
-
path =~ /^\.($|\.?\/)/
-
end
-
-
1
def stat(path)
-
context.environment.stat(path)
-
end
-
-
1
def entries(path)
-
context.environment.entries(path)
-
end
-
-
1
def each_entry(root, &block)
-
context.environment.each_entry(root, &block)
-
end
-
end
-
end
-
1
require 'tilt'
-
-
1
module Sprockets
-
# Tilt engine class for the Eco compiler. Depends on the `eco` gem.
-
#
-
# For more infomation see:
-
#
-
# https://github.com/sstephenson/ruby-eco
-
# https://github.com/sstephenson/eco
-
#
-
1
class EcoTemplate < Tilt::Template
-
# Check to see if Eco is loaded
-
1
def self.engine_initialized?
-
defined? ::Eco
-
end
-
-
# Autoload eco library. If the library isn't loaded, Tilt will produce
-
# a thread safetly warning. If you intend to use `.eco` files, you
-
# should explicitly require it.
-
1
def initialize_engine
-
require_template_library 'eco'
-
end
-
-
1
def prepare
-
end
-
-
# Compile template data with Eco compiler.
-
#
-
# Returns a JS function definition String. The result should be
-
# assigned to a JS variable.
-
#
-
# # => "function(...) {...}"
-
#
-
1
def evaluate(scope, locals, &block)
-
Eco.compile(data)
-
end
-
end
-
end
-
1
require 'tilt'
-
-
1
module Sprockets
-
# Tilt engine class for the EJS compiler. Depends on the `ejs` gem.
-
#
-
# For more infomation see:
-
#
-
# https://github.com/sstephenson/ruby-ejs
-
#
-
1
class EjsTemplate < Tilt::Template
-
# Check to see if EJS is loaded
-
1
def self.engine_initialized?
-
defined? ::EJS
-
end
-
-
# Autoload ejs library. If the library isn't loaded, Tilt will produce
-
# a thread safetly warning. If you intend to use `.ejs` files, you
-
# should explicitly require it.
-
1
def initialize_engine
-
require_template_library 'ejs'
-
end
-
-
1
def prepare
-
end
-
-
# Compile template data with EJS compiler.
-
#
-
# Returns a JS function definition String. The result should be
-
# assigned to a JS variable.
-
#
-
# # => "function(obj){...}"
-
#
-
1
def evaluate(scope, locals, &block)
-
EJS.compile(data)
-
end
-
end
-
end
-
1
require 'sprockets/eco_template'
-
1
require 'sprockets/ejs_template'
-
1
require 'sprockets/jst_processor'
-
1
require 'sprockets/utils'
-
1
require 'tilt'
-
-
1
module Sprockets
-
# `Engines` provides a global and `Environment` instance registry.
-
#
-
# An engine is a type of processor that is bound to an filename
-
# extension. `application.js.coffee` indicates that the
-
# `CoffeeScriptTemplate` engine will be ran on the file.
-
#
-
# Extensions can be stacked and will be evaulated from right to
-
# left. `application.js.coffee.erb` will first run `ERBTemplate`
-
# then `CoffeeScriptTemplate`.
-
#
-
# All `Engine`s must follow the `Tilt::Template` interface. It is
-
# recommended to subclass `Tilt::Template`.
-
#
-
# Its recommended that you register engine changes on your local
-
# `Environment` instance.
-
#
-
# environment.register_engine '.foo', FooProcessor
-
#
-
# The global registry is exposed for plugins to register themselves.
-
#
-
# Sprockets.register_engine '.sass', SassTemplate
-
#
-
1
module Engines
-
# Returns a `Hash` of `Engine`s registered on the `Environment`.
-
# If an `ext` argument is supplied, the `Engine` associated with
-
# that extension will be returned.
-
#
-
# environment.engines
-
# # => {".coffee" => CoffeeScriptTemplate, ".sass" => SassTemplate, ...}
-
#
-
# environment.engines('.coffee')
-
# # => CoffeeScriptTemplate
-
#
-
1
def engines(ext = nil)
-
2
if ext
-
ext = Sprockets::Utils.normalize_extension(ext)
-
@engines[ext]
-
else
-
2
@engines.dup
-
end
-
end
-
-
# Returns an `Array` of engine extension `String`s.
-
#
-
# environment.engine_extensions
-
# # => ['.coffee', '.sass', ...]
-
1
def engine_extensions
-
@engines.keys
-
end
-
-
# Registers a new Engine `klass` for `ext`. If the `ext` already
-
# has an engine registered, it will be overridden.
-
#
-
# environment.register_engine '.coffee', CoffeeScriptTemplate
-
#
-
1
def register_engine(ext, klass)
-
12
ext = Sprockets::Utils.normalize_extension(ext)
-
12
@engines[ext] = klass
-
end
-
-
1
private
-
1
def deep_copy_hash(hash)
-
9
initial = Hash.new { |h, k| h[k] = [] }
-
23
hash.inject(initial) { |h, (k, a)| h[k] = a.dup; h }
-
end
-
end
-
end
-
1
require 'sprockets/base'
-
1
require 'sprockets/context'
-
1
require 'sprockets/index'
-
-
1
require 'hike'
-
1
require 'logger'
-
1
require 'pathname'
-
1
require 'tilt'
-
-
1
module Sprockets
-
1
class Environment < Base
-
# `Environment` should initialized with your application's root
-
# directory. This should be the same as your Rails or Rack root.
-
#
-
# env = Environment.new(Rails.root)
-
#
-
1
def initialize(root = ".")
-
1
@trail = Hike::Trail.new(root)
-
-
1
self.logger = Logger.new($stderr)
-
1
self.logger.level = Logger::FATAL
-
-
1
if respond_to?(:default_external_encoding)
-
1
self.default_external_encoding = Encoding::UTF_8
-
end
-
-
# Create a safe `Context` subclass to mutate
-
1
@context_class = Class.new(Context)
-
-
# Set MD5 as the default digest
-
1
require 'digest/md5'
-
1
@digest_class = ::Digest::MD5
-
1
@version = ''
-
-
1
@mime_types = Sprockets.registered_mime_types
-
1
@engines = Sprockets.engines
-
1
@preprocessors = Sprockets.preprocessors
-
1
@postprocessors = Sprockets.postprocessors
-
1
@bundle_processors = Sprockets.bundle_processors
-
1
@compressors = Sprockets.compressors
-
-
1
Sprockets.paths.each do |path|
-
append_path(path)
-
end
-
-
1
@engines.each do |ext, klass|
-
9
add_engine_to_trail(ext, klass)
-
end
-
-
1
@mime_types.each do |ext, type|
-
2
@trail.append_extension(ext)
-
end
-
-
1
expire_index!
-
-
1
yield self if block_given?
-
end
-
-
# Returns a cached version of the environment.
-
#
-
# All its file system calls are cached which makes `index` much
-
# faster. This behavior is ideal in production since the file
-
# system only changes between deploys.
-
1
def index
-
1
Index.new(self)
-
end
-
-
# Cache `find_asset` calls
-
1
def find_asset(path, options = {})
-
options[:bundle] = true unless options.key?(:bundle)
-
-
# Ensure inmemory cached assets are still fresh on every lookup
-
if (asset = @assets[cache_key_for(path, options)]) && asset.fresh?(self)
-
asset
-
elsif asset = index.find_asset(path, options)
-
# Cache is pushed upstream by Index#find_asset
-
asset
-
end
-
end
-
-
1
protected
-
1
def expire_index!
-
# Clear digest to be recomputed
-
35
@digest = nil
-
35
@assets = {}
-
end
-
end
-
end
-
# Define some basic Sprockets error classes
-
1
module Sprockets
-
1
class Error < StandardError; end
-
1
class ArgumentError < Error; end
-
1
class CircularDependencyError < Error; end
-
1
class ContentTypeMismatch < Error; end
-
1
class EncodingError < Error; end
-
1
class FileNotFound < Error; end
-
1
class FileOutsidePaths < Error; end
-
1
class NotImplementedError < Error; end
-
1
class UnserializeError < Error; end
-
-
1
module EngineError
-
1
attr_accessor :sprockets_annotation
-
-
1
def message
-
[super, sprockets_annotation].compact.join("\n")
-
end
-
end
-
end
-
1
require 'sprockets/base'
-
-
1
module Sprockets
-
# `Index` is a special cached version of `Environment`.
-
#
-
# The expection is that all of its file system methods are cached
-
# for the instances lifetime. This makes `Index` much faster. This
-
# behavior is ideal in production environments where the file system
-
# is immutable.
-
#
-
# `Index` should not be initialized directly. Instead use
-
# `Environment#index`.
-
1
class Index < Base
-
1
def initialize(environment)
-
1
@environment = environment
-
-
1
if environment.respond_to?(:default_external_encoding)
-
1
@default_external_encoding = environment.default_external_encoding
-
end
-
-
# Copy environment attributes
-
1
@logger = environment.logger
-
1
@context_class = environment.context_class
-
1
@cache = environment.cache
-
1
@trail = environment.trail.index
-
1
@digest = environment.digest
-
1
@digest_class = environment.digest_class
-
1
@version = environment.version
-
1
@mime_types = environment.mime_types
-
1
@engines = environment.engines
-
1
@preprocessors = environment.preprocessors
-
1
@postprocessors = environment.postprocessors
-
1
@bundle_processors = environment.bundle_processors
-
1
@compressors = environment.compressors
-
-
# Initialize caches
-
1
@assets = {}
-
1
@digests = {}
-
end
-
-
# No-op return self as index
-
1
def index
-
self
-
end
-
-
# Cache calls to `file_digest`
-
1
def file_digest(pathname)
-
key = pathname.to_s
-
if @digests.key?(key)
-
@digests[key]
-
else
-
@digests[key] = super
-
end
-
end
-
-
# Cache `find_asset` calls
-
1
def find_asset(path, options = {})
-
options[:bundle] = true unless options.key?(:bundle)
-
if asset = @assets[cache_key_for(path, options)]
-
asset
-
elsif asset = super
-
logical_path_cache_key = cache_key_for(path, options)
-
full_path_cache_key = cache_key_for(asset.pathname, options)
-
-
# Cache on Index
-
@assets[logical_path_cache_key] = @assets[full_path_cache_key] = asset
-
-
# Push cache upstream to Environment
-
@environment.instance_eval do
-
@assets[logical_path_cache_key] = @assets[full_path_cache_key] = asset
-
end
-
-
asset
-
end
-
end
-
-
1
protected
-
# Index is immutable, any methods that try to clear the cache
-
# should bomb.
-
1
def expire_index!
-
raise TypeError, "can't modify immutable index"
-
end
-
-
# Cache asset building in memory and in persisted cache.
-
1
def build_asset(path, pathname, options)
-
# Memory cache
-
key = cache_key_for(pathname, options)
-
if @assets.key?(key)
-
@assets[key]
-
else
-
@assets[key] = begin
-
# Persisted cache
-
cache_asset(key) do
-
super
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'tilt'
-
-
1
module Sprockets
-
1
class JstProcessor < Tilt::Template
-
1
self.default_mime_type = 'application/javascript'
-
-
1
def self.default_namespace
-
'this.JST'
-
end
-
-
1
def prepare
-
@namespace = self.class.default_namespace
-
end
-
-
1
attr_reader :namespace
-
-
1
def evaluate(scope, locals, &block)
-
<<-JST
-
(function() { #{namespace} || (#{namespace} = {}); #{namespace}[#{scope.logical_path.inspect}] = #{indent(data)};
-
}).call(this);
-
JST
-
end
-
-
1
private
-
1
def indent(string)
-
string.gsub(/$(.)/m, "\\1 ").strip
-
end
-
end
-
end
-
1
require 'multi_json'
-
1
require 'securerandom'
-
1
require 'time'
-
-
1
module Sprockets
-
# The Manifest logs the contents of assets compiled to a single
-
# directory. It records basic attributes about the asset for fast
-
# lookup without having to compile. A pointer from each logical path
-
# indicates with fingerprinted asset is the current one.
-
#
-
# The JSON is part of the public API and should be considered
-
# stable. This should make it easy to read from other programming
-
# languages and processes that don't have sprockets loaded. See
-
# `#assets` and `#files` for more infomation about the structure.
-
1
class Manifest
-
1
attr_reader :environment, :path, :dir
-
-
# Create new Manifest associated with an `environment`. `path` is
-
# a full path to the manifest json file. The file may or may not
-
# already exist. The dirname of the `path` will be used to write
-
# compiled assets to. Otherwise, if the path is a directory, the
-
# filename will default a random "manifest-123.json" file in that
-
# directory.
-
#
-
# Manifest.new(environment, "./public/assets/manifest.json")
-
#
-
1
def initialize(*args)
-
1
if args.first.is_a?(Base) || args.first.nil?
-
1
@environment = args.shift
-
end
-
-
1
@dir, @path = args[0], args[1]
-
-
# Expand paths
-
1
@dir = File.expand_path(@dir) if @dir
-
1
@path = File.expand_path(@path) if @path
-
-
# If path is given as the second arg
-
1
if @dir && File.extname(@dir) != ""
-
@dir, @path = nil, @dir
-
end
-
-
# Default dir to the directory of the path
-
1
@dir ||= File.dirname(@path) if @path
-
-
# If directory is given w/o path, pick a random manifest.json location
-
1
if @dir && @path.nil?
-
# Find the first manifest.json in the directory
-
1
paths = Dir[File.join(@dir, "manifest*.json")]
-
1
if paths.any?
-
1
@path = paths.first
-
else
-
@path = File.join(@dir, "manifest-#{SecureRandom.hex(16)}.json")
-
end
-
end
-
-
1
unless @dir && @path
-
raise ArgumentError, "manifest requires output path"
-
end
-
-
1
data = nil
-
-
1
begin
-
1
if File.exist?(@path)
-
1
data = json_decode(File.read(@path))
-
end
-
rescue MultiJson::DecodeError => e
-
logger.error "#{@path} is invalid: #{e.class} #{e.message}"
-
end
-
-
1
@data = data.is_a?(Hash) ? data : {}
-
end
-
-
# Returns internal assets mapping. Keys are logical paths which
-
# map to the latest fingerprinted filename.
-
#
-
# Logical path (String): Fingerprint path (String)
-
#
-
# { "application.js" => "application-2e8e9a7c6b0aafa0c9bdeec90ea30213.js",
-
# "jquery.js" => "jquery-ae0908555a245f8266f77df5a8edca2e.js" }
-
#
-
1
def assets
-
@data['assets'] ||= {}
-
end
-
-
# Returns internal file directory listing. Keys are filenames
-
# which map to an attributes array.
-
#
-
# Fingerprint path (String):
-
# logical_path: Logical path (String)
-
# mtime: ISO8601 mtime (String)
-
# digest: Base64 hex digest (String)
-
#
-
# { "application-2e8e9a7c6b0aafa0c9bdeec90ea30213.js" =>
-
# { 'logical_path' => "application.js",
-
# 'mtime' => "2011-12-13T21:47:08-06:00",
-
# 'digest' => "2e8e9a7c6b0aafa0c9bdeec90ea30213" } }
-
#
-
1
def files
-
@data['files'] ||= {}
-
end
-
-
# Compile and write asset to directory. The asset is written to a
-
# fingerprinted filename like
-
# `application-2e8e9a7c6b0aafa0c9bdeec90ea30213.js`. An entry is
-
# also inserted into the manifest file.
-
#
-
# compile("application.js")
-
#
-
1
def compile(*args)
-
unless environment
-
raise Error, "manifest requires environment for compilation"
-
end
-
-
paths = environment.each_logical_path(*args).to_a +
-
args.flatten.select { |fn| Pathname.new(fn).absolute? if fn.is_a?(String)}
-
-
paths.each do |path|
-
if asset = find_asset(path)
-
files[asset.digest_path] = {
-
'logical_path' => asset.logical_path,
-
'mtime' => asset.mtime.iso8601,
-
'size' => asset.bytesize,
-
'digest' => asset.digest
-
}
-
assets[asset.logical_path] = asset.digest_path
-
-
target = File.join(dir, asset.digest_path)
-
-
if File.exist?(target)
-
logger.debug "Skipping #{target}, already exists"
-
else
-
logger.info "Writing #{target}"
-
asset.write_to target
-
asset.write_to "#{target}.gz" if asset.is_a?(BundledAsset)
-
end
-
-
end
-
end
-
save
-
paths
-
end
-
-
# Removes file from directory and from manifest. `filename` must
-
# be the name with any directory path.
-
#
-
# manifest.remove("application-2e8e9a7c6b0aafa0c9bdeec90ea30213.js")
-
#
-
1
def remove(filename)
-
path = File.join(dir, filename)
-
gzip = "#{path}.gz"
-
logical_path = files[filename]['logical_path']
-
-
if assets[logical_path] == filename
-
assets.delete(logical_path)
-
end
-
-
files.delete(filename)
-
FileUtils.rm(path) if File.exist?(path)
-
FileUtils.rm(gzip) if File.exist?(gzip)
-
-
save
-
-
logger.info "Removed #{filename}"
-
-
nil
-
end
-
-
# Cleanup old assets in the compile directory. By default it will
-
# keep the latest version plus 2 backups.
-
1
def clean(keep = 2)
-
self.assets.keys.each do |logical_path|
-
# Get assets sorted by ctime, newest first
-
assets = backups_for(logical_path)
-
-
# Keep the last N backups
-
assets = assets[keep..-1] || []
-
-
# Remove old assets
-
assets.each { |path, _| remove(path) }
-
end
-
end
-
-
# Wipe directive
-
1
def clobber
-
FileUtils.rm_r(@dir) if File.exist?(@dir)
-
logger.info "Removed #{@dir}"
-
nil
-
end
-
-
1
protected
-
# Finds all the backup assets for a logical path. The latest
-
# version is always excluded. The return array is sorted by the
-
# assets mtime in descending order (Newest to oldest).
-
1
def backups_for(logical_path)
-
files.select { |filename, attrs|
-
# Matching logical paths
-
attrs['logical_path'] == logical_path &&
-
# Excluding whatever asset is the current
-
assets[logical_path] != filename
-
}.sort_by { |filename, attrs|
-
# Sort by timestamp
-
Time.parse(attrs['mtime'])
-
}.reverse
-
end
-
-
# Basic wrapper around Environment#find_asset. Logs compile time.
-
1
def find_asset(logical_path)
-
asset = nil
-
ms = benchmark do
-
asset = environment.find_asset(logical_path)
-
end
-
logger.debug "Compiled #{logical_path} (#{ms}ms)"
-
asset
-
end
-
-
# Persist manfiest back to FS
-
1
def save
-
FileUtils.mkdir_p dir
-
File.open(path, 'w') do |f|
-
f.write json_encode(@data)
-
end
-
end
-
-
1
private
-
# Feature detect newer MultiJson API
-
1
if MultiJson.respond_to?(:dump)
-
1
def json_decode(obj)
-
1
MultiJson.load(obj)
-
end
-
-
1
def json_encode(obj)
-
MultiJson.dump(obj)
-
end
-
else
-
def json_decode(obj)
-
MultiJson.decode(obj)
-
end
-
-
def json_encode(obj)
-
MultiJson.encode(obj)
-
end
-
end
-
-
1
def logger
-
if environment
-
environment.logger
-
else
-
logger = Logger.new($stderr)
-
logger.level = Logger::FATAL
-
logger
-
end
-
end
-
-
1
def benchmark
-
start_time = Time.now.to_f
-
yield
-
((Time.now.to_f - start_time) * 1000).to_i
-
end
-
end
-
end
-
1
require 'rack/mime'
-
-
1
module Sprockets
-
1
module Mime
-
# Returns a `Hash` of registered mime types registered on the
-
# environment and those part of `Rack::Mime`.
-
#
-
# If an `ext` is given, it will lookup the mime type for that extension.
-
1
def mime_types(ext = nil)
-
8
if ext.nil?
-
8
Rack::Mime::MIME_TYPES.merge(@mime_types)
-
else
-
ext = Sprockets::Utils.normalize_extension(ext)
-
@mime_types[ext] || Rack::Mime::MIME_TYPES[ext]
-
end
-
end
-
-
# Returns a `Hash` of explicitly registered mime types.
-
1
def registered_mime_types
-
1
@mime_types.dup
-
end
-
-
1
if {}.respond_to?(:key)
-
1
def extension_for_mime_type(type)
-
7
mime_types.key(type)
-
end
-
else
-
def extension_for_mime_type(type)
-
mime_types.index(type)
-
end
-
end
-
-
# Register a new mime type.
-
1
def register_mime_type(mime_type, ext)
-
2
ext = Sprockets::Utils.normalize_extension(ext)
-
2
@mime_types[ext] = mime_type
-
end
-
-
1
if defined? Encoding
-
# Returns the correct encoding for a given mime type, while falling
-
# back on the default external encoding, if it exists.
-
1
def encoding_for_mime_type(type)
-
encoding = Encoding::BINARY if type =~ %r{^(image|audio|video)/}
-
encoding ||= default_external_encoding if respond_to?(:default_external_encoding)
-
encoding
-
end
-
end
-
end
-
end
-
1
module Sprockets
-
1
module Paths
-
# Returns `Environment` root.
-
#
-
# All relative paths are expanded with root as its base. To be
-
# useful set this to your applications root directory. (`Rails.root`)
-
1
def root
-
@trail.root.dup
-
end
-
-
# Returns an `Array` of path `String`s.
-
#
-
# These paths will be used for asset logical path lookups.
-
#
-
# Note that a copy of the `Array` is returned so mutating will
-
# have no affect on the environment. See `append_path`,
-
# `prepend_path`, and `clear_paths`.
-
1
def paths
-
1
@trail.paths.dup
-
end
-
-
# Prepend a `path` to the `paths` list.
-
#
-
# Paths at the end of the `Array` have the least priority.
-
1
def prepend_path(path)
-
@trail.prepend_path(path)
-
end
-
-
# Append a `path` to the `paths` list.
-
#
-
# Paths at the beginning of the `Array` have a higher priority.
-
1
def append_path(path)
-
28
@trail.append_path(path)
-
end
-
-
# Clear all paths and start fresh.
-
#
-
# There is no mechanism for reordering paths, so its best to
-
# completely wipe the paths list and reappend them in the order
-
# you want.
-
1
def clear_paths
-
@trail.paths.dup.each { |path| @trail.remove_path(path) }
-
end
-
-
# Returns an `Array` of extensions.
-
#
-
# These extensions maybe omitted from logical path searches.
-
#
-
# # => [".js", ".css", ".coffee", ".sass", ...]
-
#
-
1
def extensions
-
@trail.extensions.dup
-
end
-
-
1
protected
-
1
attr_reader :trail
-
end
-
end
-
1
require 'sprockets/asset'
-
1
require 'sprockets/utils'
-
-
1
module Sprockets
-
1
class ProcessedAsset < Asset
-
1
def initialize(environment, logical_path, pathname)
-
super
-
-
start_time = Time.now.to_f
-
-
context = environment.context_class.new(environment, logical_path, pathname)
-
@source = context.evaluate(pathname)
-
@length = Rack::Utils.bytesize(source)
-
@digest = environment.digest.update(source).hexdigest
-
-
build_required_assets(environment, context)
-
build_dependency_paths(environment, context)
-
-
@dependency_digest = compute_dependency_digest(environment)
-
-
elapsed_time = ((Time.now.to_f - start_time) * 1000).to_i
-
environment.logger.debug "Compiled #{logical_path} (#{elapsed_time}ms) (pid #{Process.pid})"
-
end
-
-
# Interal: Used to check equality
-
1
attr_reader :dependency_digest
-
-
1
attr_reader :source
-
-
# Initialize `BundledAsset` from serialized `Hash`.
-
1
def init_with(environment, coder)
-
super
-
-
@source = coder['source']
-
@dependency_digest = coder['dependency_digest']
-
-
@required_assets = coder['required_paths'].map { |p|
-
p = expand_root_path(p)
-
-
unless environment.paths.detect { |path| p[path] }
-
raise UnserializeError, "#{p} isn't in paths"
-
end
-
-
p == pathname.to_s ? self : environment.find_asset(p, :bundle => false)
-
}
-
@dependency_paths = coder['dependency_paths'].map { |h|
-
DependencyFile.new(expand_root_path(h['path']), h['mtime'], h['digest'])
-
}
-
end
-
-
# Serialize custom attributes in `BundledAsset`.
-
1
def encode_with(coder)
-
super
-
-
coder['source'] = source
-
coder['dependency_digest'] = dependency_digest
-
-
coder['required_paths'] = required_assets.map { |a|
-
relativize_root_path(a.pathname).to_s
-
}
-
coder['dependency_paths'] = dependency_paths.map { |d|
-
{ 'path' => relativize_root_path(d.pathname).to_s,
-
'mtime' => d.mtime.iso8601,
-
'digest' => d.digest }
-
}
-
end
-
-
# Checks if Asset is stale by comparing the actual mtime and
-
# digest to the inmemory model.
-
1
def fresh?(environment)
-
# Check freshness of all declared dependencies
-
@dependency_paths.all? { |dep| dependency_fresh?(environment, dep) }
-
end
-
-
1
protected
-
1
class DependencyFile < Struct.new(:pathname, :mtime, :digest)
-
1
def initialize(pathname, mtime, digest)
-
pathname = Pathname.new(pathname) unless pathname.is_a?(Pathname)
-
mtime = Time.parse(mtime) if mtime.is_a?(String)
-
super
-
end
-
-
1
def eql?(other)
-
other.is_a?(DependencyFile) &&
-
pathname.eql?(other.pathname) &&
-
mtime.eql?(other.mtime) &&
-
digest.eql?(other.digest)
-
end
-
-
1
def hash
-
pathname.to_s.hash
-
end
-
end
-
-
1
private
-
1
def build_required_assets(environment, context)
-
@required_assets = resolve_dependencies(environment, context._required_paths + [pathname.to_s]) -
-
resolve_dependencies(environment, context._stubbed_assets.to_a)
-
end
-
-
1
def resolve_dependencies(environment, paths)
-
assets = []
-
cache = {}
-
-
paths.each do |path|
-
if path == self.pathname.to_s
-
unless cache[self]
-
cache[self] = true
-
assets << self
-
end
-
elsif asset = environment.find_asset(path, :bundle => false)
-
asset.required_assets.each do |asset_dependency|
-
unless cache[asset_dependency]
-
cache[asset_dependency] = true
-
assets << asset_dependency
-
end
-
end
-
end
-
end
-
-
assets
-
end
-
-
1
def build_dependency_paths(environment, context)
-
dependency_paths = {}
-
-
context._dependency_paths.each do |path|
-
dep = DependencyFile.new(path, environment.stat(path).mtime, environment.file_digest(path).hexdigest)
-
dependency_paths[dep] = true
-
end
-
-
context._dependency_assets.each do |path|
-
if path == self.pathname.to_s
-
dep = DependencyFile.new(pathname, environment.stat(path).mtime, environment.file_digest(path).hexdigest)
-
dependency_paths[dep] = true
-
elsif asset = environment.find_asset(path, :bundle => false)
-
asset.dependency_paths.each do |d|
-
dependency_paths[d] = true
-
end
-
end
-
end
-
-
@dependency_paths = dependency_paths.keys
-
end
-
-
1
def compute_dependency_digest(environment)
-
required_assets.inject(environment.digest) { |digest, asset|
-
digest.update asset.digest
-
}.hexdigest
-
end
-
end
-
end
-
1
require 'sprockets/engines'
-
1
require 'sprockets/mime'
-
1
require 'sprockets/processor'
-
1
require 'sprockets/utils'
-
-
1
module Sprockets
-
# `Processing` is an internal mixin whose public methods are exposed on
-
# the `Environment` and `Index` classes.
-
1
module Processing
-
# Returns an `Array` of format extension `String`s.
-
#
-
# format_extensions
-
# # => ['.js', '.css']
-
#
-
1
def format_extensions
-
@trail.extensions - @engines.keys
-
end
-
-
# Deprecated alias for `preprocessors`.
-
1
def processors(*args)
-
preprocessors(*args)
-
end
-
-
# Returns an `Array` of `Processor` classes. If a `mime_type`
-
# argument is supplied, the processors registered under that
-
# extension will be returned.
-
#
-
# Preprocessors are ran before Postprocessors and Engine
-
# processors.
-
#
-
# All `Processor`s must follow the `Tilt::Template` interface. It is
-
# recommended to subclass `Tilt::Template`.
-
1
def preprocessors(mime_type = nil)
-
2
if mime_type
-
@preprocessors[mime_type].dup
-
else
-
2
deep_copy_hash(@preprocessors)
-
end
-
end
-
-
# Returns an `Array` of `Processor` classes. If a `mime_type`
-
# argument is supplied, the processors registered under that
-
# extension will be returned.
-
#
-
# Postprocessors are ran after Preprocessors and Engine processors.
-
#
-
# All `Processor`s must follow the `Tilt::Template` interface. It is
-
# recommended to subclass `Tilt::Template`.
-
1
def postprocessors(mime_type = nil)
-
2
if mime_type
-
@postprocessors[mime_type].dup
-
else
-
2
deep_copy_hash(@postprocessors)
-
end
-
end
-
-
# Deprecated alias for `register_preprocessor`.
-
1
def register_processor(*args, &block)
-
register_preprocessor(*args, &block)
-
end
-
-
# Registers a new Preprocessor `klass` for `mime_type`.
-
#
-
# register_preprocessor 'text/css', Sprockets::DirectiveProcessor
-
#
-
# A block can be passed for to create a shorthand processor.
-
#
-
# register_preprocessor 'text/css', :my_processor do |context, data|
-
# data.gsub(...)
-
# end
-
#
-
1
def register_preprocessor(mime_type, klass, &block)
-
3
if block_given?
-
name = klass.to_s
-
klass = Class.new(Processor) do
-
@name = name
-
@processor = block
-
end
-
end
-
-
3
@preprocessors[mime_type].push(klass)
-
end
-
-
# Registers a new Postprocessor `klass` for `mime_type`.
-
#
-
# register_postprocessor 'text/css', Sprockets::CharsetNormalizer
-
#
-
# A block can be passed for to create a shorthand processor.
-
#
-
# register_postprocessor 'text/css', :my_processor do |context, data|
-
# data.gsub(...)
-
# end
-
#
-
1
def register_postprocessor(mime_type, klass, &block)
-
1
if block_given?
-
name = klass.to_s
-
klass = Class.new(Processor) do
-
@name = name
-
@processor = block
-
end
-
end
-
-
1
@postprocessors[mime_type].push(klass)
-
end
-
-
# Deprecated alias for `unregister_preprocessor`.
-
1
def unregister_processor(*args)
-
unregister_preprocessor(*args)
-
end
-
-
# Remove Preprocessor `klass` for `mime_type`.
-
#
-
# unregister_preprocessor 'text/css', Sprockets::DirectiveProcessor
-
#
-
1
def unregister_preprocessor(mime_type, klass)
-
if klass.is_a?(String) || klass.is_a?(Symbol)
-
klass = @preprocessors[mime_type].detect { |cls|
-
cls.respond_to?(:name) &&
-
cls.name == "Sprockets::Processor (#{klass})"
-
}
-
end
-
-
@preprocessors[mime_type].delete(klass)
-
end
-
-
# Remove Postprocessor `klass` for `mime_type`.
-
#
-
# unregister_postprocessor 'text/css', Sprockets::DirectiveProcessor
-
#
-
1
def unregister_postprocessor(mime_type, klass)
-
if klass.is_a?(String) || klass.is_a?(Symbol)
-
klass = @postprocessors[mime_type].detect { |cls|
-
cls.respond_to?(:name) &&
-
cls.name == "Sprockets::Processor (#{klass})"
-
}
-
end
-
-
@postprocessors[mime_type].delete(klass)
-
end
-
-
# Returns an `Array` of `Processor` classes. If a `mime_type`
-
# argument is supplied, the processors registered under that
-
# extension will be returned.
-
#
-
# Bundle Processors are ran on concatenated assets rather than
-
# individual files.
-
#
-
# All `Processor`s must follow the `Tilt::Template` interface. It is
-
# recommended to subclass `Tilt::Template`.
-
1
def bundle_processors(mime_type = nil)
-
2
if mime_type
-
@bundle_processors[mime_type].dup
-
else
-
2
deep_copy_hash(@bundle_processors)
-
end
-
end
-
-
# Registers a new Bundle Processor `klass` for `mime_type`.
-
#
-
# register_bundle_processor 'text/css', Sprockets::CharsetNormalizer
-
#
-
# A block can be passed for to create a shorthand processor.
-
#
-
# register_bundle_processor 'text/css', :my_processor do |context, data|
-
# data.gsub(...)
-
# end
-
#
-
1
def register_bundle_processor(mime_type, klass, &block)
-
2
if block_given?
-
name = klass.to_s
-
klass = Class.new(Processor) do
-
@name = name
-
@processor = block
-
end
-
end
-
-
2
@bundle_processors[mime_type].push(klass)
-
end
-
-
# Remove Bundle Processor `klass` for `mime_type`.
-
#
-
# unregister_bundle_processor 'text/css', Sprockets::CharsetNormalizer
-
#
-
1
def unregister_bundle_processor(mime_type, klass)
-
if klass.is_a?(String) || klass.is_a?(Symbol)
-
klass = @bundle_processors[mime_type].detect { |cls|
-
cls.respond_to?(:name) &&
-
cls.name == "Sprockets::Processor (#{klass})"
-
}
-
end
-
-
@bundle_processors[mime_type].delete(klass)
-
end
-
-
1
private
-
1
def add_engine_to_trail(ext, klass)
-
11
@trail.append_extension(ext.to_s)
-
-
11
if klass.respond_to?(:default_mime_type) && klass.default_mime_type
-
7
if format_ext = extension_for_mime_type(klass.default_mime_type)
-
7
@trail.alias_extension(ext.to_s, format_ext)
-
end
-
end
-
end
-
end
-
end
-
1
require 'tilt'
-
-
1
module Sprockets
-
# `Processor` creates an anonymous processor class from a block.
-
#
-
# register_preprocessor 'text/css', :my_processor do |context, data|
-
# # ...
-
# end
-
#
-
1
class Processor < Tilt::Template
-
# `processor` is a lambda or block
-
1
def self.processor
-
@processor
-
end
-
-
1
def self.name
-
"Sprockets::Processor (#{@name})"
-
end
-
-
1
def self.to_s
-
name
-
end
-
-
1
def prepare
-
end
-
-
# Call processor block with `context` and `data`.
-
1
def evaluate(context, locals)
-
self.class.processor.call(context, data)
-
end
-
end
-
end
-
1
require 'tilt'
-
-
1
module Sprockets
-
# For JS developers who are colonfobic, concatenating JS files using
-
# the module pattern usually leads to syntax errors.
-
#
-
# The `SafetyColons` processor will insert missing semicolons to the
-
# end of the file.
-
#
-
# This behavior can be disabled with:
-
#
-
# environment.unregister_postprocessor 'application/javascript', Sprockets::SafetyColons
-
#
-
1
class SafetyColons < Tilt::Template
-
1
def prepare
-
end
-
-
1
def evaluate(context, locals, &block)
-
# If the file is blank or ends in a semicolon, leave it as is
-
if data =~ /\A\s*\Z/m || data =~ /;\s*\Z/m
-
data
-
else
-
# Otherwise, append a semicolon and newline
-
"#{data};\n"
-
end
-
end
-
end
-
end
-
1
require 'tilt'
-
-
1
module Sprockets
-
1
class SassCompressor < Tilt::Template
-
1
self.default_mime_type = 'text/css'
-
-
1
def self.engine_initialized?
-
defined?(::Sass::Engine)
-
end
-
-
1
def initialize_engine
-
require_template_library 'sass'
-
end
-
-
1
def prepare
-
end
-
-
1
def evaluate(context, locals, &block)
-
::Sass::Engine.new(data, {
-
:syntax => :scss,
-
:cache => false,
-
:read_cache => false,
-
:style => :compressed
-
}).render
-
end
-
end
-
end
-
1
require 'sass'
-
-
1
module Sprockets
-
1
module SassFunctions
-
1
def asset_path(path)
-
Sass::Script::String.new(sprockets_context.asset_path(path.value), :string)
-
end
-
-
1
def asset_url(path)
-
Sass::Script::String.new("url(" + sprockets_context.asset_path(path.value) + ")")
-
end
-
-
1
def image_path(path)
-
Sass::Script::String.new(sprockets_context.image_path(path.value), :string)
-
end
-
-
1
def image_url(path)
-
Sass::Script::String.new("url(" + sprockets_context.image_path(path.value) + ")")
-
end
-
-
1
def video_path(path)
-
Sass::Script::String.new(sprockets_context.video_path(path.value), :string)
-
end
-
-
1
def video_url(path)
-
Sass::Script::String.new("url(" + sprockets_context.video_path(path.value) + ")")
-
end
-
-
1
def audio_path(path)
-
Sass::Script::String.new(sprockets_context.audio_path(path.value), :string)
-
end
-
-
1
def audio_url(path)
-
Sass::Script::String.new("url(" + sprockets_context.audio_path(path.value) + ")")
-
end
-
-
1
def font_path(path)
-
Sass::Script::String.new(sprockets_context.font_path(path.value), :string)
-
end
-
-
1
def font_url(path)
-
Sass::Script::String.new("url(" + sprockets_context.font_path(path.value) + ")")
-
end
-
-
1
def javascript_path(path)
-
Sass::Script::String.new(sprockets_context.javascript_path(path.value), :string)
-
end
-
-
1
def javascript_url(path)
-
Sass::Script::String.new("url(" + sprockets_context.javascript_path(path.value) + ")")
-
end
-
-
1
def stylesheet_path(path)
-
Sass::Script::String.new(sprockets_context.stylesheet_path(path.value), :string)
-
end
-
-
1
def stylesheet_url(path)
-
Sass::Script::String.new("url(" + sprockets_context.stylesheet_path(path.value) + ")")
-
end
-
-
1
protected
-
1
def sprockets_context
-
options[:sprockets][:context]
-
end
-
-
1
def sprockets_environment
-
options[:sprockets][:environment]
-
end
-
end
-
end
-
1
require 'sass'
-
-
1
module Sprockets
-
# This custom importer adds sprockets dependency tracking on to Sass
-
# `@import` statements. This makes the Sprockets and Sass caching
-
# systems work together.
-
1
class SassImporter < Sass::Importers::Filesystem
-
1
def initialize(context, root)
-
@context = context
-
super root.to_s
-
end
-
-
1
def find_relative(*args)
-
engine = super
-
if engine && (filename = engine.options[:filename])
-
@context.depend_on(filename)
-
end
-
engine
-
end
-
-
1
def find(*args)
-
engine = super
-
if engine && (filename = engine.options[:filename])
-
@context.depend_on(filename)
-
end
-
engine
-
end
-
end
-
end
-
1
require 'tilt'
-
-
1
module Sprockets
-
# This custom Tilt handler replaces the one built into Tilt. The
-
# main difference is that it uses a custom importer that plays nice
-
# with sprocket's caching system.
-
#
-
# See `SassImporter` for more infomation.
-
1
class SassTemplate < Tilt::Template
-
1
self.default_mime_type = 'text/css'
-
-
1
def self.engine_initialized?
-
defined?(::Sass::Engine) && defined?(::Sass::Script::Functions) &&
-
::Sass::Script::Functions < Sprockets::SassFunctions
-
end
-
-
1
def initialize_engine
-
# Double check constant to avoid tilt warning
-
unless defined? ::Sass
-
require_template_library 'sass'
-
end
-
-
# Install custom functions. It'd be great if this didn't need to
-
# be installed globally, but could be passed into Engine as an
-
# option.
-
::Sass::Script::Functions.send :include, Sprockets::SassFunctions
-
end
-
-
1
def prepare
-
end
-
-
1
def syntax
-
:sass
-
end
-
-
1
def evaluate(context, locals, &block)
-
# Use custom importer that knows about Sprockets Caching
-
cache_store = SassCacheStore.new(context.environment)
-
-
options = {
-
:filename => eval_file,
-
:line => line,
-
:syntax => syntax,
-
:cache_store => cache_store,
-
:importer => SassImporter.new(context, context.pathname),
-
:load_paths => context.environment.paths.map { |path| SassImporter.new(context, path) },
-
:sprockets => {
-
:context => context,
-
:environment => context.environment
-
}
-
}
-
-
::Sass::Engine.new(data, options).render
-
rescue ::Sass::SyntaxError => e
-
# Annotates exception message with parse line number
-
context.__LINE__ = e.sass_backtrace.first[:line]
-
raise e
-
end
-
end
-
end
-
1
require 'sprockets/sass_template'
-
-
1
module Sprockets
-
# Scss handler to replace Tilt's builtin one. See `SassTemplate` and
-
# `SassImporter` for more infomation.
-
1
class ScssTemplate < SassTemplate
-
1
self.default_mime_type = 'text/css'
-
-
1
def syntax
-
:scss
-
end
-
end
-
end
-
1
require 'time'
-
1
require 'uri'
-
-
1
module Sprockets
-
# `Server` is a concern mixed into `Environment` and
-
# `Index` that provides a Rack compatible `call`
-
# interface and url generation helpers.
-
1
module Server
-
# `call` implements the Rack 1.x specification which accepts an
-
# `env` Hash and returns a three item tuple with the status code,
-
# headers, and body.
-
#
-
# Mapping your environment at a url prefix will serve all assets
-
# in the path.
-
#
-
# map "/assets" do
-
# run Sprockets::Environment.new
-
# end
-
#
-
# A request for `"/assets/foo/bar.js"` will search your
-
# environment for `"foo/bar.js"`.
-
1
def call(env)
-
start_time = Time.now.to_f
-
time_elapsed = lambda { ((Time.now.to_f - start_time) * 1000).to_i }
-
-
msg = "Served asset #{env['PATH_INFO']} -"
-
-
# Mark session as "skipped" so no `Set-Cookie` header is set
-
env['rack.session.options'] ||= {}
-
env['rack.session.options'][:defer] = true
-
env['rack.session.options'][:skip] = true
-
-
# Extract the path from everything after the leading slash
-
path = unescape(env['PATH_INFO'].to_s.sub(/^\//, ''))
-
-
# URLs containing a `".."` are rejected for security reasons.
-
if forbidden_request?(path)
-
return forbidden_response
-
end
-
-
# Strip fingerprint
-
if fingerprint = path_fingerprint(path)
-
path = path.sub("-#{fingerprint}", '')
-
end
-
-
# Look up the asset.
-
asset = find_asset(path, :bundle => !body_only?(env))
-
-
# `find_asset` returns nil if the asset doesn't exist
-
if asset.nil?
-
logger.info "#{msg} 404 Not Found (#{time_elapsed.call}ms)"
-
-
# Return a 404 Not Found
-
not_found_response
-
-
# Check request headers `HTTP_IF_NONE_MATCH` against the asset digest
-
elsif etag_match?(asset, env)
-
logger.info "#{msg} 304 Not Modified (#{time_elapsed.call}ms)"
-
-
# Return a 304 Not Modified
-
not_modified_response(asset, env)
-
-
else
-
logger.info "#{msg} 200 OK (#{time_elapsed.call}ms)"
-
-
# Return a 200 with the asset contents
-
ok_response(asset, env)
-
end
-
rescue Exception => e
-
logger.error "Error compiling asset #{path}:"
-
logger.error "#{e.class.name}: #{e.message}"
-
-
case content_type_of(path)
-
when "application/javascript"
-
# Re-throw JavaScript asset exceptions to the browser
-
logger.info "#{msg} 500 Internal Server Error\n\n"
-
return javascript_exception_response(e)
-
when "text/css"
-
# Display CSS asset exceptions in the browser
-
logger.info "#{msg} 500 Internal Server Error\n\n"
-
return css_exception_response(e)
-
else
-
raise
-
end
-
end
-
-
1
private
-
1
def forbidden_request?(path)
-
# Prevent access to files elsewhere on the file system
-
#
-
# http://example.org/assets/../../../etc/passwd
-
#
-
path.include?("..")
-
end
-
-
# Returns a 403 Forbidden response tuple
-
1
def forbidden_response
-
[ 403, { "Content-Type" => "text/plain", "Content-Length" => "9" }, [ "Forbidden" ] ]
-
end
-
-
# Returns a 404 Not Found response tuple
-
1
def not_found_response
-
[ 404, { "Content-Type" => "text/plain", "Content-Length" => "9", "X-Cascade" => "pass" }, [ "Not found" ] ]
-
end
-
-
# Returns a JavaScript response that re-throws a Ruby exception
-
# in the browser
-
1
def javascript_exception_response(exception)
-
err = "#{exception.class.name}: #{exception.message}"
-
body = "throw Error(#{err.inspect})"
-
[ 200, { "Content-Type" => "application/javascript", "Content-Length" => Rack::Utils.bytesize(body).to_s }, [ body ] ]
-
end
-
-
# Returns a CSS response that hides all elements on the page and
-
# displays the exception
-
1
def css_exception_response(exception)
-
message = "\n#{exception.class.name}: #{exception.message}"
-
backtrace = "\n #{exception.backtrace.first}"
-
-
body = <<-CSS
-
html {
-
padding: 18px 36px;
-
}
-
-
head {
-
display: block;
-
}
-
-
body {
-
margin: 0;
-
padding: 0;
-
}
-
-
body > * {
-
display: none !important;
-
}
-
-
head:after, body:before, body:after {
-
display: block !important;
-
}
-
-
head:after {
-
font-family: sans-serif;
-
font-size: large;
-
font-weight: bold;
-
content: "Error compiling CSS asset";
-
}
-
-
body:before, body:after {
-
font-family: monospace;
-
white-space: pre-wrap;
-
}
-
-
body:before {
-
font-weight: bold;
-
content: "#{escape_css_content(message)}";
-
}
-
-
body:after {
-
content: "#{escape_css_content(backtrace)}";
-
}
-
CSS
-
-
[ 200, { "Content-Type" => "text/css;charset=utf-8", "Content-Length" => Rack::Utils.bytesize(body).to_s }, [ body ] ]
-
end
-
-
# Escape special characters for use inside a CSS content("...") string
-
1
def escape_css_content(content)
-
content.
-
gsub('\\', '\\\\005c ').
-
gsub("\n", '\\\\000a ').
-
gsub('"', '\\\\0022 ').
-
gsub('/', '\\\\002f ')
-
end
-
-
# Compare the requests `HTTP_IF_NONE_MATCH` against the assets digest
-
1
def etag_match?(asset, env)
-
env["HTTP_IF_NONE_MATCH"] == etag(asset)
-
end
-
-
# Test if `?body=1` or `body=true` query param is set
-
1
def body_only?(env)
-
env["QUERY_STRING"].to_s =~ /body=(1|t)/
-
end
-
-
# Returns a 304 Not Modified response tuple
-
1
def not_modified_response(asset, env)
-
[ 304, {}, [] ]
-
end
-
-
# Returns a 200 OK response tuple
-
1
def ok_response(asset, env)
-
[ 200, headers(env, asset, asset.length), asset ]
-
end
-
-
1
def headers(env, asset, length)
-
Hash.new.tap do |headers|
-
# Set content type and length headers
-
headers["Content-Type"] = asset.content_type
-
headers["Content-Length"] = length.to_s
-
-
# Set caching headers
-
headers["Cache-Control"] = "public"
-
headers["Last-Modified"] = asset.mtime.httpdate
-
headers["ETag"] = etag(asset)
-
-
# If the request url contains a fingerprint, set a long
-
# expires on the response
-
if path_fingerprint(env["PATH_INFO"])
-
headers["Cache-Control"] << ", max-age=31536000"
-
-
# Otherwise set `must-revalidate` since the asset could be modified.
-
else
-
headers["Cache-Control"] << ", must-revalidate"
-
end
-
end
-
end
-
-
# Gets digest fingerprint.
-
#
-
# "foo-0aa2105d29558f3eb790d411d7d8fb66.js"
-
# # => "0aa2105d29558f3eb790d411d7d8fb66"
-
#
-
1
def path_fingerprint(path)
-
path[/-([0-9a-f]{7,40})\.[^.]+$/, 1]
-
end
-
-
# URI.unescape is deprecated on 1.9. We need to use URI::Parser
-
# if its available.
-
1
if defined? URI::DEFAULT_PARSER
-
1
def unescape(str)
-
str = URI::DEFAULT_PARSER.unescape(str)
-
str.force_encoding(Encoding.default_internal) if Encoding.default_internal
-
str
-
end
-
else
-
def unescape(str)
-
URI.unescape(str)
-
end
-
end
-
-
# Helper to quote the assets digest for use as an ETag.
-
1
def etag(asset)
-
%("#{asset.digest}")
-
end
-
end
-
end
-
1
require 'sprockets/asset'
-
1
require 'fileutils'
-
1
require 'zlib'
-
-
1
module Sprockets
-
# `StaticAsset`s are used for files that are served verbatim without
-
# any processing or concatenation. These are typical images and
-
# other binary files.
-
1
class StaticAsset < Asset
-
# Returns file contents as its `source`.
-
1
def source
-
# File is read everytime to avoid memory bloat of large binary files
-
pathname.open('rb') { |f| f.read }
-
end
-
-
# Implemented for Rack SendFile support.
-
1
def to_path
-
pathname.to_s
-
end
-
-
# Save asset to disk.
-
1
def write_to(filename, options = {})
-
# Gzip contents if filename has '.gz'
-
options[:compress] ||= File.extname(filename) == '.gz'
-
-
FileUtils.mkdir_p File.dirname(filename)
-
-
if options[:compress]
-
# Open file and run it through `Zlib`
-
pathname.open('rb') do |rd|
-
File.open("#{filename}+", 'wb') do |wr|
-
gz = Zlib::GzipWriter.new(wr, Zlib::BEST_COMPRESSION)
-
gz.mtime = mtime.to_i
-
buf = ""
-
while rd.read(16384, buf)
-
gz.write(buf)
-
end
-
gz.close
-
end
-
end
-
else
-
# If no compression needs to be done, we can just copy it into place.
-
FileUtils.cp(pathname, "#{filename}+")
-
end
-
-
# Atomic write
-
FileUtils.mv("#{filename}+", filename)
-
-
# Set mtime correctly
-
File.utime(mtime, mtime, filename)
-
-
nil
-
ensure
-
# Ensure tmp file gets cleaned up
-
FileUtils.rm("#{filename}+") if File.exist?("#{filename}+")
-
end
-
end
-
end
-
1
require 'tilt'
-
-
1
module Sprockets
-
1
class UglifierCompressor < Tilt::Template
-
1
self.default_mime_type = 'application/javascript'
-
-
1
def self.engine_initialized?
-
defined?(::Uglifier)
-
end
-
-
1
def initialize_engine
-
require_template_library 'uglifier'
-
end
-
-
1
def prepare
-
end
-
-
1
def evaluate(context, locals, &block)
-
# Feature detect Uglifier 2.0 option support
-
if Uglifier::DEFAULTS[:copyright]
-
# Uglifier < 2.x
-
Uglifier.new(:copyright => false).compile(data)
-
else
-
# Uglifier >= 2.x
-
Uglifier.new(:comments => :none).compile(data)
-
end
-
end
-
end
-
end
-
1
module Sprockets
-
# `Utils`, we didn't know where else to put it!
-
1
module Utils
-
# If theres encoding support (aka Ruby 1.9)
-
1
if "".respond_to?(:valid_encoding?)
-
# Define UTF-8 BOM pattern matcher.
-
# Avoid using a Regexp literal because it inheirts the files
-
# encoding and we want to avoid syntax errors in other interpreters.
-
1
UTF8_BOM_PATTERN = Regexp.new("\\A\uFEFF".encode('utf-8'))
-
-
1
def self.read_unicode(pathname, external_encoding = Encoding.default_external)
-
pathname.open("r:#{external_encoding}") do |f|
-
f.read.tap do |data|
-
# Eager validate the file's encoding. In most cases we
-
# expect it to be UTF-8 unless `default_external` is set to
-
# something else. An error is usually raised if the file is
-
# saved as UTF-16 when we expected UTF-8.
-
if !data.valid_encoding?
-
raise EncodingError, "#{pathname} has a invalid " +
-
"#{data.encoding} byte sequence"
-
-
# If the file is UTF-8 and theres a BOM, strip it for safe concatenation.
-
elsif data.encoding.name == "UTF-8" && data =~ UTF8_BOM_PATTERN
-
data.sub!(UTF8_BOM_PATTERN, "")
-
end
-
end
-
end
-
end
-
-
else
-
# Define UTF-8 and UTF-16 BOM pattern matchers.
-
# Avoid using a Regexp literal to prevent syntax errors in other interpreters.
-
UTF8_BOM_PATTERN = Regexp.new("\\A\\xEF\\xBB\\xBF")
-
UTF16_BOM_PATTERN = Regexp.new("\\A(\\xFE\\xFF|\\xFF\\xFE)")
-
-
def self.read_unicode(pathname)
-
pathname.read.tap do |data|
-
# If the file is UTF-8 and theres a BOM, strip it for safe concatenation.
-
if data =~ UTF8_BOM_PATTERN
-
data.sub!(UTF8_BOM_PATTERN, "")
-
-
# If we find a UTF-16 BOM, theres nothing we can do on
-
# 1.8. Only UTF-8 is supported.
-
elsif data =~ UTF16_BOM_PATTERN
-
raise EncodingError, "#{pathname} has a UTF-16 BOM. " +
-
"Resave the file as UTF-8 or upgrade to Ruby 1.9."
-
end
-
end
-
end
-
end
-
-
# Prepends a leading "." to an extension if its missing.
-
#
-
# normalize_extension("js")
-
# # => ".js"
-
#
-
# normalize_extension(".css")
-
# # => ".css"
-
#
-
1
def self.normalize_extension(extension)
-
14
extension = extension.to_s
-
14
if extension[/^\./]
-
12
extension
-
else
-
2
".#{extension}"
-
end
-
end
-
end
-
end
-
1
module Sprockets
-
1
VERSION = "2.11.0"
-
end
-
1
require 'tilt'
-
-
1
module Sprockets
-
1
class YUICompressor < Tilt::Template
-
1
def self.engine_initialized?
-
defined?(::YUI)
-
end
-
-
1
def initialize_engine
-
require_template_library 'yui/compressor'
-
end
-
-
1
def prepare
-
end
-
-
1
def evaluate(context, locals, &block)
-
case context.content_type
-
when 'application/javascript'
-
YUI::JavaScriptCompressor.new.compress(data)
-
when 'text/css'
-
YUI::CssCompressor.new.compress(data)
-
else
-
data
-
end
-
end
-
end
-
end
-
1
require 'action_view'
-
1
require 'sprockets'
-
1
require 'active_support/core_ext/class/attribute'
-
-
1
module Sprockets
-
1
module Rails
-
1
module Helper
-
1
class << self
-
1
attr_accessor :precompile, :assets, :raise_runtime_errors
-
end
-
-
1
def precompile
-
Sprockets::Rails::Helper.precompile
-
end
-
-
1
def assets
-
Sprockets::Rails::Helper.assets
-
end
-
-
1
def raise_runtime_errors
-
Sprockets::Rails::Helper.raise_runtime_errors
-
end
-
-
1
class AssetFilteredError < StandardError
-
1
def initialize(source)
-
msg = "Asset filtered out and will not be served: " <<
-
"add `Rails.application.config.assets.precompile += %w( #{source} )` " <<
-
"to `config/initializers/assets.rb` and restart your server"
-
super(msg)
-
end
-
end
-
-
1
class AbsoluteAssetPathError < ArgumentError
-
1
def initialize(bad_path, good_path, prefix)
-
msg = "Asset names passed to helpers should not include the #{prefix.inspect} prefix. " <<
-
"Instead of #{bad_path.inspect}, use #{good_path.inspect}"
-
super(msg)
-
end
-
end
-
-
1
if defined? ActionView::Helpers::AssetUrlHelper
-
1
include ActionView::Helpers::AssetUrlHelper
-
1
include ActionView::Helpers::AssetTagHelper
-
else
-
require 'sprockets/rails/legacy_asset_tag_helper'
-
require 'sprockets/rails/legacy_asset_url_helper'
-
include LegacyAssetTagHelper
-
include LegacyAssetUrlHelper
-
end
-
-
1
VIEW_ACCESSORS = [:assets_environment, :assets_manifest,
-
:assets_prefix, :digest_assets, :debug_assets]
-
-
1
def self.included(klass)
-
2
if klass < Sprockets::Context
-
1
klass.class_eval do
-
1
alias_method :assets_environment, :environment
-
1
def assets_manifest; end
-
1
class_attribute :config, :assets_prefix, :digest_assets, :debug_assets
-
end
-
else
-
1
klass.class_attribute(*VIEW_ACCESSORS)
-
end
-
end
-
-
1
def self.extended(obj)
-
obj.class_eval do
-
attr_accessor(*VIEW_ACCESSORS)
-
end
-
end
-
-
1
def compute_asset_path(path, options = {})
-
# Check if we are inside Sprockets context before calling check_dependencies!.
-
check_dependencies!(path) if defined?(depend_on)
-
-
if digest_path = asset_digest_path(path)
-
path = digest_path if digest_assets
-
path += "?body=1" if options[:debug]
-
File.join(assets_prefix || "/", path)
-
else
-
super
-
end
-
end
-
-
# Computes the full URL to a asset in the public directory. This
-
# method checks for errors before returning path.
-
1
def asset_path(source, options = {})
-
unless options[:debug]
-
check_errors_for(source, options)
-
end
-
super(source, options)
-
end
-
1
alias :path_to_asset :asset_path
-
-
# Get digest for asset path.
-
#
-
# path - String path
-
# options - Hash options
-
#
-
# Returns String Hex digest or nil if digests are disabled.
-
1
def asset_digest(path, options = {})
-
return unless digest_assets
-
-
if digest_path = asset_digest_path(path, options)
-
digest_path[/-(.+)\./, 1]
-
end
-
end
-
-
# Expand asset path to digested form.
-
#
-
# path - String path
-
# options - Hash options
-
#
-
# Returns String path or nil if no asset was found.
-
1
def asset_digest_path(path, options = {})
-
if manifest = assets_manifest
-
if digest_path = manifest.assets[path]
-
return digest_path
-
end
-
end
-
-
if environment = assets_environment
-
if asset = environment[path]
-
return asset.digest_path
-
end
-
end
-
end
-
-
# Override javascript tag helper to provide debugging support.
-
#
-
# Eventually will be deprecated and replaced by source maps.
-
1
def javascript_include_tag(*sources)
-
options = sources.extract_options!.stringify_keys
-
-
if options["debug"] != false && request_debug_assets?
-
sources.map { |source|
-
check_errors_for(source, :type => :javascript)
-
if asset = lookup_asset_for_path(source, :type => :javascript)
-
asset.to_a.map do |a|
-
super(path_to_javascript(a.logical_path, :debug => true), options)
-
end
-
else
-
super(source, options)
-
end
-
}.flatten.uniq.join("\n").html_safe
-
else
-
sources.push(options)
-
super(*sources)
-
end
-
end
-
-
# Override stylesheet tag helper to provide debugging support.
-
#
-
# Eventually will be deprecated and replaced by source maps.
-
1
def stylesheet_link_tag(*sources)
-
options = sources.extract_options!.stringify_keys
-
if options["debug"] != false && request_debug_assets?
-
sources.map { |source|
-
check_errors_for(source, :type => :stylesheet)
-
if asset = lookup_asset_for_path(source, :type => :stylesheet)
-
asset.to_a.map do |a|
-
super(path_to_stylesheet(a.logical_path, :debug => true), options)
-
end
-
else
-
super(source, options)
-
end
-
}.flatten.uniq.join("\n").html_safe
-
else
-
sources.push(options)
-
super(*sources)
-
end
-
end
-
-
1
protected
-
# Ensures the asset is included in the dependencies list.
-
1
def check_dependencies!(dep)
-
depend_on(dep)
-
depend_on_asset(dep)
-
rescue Sprockets::FileNotFound
-
end
-
-
# Raise errors when source is not in the precompiled list, or
-
# incorrectly contains the assets_prefix.
-
1
def check_errors_for(source, options)
-
return unless self.raise_runtime_errors
-
-
source = source.to_s
-
return if source.blank? || source =~ URI_REGEXP
-
-
asset = lookup_asset_for_path(source, options)
-
-
if asset && asset_needs_precompile?(asset.logical_path, asset.pathname.to_s)
-
raise AssetFilteredError.new(asset.logical_path)
-
end
-
-
full_prefix = File.join(self.assets_prefix || "/", '')
-
if !asset && source.start_with?(full_prefix)
-
short_path = source[full_prefix.size, source.size]
-
if lookup_asset_for_path(short_path, options)
-
raise AbsoluteAssetPathError.new(source, short_path, full_prefix)
-
end
-
end
-
end
-
-
# Returns true when an asset will not be available after precompile is run
-
1
def asset_needs_precompile?(source, filename)
-
if assets_environment && assets_environment.send(:matches_filter, precompile || [], source, filename)
-
false
-
else
-
true
-
end
-
end
-
-
# Enable split asset debugging. Eventually will be deprecated
-
# and replaced by source maps in Sprockets 3.x.
-
1
def request_debug_assets?
-
debug_assets || (defined?(controller) && controller && params[:debug_assets])
-
rescue
-
return false
-
end
-
-
# Internal method to support multifile debugging. Will
-
# eventually be removed w/ Sprockets 3.x.
-
1
def lookup_asset_for_path(path, options = {})
-
return unless env = assets_environment
-
path = path.to_s
-
if extname = compute_asset_extname(path, options)
-
path = "#{path}#{extname}"
-
end
-
env[path]
-
end
-
end
-
end
-
end
-
1
module Sprockets
-
1
module Rails
-
1
VERSION = "2.1.4"
-
end
-
end
-
1
require 'rails'
-
1
require 'rails/railtie'
-
1
require 'action_controller/railtie'
-
1
require 'active_support/core_ext/module/remove_method'
-
1
require 'sprockets'
-
1
require 'sprockets/rails/helper'
-
1
require 'sprockets/rails/version'
-
-
1
module Rails
-
1
class Application
-
# Hack: We need to remove Rails' built in config.assets so we can
-
# do our own thing.
-
1
class Configuration
-
1
remove_possible_method :assets
-
end
-
-
# Undefine Rails' assets method before redefining it, to avoid warnings.
-
1
remove_possible_method :assets
-
1
remove_possible_method :assets=
-
-
# Returns Sprockets::Environment for app config.
-
1
def assets
-
@assets ||= Sprockets::Environment.new(root.to_s) do |env|
-
1
env.version = ::Rails.env
-
-
1
path = "#{config.root}/tmp/cache/assets/#{::Rails.env}"
-
1
env.cache = Sprockets::Cache::FileStore.new(path)
-
-
1
env.context_class.class_eval do
-
1
include ::Sprockets::Rails::Helper
-
end
-
44
end
-
end
-
1
attr_writer :assets
-
end
-
end
-
-
1
module Sprockets
-
1
class Railtie < ::Rails::Railtie
-
1
LOOSE_APP_ASSETS = lambda do |filename, path|
-
path =~ /app\/assets/ && !%w(.js .css).include?(File.extname(filename))
-
end
-
-
1
class OrderedOptions < ActiveSupport::OrderedOptions
-
1
def configure(&block)
-
self._blocks << block
-
end
-
end
-
-
1
config.assets = OrderedOptions.new
-
1
config.assets._blocks = []
-
1
config.assets.paths = []
-
1
config.assets.prefix = "/assets"
-
1
config.assets.manifest = nil
-
1
config.assets.precompile = [LOOSE_APP_ASSETS, /(?:\/|\\|\A)application\.(css|js)$/]
-
1
config.assets.version = ""
-
1
config.assets.debug = false
-
1
config.assets.compile = true
-
1
config.assets.digest = false
-
-
1
rake_tasks do |app|
-
require 'sprockets/rails/task'
-
Sprockets::Rails::Task.new(app)
-
end
-
-
1
config.after_initialize do |app|
-
1
config = app.config
-
-
1
manifest_assets_path = File.join(config.paths['public'].first, config.assets.prefix)
-
-
# Configuration options that should invalidate
-
# the Sprockets cache when changed.
-
1
app.assets.version = [
-
app.assets.version,
-
config.assets.version,
-
config.action_controller.relative_url_root,
-
1
(config.action_controller.asset_host unless config.action_controller.asset_host.respond_to?(:call)),
-
Sprockets::Rails::VERSION
-
].compact.join('-')
-
-
# Copy config.assets.paths to Sprockets
-
1
config.assets.paths.each do |path|
-
28
app.assets.append_path path
-
end
-
-
1
ActiveSupport.on_load(:action_view) do
-
1
include Sprockets::Rails::Helper
-
-
# Copy relevant config to AV context
-
1
self.debug_assets = config.assets.debug
-
1
self.digest_assets = config.assets.digest
-
1
self.assets_prefix = config.assets.prefix
-
-
# Copy over to Sprockets as well
-
1
context = app.assets.context_class
-
1
context.assets_prefix = config.assets.prefix
-
1
context.digest_assets = config.assets.digest
-
1
context.config = config.action_controller
-
-
1
if config.assets.compile
-
1
self.assets_environment = app.assets
-
1
self.assets_manifest = Sprockets::Manifest.new(app.assets, manifest_assets_path, config.assets.manifest)
-
else
-
self.assets_manifest = Sprockets::Manifest.new(manifest_assets_path, config.assets.manifest)
-
end
-
end
-
-
1
app.assets.js_compressor = config.assets.js_compressor
-
1
app.assets.css_compressor = config.assets.css_compressor
-
-
# Run app.assets.configure blocks
-
1
config.assets._blocks.each do |block|
-
block.call app.assets
-
end
-
-
# No more configuration changes at this point.
-
# With cache classes on, Sprockets won't check the FS when files
-
# change. Preferable in production when the FS only changes on
-
# deploys when the app restarts.
-
1
if config.cache_classes
-
1
app.assets = app.assets.index
-
end
-
-
-
1
Sprockets::Rails::Helper.precompile ||= app.config.assets.precompile
-
1
Sprockets::Rails::Helper.assets ||= app.assets
-
1
Sprockets::Rails::Helper.raise_runtime_errors = app.config.assets.raise_runtime_errors
-
-
1
if config.assets.compile
-
1
if app.routes.respond_to?(:prepend)
-
1
app.routes.prepend do
-
1
mount app.assets => config.assets.prefix
-
end
-
end
-
end
-
end
-
end
-
end
-
# # Subexec
-
# * by Peter Kieltyka
-
# * http://github/nulayer/subexec
-
#
-
# ## Description
-
#
-
# Subexec is a simple library that spawns an external command with
-
# an optional timeout parameter. It relies on Ruby 1.9's Process.spawn
-
# method. Also, it works with synchronous and asynchronous code.
-
#
-
# Useful for libraries that are Ruby wrappers for CLI's. For example,
-
# resizing images with ImageMagick's mogrify command sometimes stalls
-
# and never returns control back to the original process. Subexec
-
# executes mogrify and preempts if it gets lost.
-
#
-
# ## Usage
-
#
-
# # Print hello
-
# sub = Subexec.run "echo 'hello' && sleep 3", :timeout => 5
-
# puts sub.output # returns: hello
-
# puts sub.exitstatus # returns: 0
-
#
-
# # Timeout process after a second
-
# sub = Subexec.run "echo 'hello' && sleep 3", :timeout => 1
-
# puts sub.output # returns:
-
# puts sub.exitstatus # returns:
-
-
1
class Subexec
-
1
VERSION = '0.2.3'
-
-
1
attr_accessor :pid,
-
:command,
-
:lang,
-
:output,
-
:exitstatus,
-
:timeout,
-
:log_file
-
-
1
def self.run(command, options={})
-
sub = new(command, options)
-
sub.run!
-
sub
-
end
-
-
1
def initialize(command, options={})
-
self.command = command
-
self.lang = options[:lang] || "C"
-
self.timeout = options[:timeout] || -1 # default is to never timeout
-
self.log_file = options[:log_file]
-
self.exitstatus = 0
-
end
-
-
1
def run!
-
if RUBY_VERSION >= '1.9' && RUBY_ENGINE != 'jruby'
-
spawn
-
else
-
exec
-
end
-
end
-
-
-
1
private
-
-
1
def spawn
-
# TODO: weak implementation for log_file support.
-
# Ideally, the data would be piped through to both descriptors
-
r, w = IO.pipe
-
-
log_to_file = !log_file.nil?
-
log_opts = log_to_file ? {[:out, :err] => [log_file, 'a']} : {STDERR=>w, STDOUT=>w}
-
self.pid = Process.spawn({'LANG' => self.lang}, command, log_opts)
-
w.close
-
-
@timer = Time.now + timeout
-
timed_out = false
-
-
self.output = ''
-
-
append_to_output = Proc.new do
-
self.output << r.readlines.join('') unless log_to_file
-
end
-
-
loop do
-
ret = begin
-
Process.waitpid(pid, Process::WUNTRACED|Process::WNOHANG)
-
rescue Errno::ECHILD
-
break
-
end
-
-
break if ret == pid
-
-
append_to_output.call
-
-
if timeout > 0 && Time.now > @timer
-
timed_out = true
-
break
-
end
-
-
sleep 0.01
-
end
-
-
if timed_out
-
# The subprocess timed out -- kill it
-
Process.kill(9, pid) rescue Errno::ESRCH
-
self.exitstatus = nil
-
else
-
# The subprocess exited on its own
-
self.exitstatus = $?.exitstatus
-
append_to_output.call
-
end
-
r.close
-
-
self
-
end
-
-
1
def exec
-
if !(RUBY_PLATFORM =~ /win32|mswin|mingw/).nil?
-
self.output = `set LANG=#{lang} && #{command} 2>&1`
-
else
-
self.output = `LANG=#{lang} && export LANG && #{command} 2>&1`
-
end
-
self.exitstatus = $?.exitstatus
-
end
-
-
end
-
1
require "v8/version"
-
-
1
require 'v8/weak'
-
1
require 'v8/init'
-
1
require 'v8/error'
-
1
require 'v8/stack'
-
1
require 'v8/conversion/fundamental'
-
1
require 'v8/conversion/indentity'
-
1
require 'v8/conversion/reference'
-
1
require 'v8/conversion/primitive'
-
1
require 'v8/conversion/code'
-
1
require 'v8/conversion/class'
-
1
require 'v8/conversion/object'
-
1
require 'v8/conversion/time'
-
1
require 'v8/conversion/hash'
-
1
require 'v8/conversion/array'
-
1
require 'v8/conversion/proc'
-
1
require 'v8/conversion/method'
-
1
require 'v8/conversion/symbol'
-
1
require 'v8/conversion/string'
-
1
require 'v8/conversion/fixnum'
-
1
require 'v8/conversion'
-
1
require 'v8/access/names'
-
1
require 'v8/access/indices'
-
1
require 'v8/access/invocation'
-
1
require 'v8/access'
-
1
require 'v8/context'
-
1
require 'v8/object'
-
1
require 'v8/array'
-
1
require 'v8/function'
-
1
class V8::Access
-
1
include Names
-
1
include Indices
-
1
include Invocation
-
end
-
1
class V8::Access
-
1
module Indices
-
-
1
def indices(obj)
-
obj.respond_to?(:length) ? (0..obj.length).to_a : []
-
end
-
-
1
def iget(obj, index, &dontintercept)
-
if obj.respond_to?(:[])
-
obj.send(:[], index, &dontintercept)
-
else
-
yield
-
end
-
end
-
-
1
def iset(obj, index, value, &dontintercept)
-
if obj.respond_to?(:[]=)
-
obj.send(:[]=, index, value, &dontintercept)
-
else
-
yield
-
end
-
end
-
-
1
def iquery(obj, index, attributes, &dontintercept)
-
if obj.respond_to?(:[])
-
attributes.dont_delete
-
unless obj.respond_to?(:[]=)
-
attributes.read_only
-
end
-
else
-
yield
-
end
-
end
-
-
1
def idelete(obj, index, &dontintercept)
-
yield
-
end
-
-
end
-
end
-
1
class V8::Access
-
1
module Invocation
-
1
def methodcall(code, this, args)
-
81
code.methodcall this, args
-
end
-
-
1
module Aritize
-
1
def aritize(args)
-
81
arity < 0 ? args : Array.new(arity).to_enum(:each_with_index).map {|item, i| args[i]}
-
end
-
end
-
-
1
module Proc
-
1
include Aritize
-
1
def methodcall(this, args)
-
81
call *aritize([this].concat(args))
-
end
-
1
::Proc.send :include, self
-
end
-
-
1
module Method
-
1
include Aritize
-
1
def methodcall(this, args)
-
context = V8::Context.current
-
access = context.access
-
if this.equal? self.receiver
-
call *aritize(args)
-
elsif this.class <= self.receiver.class
-
access.methodcall(unbind, this, args)
-
elsif this.equal? context.scope
-
call *aritize(args)
-
else
-
fail TypeError, "cannot invoke #{self} on #{this}"
-
end
-
end
-
1
::Method.send :include, self
-
end
-
-
1
module UnboundMethod
-
1
def methodcall(this, args)
-
access = V8::Context.current.access
-
access.methodcall bind(this), this, args
-
end
-
1
::UnboundMethod.send :include, self
-
end
-
end
-
end
-
1
require 'set'
-
1
class V8::Access
-
1
module Names
-
1
def names(obj)
-
accessible_names(obj)
-
end
-
-
1
def get(obj, name, &dontintercept)
-
methods = accessible_names(obj)
-
if methods.include?(name)
-
method = obj.method(name)
-
method.arity == 0 ? method.call : method.unbind
-
elsif obj.respond_to?(:[]) && !special?(name)
-
obj.send(:[], name, &dontintercept)
-
else
-
yield
-
end
-
end
-
-
1
def set(obj, name, value, &dontintercept)
-
setter = name + "="
-
methods = accessible_names(obj, true)
-
if methods.include?(setter)
-
obj.send(setter, value)
-
elsif obj.respond_to?(:[]=) && !special?(name)
-
obj.send(:[]=, name, value, &dontintercept)
-
else
-
yield
-
end
-
end
-
-
1
def query(obj, name, attributes, &dontintercept)
-
if obj.respond_to?(name)
-
attributes.dont_delete
-
unless obj.respond_to?(name + "=")
-
attributes.read_only
-
end
-
else
-
yield
-
end
-
end
-
-
1
def delete(obj, name, &dontintercept)
-
yield
-
end
-
-
1
def accessible_names(obj, special_methods = false)
-
obj.public_methods(false).map {|m| m.to_s}.to_set.tap do |methods|
-
ancestors = obj.class.ancestors.dup
-
while ancestor = ancestors.shift
-
break if ancestor == ::Object
-
methods.merge(ancestor.public_instance_methods(false).map {|m| m.to_s})
-
end
-
methods.reject!(&special?) unless special_methods
-
end
-
end
-
-
1
private
-
-
1
def special?(name = nil)
-
@special ||= lambda {|m| m == "[]" || m == "[]=" || m =~ /=$/}
-
name.nil? ? @special : @special[name]
-
end
-
end
-
end
-
1
class V8::Array < V8::Object
-
-
1
def initialize(native_or_length = nil)
-
super do
-
if native_or_length.is_a?(Numeric)
-
V8::C::Array::New(native_or_length)
-
elsif native_or_length.is_a?(V8::C::Array)
-
native_or_length
-
else
-
V8::C::Array::New()
-
end
-
end
-
end
-
-
1
def each
-
@context.enter do
-
0.upto(@native.Length() - 1) do |i|
-
yield @context.to_ruby(@native.Get(i))
-
end
-
end
-
end
-
-
1
def length
-
@native.Length()
-
end
-
end
-
# -*- coding: utf-8 -*-
-
1
require 'stringio'
-
1
module V8
-
# All JavaScript must be executed in a context. This context consists of a global scope containing the
-
# standard JavaScript objects¨and functions like Object, String, Array, as well as any objects or
-
# functions from Ruby which have been embedded into it from the containing enviroment. E.g.
-
#
-
# V8::Context.new do |cxt|
-
# cxt['num'] = 5
-
# cxt.eval('num + 5') #=> 10
-
# end
-
#
-
# The same object may appear in any number of contexts, but only one context may be executing JavaScript code
-
# in any given thread. If a new context is opened in a thread in which a context is already opened, the second
-
# context will "mask" the old context e.g.
-
#
-
# six = 6
-
# Context.new do |cxt|
-
# cxt['num'] = 5
-
# cxt.eval('num') # => 5
-
# Context.new do |cxt|
-
# cxt['num'] = 10
-
# cxt.eval('num') # => 10
-
# cxt.eval('++num') # => 11
-
# end
-
# cxt.eval('num') # => 5
-
# end
-
1
class Context
-
1
include V8::Error::Try
-
-
# @!attribute [r] conversion
-
# @return [V8::Conversion] conversion behavior for this context
-
1
attr_reader :conversion
-
-
# @!attrribute [r] access
-
# @return [V8::Access] Ruby access behavior for this context
-
1
attr_reader :access
-
-
# @!attribute [r] native
-
# @return [V8::C::Context] the underlying C++ object
-
1
attr_reader :native
-
-
# @!attribute [r] timeout
-
# @return [Number] maximum execution time in milliseconds for scripts executed in this context
-
1
attr_reader :timeout
-
-
# Creates a new context.
-
#
-
# If passed the `:with` option, that object will be used as
-
# the global scope of the newly creating context. e.g.
-
#
-
# scope = Object.new
-
# def scope.hello; "Hi"; end
-
# V8::Context.new(:with => scope) do |cxt|
-
# cxt['hello'] #=> 'Hi'
-
# end
-
#
-
# If passed the `:timeout` option, every eval will timeout once
-
# N milliseconds elapse
-
#
-
# @param [Hash<Symbol, Object>] options initial context configuration
-
# * :with scope serves as the global scope of the new context
-
# @yield [V8::Context] the newly created context
-
1
def initialize(options = {})
-
1
@conversion = Conversion.new
-
1
@access = Access.new
-
1
@timeout = options[:timeout]
-
1
if global = options[:with]
-
Context.new.enter do
-
global_template = global.class.to_template.InstanceTemplate()
-
@native = V8::C::Context::New(nil, global_template)
-
end
-
enter {link global, @native.Global()}
-
else
-
1
V8::C::Locker() do
-
1
@native = V8::C::Context::New()
-
end
-
end
-
1
yield self if block_given?
-
end
-
-
# Compile and execute a string of JavaScript source.
-
#
-
# If `source` is an IO object it will be read fully before being evaluated
-
#
-
# @param [String,IO] source the source code to compile and execute
-
# @param [String] filename the name to use for this code when generating stack traces
-
# @param [Integer] line the line number to start with
-
# @return [Object] the result of the evaluation
-
1
def eval(source, filename = '<eval>', line = 1)
-
40
if IO === source || StringIO === source
-
source = source.read
-
end
-
40
enter do
-
80
script = try { V8::C::Script::New(source.to_s, filename.to_s) }
-
40
if @timeout
-
to_ruby try {script.RunWithTimeout(@timeout)}
-
else
-
80
to_ruby try {script.Run()}
-
end
-
end
-
end
-
-
# Read a value from the global scope of this context
-
#
-
# @param [Object] key the name of the value to read
-
# @return [Object] value the value at `key`
-
1
def [](key)
-
40
enter do
-
40
to_ruby(@native.Global().Get(to_v8(key)))
-
end
-
end
-
-
# Binds `value` to the name `key` in the global scope of this context.
-
#
-
# @param [Object] key the name to bind to
-
# @param [Object] value the value to bind
-
1
def []=(key, value)
-
3
enter do
-
3
@native.Global().Set(to_v8(key), to_v8(value))
-
end
-
3
return value
-
end
-
-
# Destroy this context and release any internal references it may
-
# contain to embedded Ruby objects.
-
#
-
# A disposed context may never again be used for anything, and all
-
# objects created with it will become unusable.
-
1
def dispose
-
return unless @native
-
@native.Dispose()
-
@native = nil
-
V8::C::V8::ContextDisposedNotification()
-
def self.enter
-
fail "cannot enter a context which has already been disposed"
-
end
-
end
-
-
# Returns this context's global object. This will be a `V8::Object`
-
# if no scope was provided or just an `Object` if a Ruby object
-
# is serving as the global scope.
-
#
-
# @return [Object] scope the context's global scope.
-
1
def scope
-
enter { to_ruby @native.Global() }
-
end
-
-
# Converts a v8 C++ object into its ruby counterpart. This is method
-
# is used to translate all values passed to Ruby from JavaScript, either
-
# as return values or as callback parameters.
-
#
-
# @param [V8::C::Object] v8_object the native c++ object to convert.
-
# @return [Object] to pass to Ruby
-
# @see V8::Conversion for how to customize and extend this mechanism
-
1
def to_ruby(v8_object)
-
352
@conversion.to_ruby(v8_object)
-
end
-
-
# Converts a Ruby object into a native v8 C++ object. This method is
-
# used to translate all values passed to JavaScript from Ruby, either
-
# as return value or as callback parameters.
-
#
-
# @param [Object] ruby_object the Ruby object to convert
-
# @return [V8::C::Object] to pass to V8
-
# @see V8::Conversion for customizing and extending this mechanism
-
1
def to_v8(ruby_object)
-
392
@conversion.to_v8(ruby_object)
-
end
-
-
# Marks a Ruby object and a v8 C++ Object as being the same. In other
-
# words whenever `ruby_object` is passed to v8, the result of the
-
# conversion should be `v8_object`. Conversely, whenever `v8_object`
-
# is passed to Ruby, the result of the conversion should be `ruby_object`.
-
# The Ruby Racer uses this mechanism to maintain referential integrity
-
# between Ruby and JavaScript peers
-
#
-
# @param [Object] ruby_object the Ruby half of the object identity
-
# @param [V8::C::Object] v8_object the V8 half of the object identity.
-
# @see V8::Conversion::Identity
-
1
def link(ruby_object, v8_object)
-
188
@conversion.equate ruby_object, v8_object
-
end
-
-
# Links `ruby_object` and `v8_object` inside the currently entered
-
# context. This is an error if no context has been entered.
-
#
-
# @param [Object] ruby_object the Ruby half of the object identity
-
# @param [V8::C::Object] v8_object the V8 half of the object identity.
-
1
def self.link(ruby_object, v8_object)
-
60
current.link ruby_object, v8_object
-
end
-
-
# Run some Ruby code in the context of this context.
-
#
-
# This will acquire the V8 interpreter lock (possibly blocking
-
# until it is available), and prepare V8 for JavaScript execution.
-
#
-
# Only one context may be running at a time per thread.
-
#
-
# @return [Object] the result of executing `block`
-
1
def enter(&block)
-
248
if !entered?
-
52
lock_scope_and_enter(&block)
-
else
-
196
yield
-
end
-
end
-
-
# Indicates if this context is the currently entered context
-
#
-
# @return true if this context is currently entered
-
1
def entered?
-
248
Context.current == self
-
end
-
-
# Get the currently entered context.
-
#
-
# @return [V8::Context] currently entered context, nil if none entered.
-
1
def self.current
-
614
Thread.current[:v8_context]
-
end
-
-
# Compile and execute the contents of the file with path `filename`
-
# as JavaScript code.
-
#
-
# @param [String] filename path to the file to execute.
-
# @return [Object] the result of the evaluation.
-
1
def load(filename)
-
File.open(filename) do |file|
-
self.eval file, filename
-
end
-
end
-
-
1
private
-
-
1
def self.current=(context)
-
104
Thread.current[:v8_context] = context
-
end
-
-
1
def lock_scope_and_enter
-
52
current = Context.current
-
52
Context.current = self
-
52
V8::C::Locker() do
-
52
V8::C::HandleScope() do
-
52
begin
-
52
@native.Enter()
-
52
yield if block_given?
-
ensure
-
52
@native.Exit()
-
end
-
end
-
end
-
ensure
-
52
Context.current = current
-
end
-
end
-
end
-
-
1
class V8::Conversion
-
1
include Fundamental
-
1
include Identity
-
-
1
def to_ruby(v8_object)
-
352
super v8_object
-
end
-
-
1
def to_v8(ruby_object)
-
392
super ruby_object
-
end
-
end
-
-
1
for type in [TrueClass, FalseClass, NilClass, Float] do
-
4
type.class_eval do
-
4
include V8::Conversion::Primitive
-
end
-
end
-
-
1
for type in [Class, Object, Array, Hash, String, Symbol, Time, Proc, Method, Fixnum] do
-
10
type.class_eval do
-
10
include V8::Conversion.const_get(type.name)
-
end
-
end
-
-
1
class UnboundMethod
-
1
include V8::Conversion::Method
-
end
-
-
1
for type in [:Object, :String, :Date] do
-
3
V8::C::const_get(type).class_eval do
-
3
include V8::Conversion::const_get("Native#{type}")
-
end
-
end
-
-
1
class V8::Conversion
-
1
module Array
-
1
def to_v8
-
array = V8::Array.new(length)
-
each_with_index do |item, i|
-
array[i] = item
-
end
-
return array.to_v8
-
end
-
end
-
end
-
1
class V8::Conversion
-
1
module Class
-
1
include V8::Conversion::Code
-
-
1
def to_template
-
5
weakcell(:constructor) do
-
5
template = V8::C::FunctionTemplate::New(V8::Conversion::Constructor.new(self))
-
5
prototype = template.InstanceTemplate()
-
5
prototype.SetNamedPropertyHandler(V8::Conversion::Get, V8::Conversion::Set)
-
5
prototype.SetIndexedPropertyHandler(V8::Conversion::IGet, V8::Conversion::ISet)
-
5
if self != ::Object && superclass != ::Object && superclass != ::Class
-
template.Inherit(superclass.to_template)
-
end
-
5
template
-
end
-
end
-
end
-
-
1
class Constructor
-
1
include V8::Error::Protect
-
-
1
def initialize(cls)
-
5
@class = cls
-
end
-
-
1
def call(arguments)
-
45
arguments.extend Args
-
45
protect do
-
45
if arguments.linkage_call?
-
45
arguments.link
-
else
-
arguments.construct @class
-
end
-
end
-
45
return arguments.This()
-
end
-
-
1
module Args
-
1
def linkage_call?
-
45
self.Length() == 1 && self[0].IsExternal()
-
end
-
-
1
def link
-
45
external = self[0]
-
45
This().SetHiddenValue("rr::implementation", external)
-
45
context.link external.Value(), This()
-
end
-
-
1
def construct(cls)
-
context.link cls.new(*to_args), This()
-
end
-
-
1
def context
-
45
V8::Context.current
-
end
-
-
1
def to_args
-
args = ::Array.new(Length())
-
0.upto(args.length - 1) do |i|
-
args[i] = self[i]
-
end
-
return args
-
end
-
end
-
end
-
-
1
module Accessor
-
1
include V8::Error::Protect
-
1
def intercept(info, key, &block)
-
context = V8::Context.current
-
access = context.access
-
object = context.to_ruby(info.This())
-
handles_property = true
-
dontintercept = proc do
-
handles_property = false
-
end
-
protect do
-
result = block.call(context, access, object, context.to_ruby(key), dontintercept)
-
handles_property ? context.to_v8(result) : V8::C::Value::Empty
-
end
-
end
-
end
-
-
1
class Get
-
1
extend Accessor
-
1
def self.call(property, info)
-
intercept(info, property) do |context, access, object, key, dontintercept|
-
access.get(object, key, &dontintercept)
-
end
-
end
-
end
-
-
1
class Set
-
1
extend Accessor
-
1
def self.call(property, value, info)
-
intercept(info, property) do |context, access, object, key, dontintercept|
-
access.set(object, key, context.to_ruby(value), &dontintercept)
-
end
-
end
-
end
-
-
1
class IGet
-
1
extend Accessor
-
1
def self.call(property, info)
-
intercept(info, property) do |context, access, object, key, dontintercept|
-
access.iget(object, key, &dontintercept)
-
end
-
end
-
end
-
-
1
class ISet
-
1
extend Accessor
-
1
def self.call(property, value, info)
-
intercept(info, property) do |context, access, object, key, dontintercept|
-
access.iset(object, key, context.to_ruby(value), &dontintercept)
-
end
-
end
-
end
-
end
-
1
class V8::Conversion
-
1
module Code
-
1
include V8::Weak::Cell
-
-
1
def to_v8
-
60
fn = to_template.GetFunction()
-
60
V8::Context.link self, fn
-
60
return fn
-
end
-
-
1
def to_template
-
110
weakcell(:template) {V8::C::FunctionTemplate::New(InvocationHandler.new(self))}
-
end
-
-
1
class InvocationHandler
-
1
include V8::Error::Protect
-
-
1
def initialize(code)
-
55
@code = code
-
end
-
-
1
def call(arguments)
-
81
protect do
-
81
context = V8::Context.current
-
81
access = context.access
-
81
args = ::Array.new(arguments.Length())
-
81
0.upto(args.length - 1) do |i|
-
81
if i < args.length
-
81
args[i] = context.to_ruby arguments[i]
-
end
-
end
-
81
this = context.to_ruby arguments.This()
-
81
context.to_v8 access.methodcall(@code, this, args)
-
end
-
end
-
end
-
end
-
end
-
1
class V8::Conversion
-
1
module Fixnum
-
1
def to_ruby
-
self
-
end
-
-
1
def to_v8
-
self.to_f.to_v8
-
end
-
end
-
end
-
1
class V8::Conversion
-
1
module Fundamental
-
1
def to_ruby(v8_object)
-
204
v8_object.to_ruby
-
end
-
-
1
def to_v8(ruby_object)
-
233
ruby_object.to_v8
-
end
-
end
-
end
-
1
class V8::Conversion
-
1
module Hash
-
1
def to_v8
-
object = V8::Object.new
-
each do |key, value|
-
object[key] = value
-
end
-
return object.to_v8
-
end
-
end
-
end
-
1
require 'ref'
-
-
1
class V8::Conversion
-
1
module Identity
-
1
def to_ruby(v8_object)
-
352
if v8_object.class <= V8::C::Object
-
231
v8_idmap[v8_object.GetIdentityHash()] || super(v8_object)
-
else
-
121
super(v8_object)
-
end
-
end
-
-
1
def to_v8(ruby_object)
-
392
return super(ruby_object) if ruby_object.is_a?(String) || ruby_object.is_a?(Primitive)
-
334
rb_idmap[ruby_object.object_id] || super(ruby_object)
-
end
-
-
1
def equate(ruby_object, v8_object)
-
188
v8_idmap[v8_object.GetIdentityHash()] = ruby_object
-
188
rb_idmap[ruby_object.object_id] = v8_object
-
end
-
-
1
def v8_idmap
-
419
@v8_idmap ||= V8::Weak::WeakValueMap.new
-
end
-
-
1
def rb_idmap
-
522
@ruby_idmap ||= V8::Weak::WeakValueMap.new
-
end
-
end
-
end
-
1
class V8::Conversion
-
1
module Method
-
1
include V8::Conversion::Code
-
-
1
def to_v8
-
template = @@method_cache[self] ||= to_template
-
template.GetFunction()
-
end
-
-
1
class MethodCache
-
1
def initialize
-
1
@map = V8::Weak::WeakValueMap.new
-
end
-
-
1
def [](method)
-
@map[method.to_s]
-
end
-
-
1
def []=(method, template)
-
@map[method.to_s] = template
-
end
-
end
-
-
1
@@method_cache = MethodCache.new
-
end
-
end
-
1
class V8::Conversion
-
1
module Object
-
1
def to_v8
-
45
Reference.construct! self
-
end
-
-
1
def to_ruby
-
40
self
-
end
-
end
-
-
1
module NativeObject
-
1
def to_ruby
-
83
wrap = if IsArray()
-
::V8::Array
-
elsif IsFunction()
-
41
::V8::Function
-
else
-
42
::V8::Object
-
end
-
83
wrap.new(self)
-
end
-
-
1
def to_v8
-
40
self
-
end
-
end
-
end
-
1
class V8::Conversion
-
1
module Primitive
-
1
def to_v8
-
return self
-
end
-
end
-
end
-
1
class V8::Conversion
-
1
module Proc
-
1
include V8::Conversion::Code
-
end
-
end
-
1
class V8::Conversion
-
1
module Reference
-
-
1
def self.construct!(object)
-
45
context = V8::Context.current
-
45
constructor = context.to_v8(object.class)
-
45
reference = constructor.NewInstance([V8::C::External::New(object)])
-
45
return reference
-
end
-
-
1
def to_v8
-
Reference.construct! self
-
end
-
-
end
-
end
-
1
class V8::Conversion
-
1
module String
-
1
def to_v8
-
58
V8::C::String::New(self)
-
end
-
end
-
1
module NativeString
-
1
def to_ruby
-
81
self.Utf8Value()
-
end
-
end
-
end
-
1
class V8::Conversion
-
1
module Symbol
-
1
def to_v8
-
30
V8::C::String::NewSymbol(to_s)
-
end
-
end
-
end
-
1
class V8::Conversion
-
1
module Time
-
1
def to_v8
-
V8::C::Date::New(to_f * 1000)
-
end
-
end
-
-
1
module NativeDate
-
1
def to_ruby
-
::Time.at(self.NumberValue() / 1000)
-
end
-
end
-
end
-
1
module V8
-
# capture 99 stack frames on exception with normal details.
-
# You can adjust these values for performance or turn of stack capture entirely
-
1
V8::C::V8::SetCaptureStackTraceForUncaughtExceptions(true, 99, V8::C::StackTrace::kOverview)
-
1
class Error < StandardError
-
1
include Enumerable
-
-
# @!attribute [r] value
-
# @return [Object] the JavaScript value passed to the `throw` statement
-
1
attr_reader :value
-
-
# @!attribute [r] cause
-
# @return [Exception] the underlying error (if any) that triggered this error to be raised
-
1
attr_reader :cause
-
-
# @!attribute [r] javascript_backtrace
-
# @return [V8::StackTrace] the complete JavaScript stack at the point this error was thrown
-
1
attr_reader :javascript_backtrace
-
-
# keep an alias to the StandardError#backtrace method so that we can capture
-
# just ruby backtrace frames
-
1
alias_method :standard_error_backtrace, :backtrace
-
-
1
def initialize(message, value, javascript_backtrace, cause = nil)
-
super(message)
-
@value = value
-
@cause = cause
-
@javascript_backtrace = javascript_backtrace
-
end
-
-
1
def causes
-
[].tap do |causes|
-
current = self
-
until current.nil? do
-
causes.push current
-
current = current.respond_to?(:cause) ? current.cause : nil
-
end
-
end
-
end
-
-
1
def backtrace(*modifiers)
-
return unless super()
-
trace_framework = modifiers.include?(:framework)
-
trace_ruby = modifiers.length == 0 || modifiers.include?(:ruby)
-
trace_javascript = modifiers.length == 0 || modifiers.include?(:javascript)
-
bilingual_backtrace(trace_ruby, trace_javascript).tap do |trace|
-
trace.reject! {|frame| frame =~ %r{(lib/v8/.*\.rb|ext/v8/.*\.cc)}} unless modifiers.include?(:framework)
-
end
-
end
-
-
1
def root_cause
-
causes.last
-
end
-
-
1
def in_javascript?
-
causes.last.is_a? self.class
-
end
-
-
1
def in_ruby?
-
!in_javascript?
-
end
-
-
1
def bilingual_backtrace(trace_ruby = true, trace_javascript = true)
-
backtrace = causes.reduce(:backtrace => [], :ruby => -1, :javascript => -1) { |accumulator, cause|
-
accumulator.tap do
-
if trace_ruby
-
backtrace_selector = cause.respond_to?(:standard_error_backtrace) ? :standard_error_backtrace : :backtrace
-
ruby_frames = cause.send(backtrace_selector)[0..accumulator[:ruby]]
-
accumulator[:backtrace].unshift *ruby_frames
-
accumulator[:ruby] -= ruby_frames.length
-
end
-
if trace_javascript && cause.respond_to?(:javascript_backtrace)
-
javascript_frames = cause.javascript_backtrace.to_a[0..accumulator[:javascript]].map(&:to_s)
-
accumulator[:backtrace].unshift *javascript_frames
-
accumulator[:javascript] -= javascript_frames.length
-
end
-
end
-
}[:backtrace]
-
end
-
-
1
module Try
-
1
def try
-
160
V8::C::TryCatch() do |trycatch|
-
160
result = yield
-
160
if trycatch.HasCaught()
-
raise V8::Error(trycatch)
-
else
-
160
result
-
end
-
end
-
end
-
end
-
-
1
module Protect
-
1
def protect
-
126
yield
-
rescue Exception => e
-
error = V8::C::Exception::Error(e.message)
-
error.SetHiddenValue("rr::Cause", V8::C::External::New(e))
-
V8::C::ThrowException(error)
-
end
-
end
-
-
end
-
-
# Convert the result of a triggered JavaScript try/catch block into
-
# a V8::Error
-
#
-
# This is a bit of a yak-shave because JavaScript let's you throw all
-
# kinds of things. We do our best to make sure that the message property
-
# of the resulting V8::Error is as helpful as possible, and that it
-
# contains as much source location information as we can put onto it.
-
#
-
# For example:
-
#
-
# throw 4
-
# throw 'four'
-
# throw {number: 4}
-
#
-
# are all valid cases, none of which actually reference an exception object
-
# with a stack trace and a message. only with something like:
-
#
-
# throw new Error('fail!')
-
#
-
# do you get the a proper stacktrace and a message property. However a lot of
-
# times JavaScript library authors are lazy and do this:
-
#
-
# throw {message: 'foo', otherMetadata: 'bar'}
-
#
-
# It's common enough so we do the courtesy of having the resulting V8::Error
-
# have as its message in ruby land the 'message' property of the value object
-
#
-
# To further complicate things, SyntaxErrors do not have a JavaScript stack
-
# (even if they occur during js execution). This can make debugging a nightmare
-
# so we copy in the source location of the syntax error into the message of
-
# the resulting V8::Error
-
#
-
# @param [V8::C::TryCatch] native trycatch object that has been triggered
-
# @return [V8::Error] the error generated by this try/catch
-
1
def self.Error(trycatch)
-
exception = trycatch.Exception()
-
-
value = exception.to_ruby
-
cause = nil
-
message = trycatch.Message()
-
javascript_backtrace = V8::StackTrace.new(message.GetStackTrace()) if message
-
-
message = if !exception.kind_of?(V8::C::Value)
-
exception.to_s==""?"Script Timed Out":exception.to_s
-
elsif exception.IsNativeError()
-
if cause = exception.GetHiddenValue("rr::Cause")
-
cause = cause.Value()
-
end
-
if value['constructor'] == V8::Context.current['SyntaxError']
-
info = trycatch.Message()
-
resource_name = info.GetScriptResourceName().to_ruby
-
"#{value['message']} at #{resource_name}:#{info.GetLineNumber()}:#{info.GetStartColumn() + 1}"
-
else
-
exception.Get("message").to_ruby
-
end
-
elsif exception.IsObject()
-
value['message'] || value.to_s
-
else
-
value.to_s
-
end
-
V8::Error.new(message, value, javascript_backtrace, cause)
-
end
-
1
const_set :JSError, Error
-
end
-
1
class V8::Function < V8::Object
-
1
include V8::Error::Try
-
-
1
def initialize(native = nil)
-
41
super do
-
41
native || V8::C::FunctionTemplate::New().GetFunction()
-
end
-
end
-
-
1
def methodcall(this, *args)
-
40
@context.enter do
-
40
this ||= @context.native.Global()
-
200
@context.to_ruby try {native.Call(@context.to_v8(this), args.map {|a| @context.to_v8 a})}
-
end
-
end
-
-
1
def call(*args)
-
40
@context.enter do
-
40
methodcall @context.native.Global(), *args
-
end
-
end
-
-
1
def new(*args)
-
40
@context.enter do
-
80
@context.to_ruby try {native.NewInstance(args.map {|a| @context.to_v8 a})}
-
end
-
end
-
end
-
1
class V8::Object
-
1
include Enumerable
-
1
attr_reader :native
-
1
alias_method :to_v8, :native
-
-
1
def initialize(native = nil)
-
83
@context = V8::Context.current or fail "tried to initialize a #{self.class} without being in an entered V8::Context"
-
83
@native = block_given? ? yield : native || V8::C::Object::New()
-
83
@context.link self, @native
-
end
-
-
1
def [](key)
-
30
@context.enter do
-
30
@context.to_ruby @native.Get(@context.to_v8(key))
-
end
-
end
-
-
1
def []=(key, value)
-
15
@context.enter do
-
15
@native.Set(@context.to_v8(key), @context.to_v8(value))
-
end
-
15
return value
-
end
-
-
1
def keys
-
@context.enter do
-
names = @native.GetPropertyNames()
-
0.upto( names.Length() - 1).to_enum.map {|i| @context.to_ruby names.Get(i)}
-
end
-
end
-
-
1
def values
-
@context.enter do
-
names = @native.GetPropertyNames()
-
0.upto( names.Length() - 1).to_enum.map {|i| @context.to_ruby @native.Get(names.Get(i))}
-
end
-
end
-
-
1
def each
-
@context.enter do
-
names = @native.GetPropertyNames()
-
0.upto(names.Length() - 1) do |i|
-
name = names.Get(i)
-
yield @context.to_ruby(name), @context.to_ruby(@native.Get(name))
-
end
-
end
-
end
-
-
1
def to_s
-
@context.enter do
-
@context.to_ruby @native.ToString()
-
end
-
end
-
-
1
def respond_to?(method)
-
15
super or self[method] != nil
-
end
-
-
1
def method_missing(name, *args, &block)
-
15
if name.to_s =~ /(.*)=$/
-
if args.length > 1
-
self[$1] = args
-
return args
-
else
-
self[$1] = args.first
-
return args
-
end
-
end
-
15
return super(name, *args, &block) unless self.respond_to?(name)
-
15
property = self[name]
-
15
if property.kind_of?(V8::Function)
-
property.methodcall(self, *args)
-
15
elsif args.empty?
-
15
property
-
else
-
raise ArgumentError, "wrong number of arguments (#{args.length} for 0)" unless args.empty?
-
end
-
end
-
end
-
-
1
module V8
-
-
1
class StackTrace
-
1
include Enumerable
-
-
1
def initialize(native)
-
@context = V8::Context.current
-
@native = native
-
end
-
-
1
def length
-
@context.enter do
-
@native ? @native.GetFrameCount() : 0
-
end
-
end
-
-
1
def each
-
return unless @native
-
@context.enter do
-
for i in 0..length - 1
-
yield V8::StackFrame.new(@native.GetFrame(i), @context)
-
end
-
end
-
end
-
-
1
def to_s
-
@native ? map(&:to_s).join("\n") : ""
-
end
-
end
-
-
1
class StackFrame
-
-
1
def initialize(native, context)
-
@context = context
-
@native = native
-
end
-
-
1
def script_name
-
@context.enter do
-
@context.to_ruby(@native.GetScriptName())
-
end
-
end
-
-
1
def function_name
-
@context.enter do
-
@context.to_ruby(@native.GetFunctionName())
-
end
-
end
-
-
1
def line_number
-
@context.enter do
-
@native.GetLineNumber()
-
end
-
end
-
-
1
def column
-
@context.enter do
-
@native.GetColumn()
-
end
-
end
-
-
1
def eval?
-
@context.enter do
-
@native.IsEval()
-
end
-
end
-
-
1
def constructor?
-
@context.enter do
-
@native.IsConstructor()
-
end
-
end
-
-
1
def to_s
-
@context.enter do
-
"at " + if !function_name.empty?
-
"#{function_name} (#{script_name}:#{line_number}:#{column})"
-
else
-
"#{script_name}:#{line_number}:#{column}"
-
end
-
end
-
end
-
end
-
end
-
1
module V8
-
1
VERSION = "0.12.1"
-
end
-
1
module V8
-
1
module Weak
-
# weak refs are broken on MRI 1.9 and merely slow on 1.8
-
# so we mitigate this by using the 'ref' gem. However, this
-
# only mitigates the problem. Under heavy load, you will still
-
# get different or terminated objects being returned. bad stuff.
-
#
-
# If you are having problems with this, an upgrade to 2.0 is *highly*
-
# recommended.
-
#
-
# for other platforms we just use the stdlib 'weakref'
-
# implementation
-
1
if defined?(RUBY_ENGINE) && RUBY_ENGINE == 'ruby' && RUBY_VERSION < '2.0.0'
-
require 'ref'
-
Ref = ::Ref::WeakReference
-
WeakValueMap = ::Ref::WeakValueMap
-
else
-
1
require 'weakref'
-
1
class Ref
-
1
def initialize(object)
-
565
@ref = ::WeakRef.new(object)
-
end
-
1
def object
-
673
@ref.__getobj__
-
rescue ::WeakRef::RefError
-
1
nil
-
end
-
end
-
-
1
class WeakValueMap
-
1
def initialize
-
3
@values = {}
-
end
-
-
1
def [](key)
-
565
if ref = @values[key]
-
307
ref.object
-
end
-
end
-
-
1
def []=(key, value)
-
376
@values[key] = V8::Weak::Ref.new(value)
-
end
-
end
-
end
-
-
1
module Cell
-
1
def weakcell(name, &block)
-
60
unless storage = instance_variable_get("@#{name}")
-
60
storage = instance_variable_set("@#{name}", Storage.new)
-
end
-
60
storage.access(&block)
-
end
-
1
class Storage
-
1
def access(&block)
-
60
if @ref
-
@ref.object || populate(block)
-
else
-
60
populate(block)
-
end
-
end
-
-
1
private
-
-
1
def populate(block)
-
60
occupant = block.call()
-
60
@ref = V8::Weak::Ref.new(occupant)
-
60
return occupant
-
end
-
end
-
end
-
end
-
end
-
1
require 'thread_safe/version'
-
1
require 'thread_safe/synchronized_delegator'
-
-
1
module ThreadSafe
-
1
autoload :Cache, 'thread_safe/cache'
-
1
autoload :Util, 'thread_safe/util'
-
-
# Various classes within allows for +nil+ values to be stored, so a special +NULL+ token is required to indicate the "nil-ness".
-
1
NULL = Object.new
-
-
1
if defined?(JRUBY_VERSION)
-
require 'jruby/synchronized'
-
-
# A thread-safe subclass of Array. This version locks
-
# against the object itself for every method call,
-
# ensuring only one thread can be reading or writing
-
# at a time. This includes iteration methods like
-
# #each.
-
class Array < ::Array
-
include JRuby::Synchronized
-
end
-
-
# A thread-safe subclass of Hash. This version locks
-
# against the object itself for every method call,
-
# ensuring only one thread can be reading or writing
-
# at a time. This includes iteration methods like
-
# #each.
-
class Hash < ::Hash
-
include JRuby::Synchronized
-
end
-
elsif !defined?(RUBY_ENGINE) || RUBY_ENGINE == 'ruby'
-
# Because MRI never runs code in parallel, the existing
-
# non-thread-safe structures should usually work fine.
-
1
Array = ::Array
-
1
Hash = ::Hash
-
elsif defined?(RUBY_ENGINE) && RUBY_ENGINE == 'rbx'
-
require 'monitor'
-
-
class Hash < ::Hash; end
-
class Array < ::Array; end
-
-
[Hash, Array].each do |klass|
-
klass.class_eval do
-
private
-
def _mon_initialize
-
@_monitor = Monitor.new unless @_monitor # avoid double initialisation
-
end
-
-
def self.allocate
-
obj = super
-
obj.send(:_mon_initialize)
-
obj
-
end
-
end
-
-
klass.superclass.instance_methods(false).each do |method|
-
klass.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
-
def #{method}(*args)
-
@_monitor.synchronize { super }
-
end
-
RUBY_EVAL
-
end
-
end
-
end
-
end
-
1
require 'thread'
-
-
1
module ThreadSafe
-
1
autoload :JRubyCacheBackend, 'thread_safe/jruby_cache_backend'
-
1
autoload :MriCacheBackend, 'thread_safe/mri_cache_backend'
-
1
autoload :NonConcurrentCacheBackend, 'thread_safe/non_concurrent_cache_backend'
-
1
autoload :AtomicReferenceCacheBackend, 'thread_safe/atomic_reference_cache_backend'
-
1
autoload :SynchronizedCacheBackend, 'thread_safe/synchronized_cache_backend'
-
-
1
ConcurrentCacheBackend = if defined?(RUBY_ENGINE)
-
1
case RUBY_ENGINE
-
when 'jruby'; JRubyCacheBackend
-
1
when 'ruby'; MriCacheBackend
-
when 'rbx'; AtomicReferenceCacheBackend
-
else
-
warn 'ThreadSafe: unsupported Ruby engine, using a fully synchronized ThreadSafe::Cache implementation' if $VERBOSE
-
SynchronizedCacheBackend
-
end
-
else
-
MriCacheBackend
-
end
-
-
1
class Cache < ConcurrentCacheBackend
-
1
KEY_ERROR = defined?(KeyError) ? KeyError : IndexError # there is no KeyError in 1.8 mode
-
-
1
def initialize(options = nil, &block)
-
96
if options.kind_of?(::Hash)
-
12
validate_options_hash!(options)
-
else
-
84
options = nil
-
end
-
-
96
super(options)
-
96
@default_proc = block
-
end
-
-
1
def [](key)
-
5958
if value = super # non-falsy value is an existing mapping, return it right away
-
5937
value
-
# re-check is done with get_or_default(key, NULL) instead of a simple !key?(key) in order to avoid a race condition, whereby by the time the current thread gets to the key?(key) call
-
# a key => value mapping might have already been created by a different thread (key?(key) would then return true, this elsif branch wouldn't be taken and an incorrent +nil+ value
-
# would be returned)
-
# note: nil == value check is not technically necessary
-
21
elsif @default_proc && nil == value && NULL == (value = get_or_default(key, NULL))
-
8
@default_proc.call(self, key)
-
else
-
13
value
-
end
-
end
-
-
1
alias_method :get, :[]
-
1
alias_method :put, :[]=
-
-
1
def fetch(key, default_value = NULL)
-
1
if NULL != (value = get_or_default(key, NULL))
-
1
value
-
elsif block_given?
-
yield key
-
elsif NULL != default_value
-
default_value
-
else
-
raise_fetch_no_key
-
end
-
end
-
-
1
def fetch_or_store(key, default_value = NULL)
-
fetch(key) do
-
put(key, block_given? ? yield(key) : (NULL == default_value ? raise_fetch_no_key : default_value))
-
end
-
end
-
-
def put_if_absent(key, value)
-
computed = false
-
result = compute_if_absent(key) do
-
computed = true
-
value
-
end
-
computed ? nil : result
-
1
end unless method_defined?(:put_if_absent)
-
-
def value?(value)
-
each_value do |v|
-
return true if value.equal?(v)
-
end
-
false
-
1
end unless method_defined?(:value?)
-
-
def keys
-
arr = []
-
each_pair {|k, v| arr << k}
-
arr
-
1
end unless method_defined?(:keys)
-
-
def values
-
arr = []
-
each_pair {|k, v| arr << v}
-
arr
-
1
end unless method_defined?(:values)
-
-
def each_key
-
each_pair {|k, v| yield k}
-
1
end unless method_defined?(:each_key)
-
-
def each_value
-
each_pair {|k, v| yield v}
-
1
end unless method_defined?(:each_value)
-
-
def key(value)
-
each_pair {|k, v| return k if v == value}
-
nil
-
1
end unless method_defined?(:key)
-
1
alias_method :index, :key if RUBY_VERSION < '1.9'
-
-
def empty?
-
each_pair {|k, v| return false}
-
true
-
1
end unless method_defined?(:empty?)
-
-
def size
-
count = 0
-
each_pair {|k, v| count += 1}
-
count
-
1
end unless method_defined?(:size)
-
-
1
def marshal_dump
-
raise TypeError, "can't dump hash with default proc" if @default_proc
-
h = {}
-
each_pair {|k, v| h[k] = v}
-
h
-
end
-
-
1
def marshal_load(hash)
-
initialize
-
populate_from(hash)
-
end
-
-
1
undef :freeze
-
-
1
private
-
1
def raise_fetch_no_key
-
raise KEY_ERROR, 'key not found'
-
end
-
-
1
def initialize_copy(other)
-
super
-
populate_from(other)
-
end
-
-
1
def populate_from(hash)
-
hash.each_pair {|k, v| self[k] = v}
-
self
-
end
-
-
1
def validate_options_hash!(options)
-
12
if (initial_capacity = options[:initial_capacity]) && (!initial_capacity.kind_of?(Fixnum) || initial_capacity < 0)
-
raise ArgumentError, ":initial_capacity must be a positive Fixnum"
-
end
-
12
if (load_factor = options[:load_factor]) && (!load_factor.kind_of?(Numeric) || load_factor <= 0 || load_factor > 1)
-
raise ArgumentError, ":load_factor must be a number between 0 and 1"
-
end
-
end
-
end
-
end
-
1
module ThreadSafe
-
1
class MriCacheBackend < NonConcurrentCacheBackend
-
# We can get away with a single global write lock (instead of a per-instance one) because of the GVL/green threads.
-
#
-
# The previous implementation used `Thread.critical` on 1.8 MRI to implement the 4 composed atomic operations (`put_if_absent`, `replace_pair`,
-
# `replace_if_exists`, `delete_pair`) this however doesn't work for `compute_if_absent` because on 1.8 the Mutex class is itself implemented
-
# via `Thread.critical` and a call to `Mutex#lock` does not restore the previous `Thread.critical` value (thus any synchronisation clears the
-
# `Thread.critical` flag and we loose control). This poses a problem as the provided block might use synchronisation on its own.
-
#
-
# NOTE: a neat idea of writing a c-ext to manually perform atomic put_if_absent, while relying on Ruby not releasing a GVL while calling
-
# a c-ext will not work because of the potentially Ruby implemented `#hash` and `#eql?` key methods.
-
1
WRITE_LOCK = Mutex.new
-
-
1
def []=(key, value)
-
40
WRITE_LOCK.synchronize { super }
-
end
-
-
1
def compute_if_absent(key)
-
if stored_value = _get(key) # fast non-blocking path for the most likely case
-
stored_value
-
else
-
WRITE_LOCK.synchronize { super }
-
end
-
end
-
-
1
def compute_if_present(key)
-
WRITE_LOCK.synchronize { super }
-
end
-
-
1
def compute(key)
-
WRITE_LOCK.synchronize { super }
-
end
-
-
1
def merge_pair(key, value)
-
WRITE_LOCK.synchronize { super }
-
end
-
-
1
def replace_pair(key, old_value, new_value)
-
WRITE_LOCK.synchronize { super }
-
end
-
-
1
def replace_if_exists(key, new_value)
-
WRITE_LOCK.synchronize { super }
-
end
-
-
1
def get_and_set(key, value)
-
WRITE_LOCK.synchronize { super }
-
end
-
-
1
def delete(key)
-
2
WRITE_LOCK.synchronize { super }
-
end
-
-
1
def delete_pair(key, value)
-
WRITE_LOCK.synchronize { super }
-
end
-
-
1
def clear
-
58
WRITE_LOCK.synchronize { super }
-
end
-
end
-
end
-
1
module ThreadSafe
-
1
class NonConcurrentCacheBackend
-
# WARNING: all public methods of the class must operate on the @backend directly without calling each other. This is important
-
# because of the SynchronizedCacheBackend which uses a non-reentrant mutex for perfomance reasons.
-
1
def initialize(options = nil)
-
96
@backend = {}
-
end
-
-
1
def [](key)
-
5958
@backend[key]
-
end
-
-
1
def []=(key, value)
-
20
@backend[key] = value
-
end
-
-
1
def compute_if_absent(key)
-
if NULL != (stored_value = @backend.fetch(key, NULL))
-
stored_value
-
else
-
@backend[key] = yield
-
end
-
end
-
-
1
def replace_pair(key, old_value, new_value)
-
if pair?(key, old_value)
-
@backend[key] = new_value
-
true
-
else
-
false
-
end
-
end
-
-
1
def replace_if_exists(key, new_value)
-
if NULL != (stored_value = @backend.fetch(key, NULL))
-
@backend[key] = new_value
-
stored_value
-
end
-
end
-
-
1
def compute_if_present(key)
-
if NULL != (stored_value = @backend.fetch(key, NULL))
-
store_computed_value(key, yield(stored_value))
-
end
-
end
-
-
1
def compute(key)
-
store_computed_value(key, yield(@backend[key]))
-
end
-
-
1
def merge_pair(key, value)
-
if NULL == (stored_value = @backend.fetch(key, NULL))
-
@backend[key] = value
-
else
-
store_computed_value(key, yield(stored_value))
-
end
-
end
-
-
1
def get_and_set(key, value)
-
stored_value = @backend[key]
-
@backend[key] = value
-
stored_value
-
end
-
-
1
def key?(key)
-
@backend.key?(key)
-
end
-
-
1
def value?(value)
-
@backend.value?(value)
-
end
-
-
1
def delete(key)
-
1
@backend.delete(key)
-
end
-
-
1
def delete_pair(key, value)
-
if pair?(key, value)
-
@backend.delete(key)
-
true
-
else
-
false
-
end
-
end
-
-
1
def clear
-
29
@backend.clear
-
29
self
-
end
-
-
1
def each_pair
-
dupped_backend.each_pair do |k, v|
-
yield k, v
-
end
-
self
-
end
-
-
1
def size
-
@backend.size
-
end
-
-
1
def get_or_default(key, default_value)
-
9
@backend.fetch(key, default_value)
-
end
-
-
1
alias_method :_get, :[]
-
1
alias_method :_set, :[]=
-
1
private :_get, :_set
-
1
private
-
1
def initialize_copy(other)
-
super
-
@backend = {}
-
self
-
end
-
-
1
def dupped_backend
-
@backend.dup
-
end
-
-
1
def pair?(key, expected_value)
-
NULL != (stored_value = @backend.fetch(key, NULL)) && expected_value.equal?(stored_value)
-
end
-
-
1
def store_computed_value(key, new_value)
-
if new_value.nil?
-
@backend.delete(key)
-
nil
-
else
-
@backend[key] = new_value
-
end
-
end
-
end
-
end
-
1
require 'delegate'
-
1
require 'monitor'
-
-
# This class provides a trivial way to synchronize all calls to a given object
-
# by wrapping it with a `Delegator` that performs `Monitor#enter/exit` calls
-
# around the delegated `#send`. Example:
-
#
-
# array = [] # not thread-safe on many impls
-
# array = SynchronizedDelegator.new([]) # thread-safe
-
#
-
# A simple `Monitor` provides a very coarse-grained way to synchronize a given
-
# object, in that it will cause synchronization for methods that have no
-
# need for it, but this is a trivial way to get thread-safety where none may
-
# exist currently on some implementations.
-
#
-
# This class is currently being considered for inclusion into stdlib, via
-
# https://bugs.ruby-lang.org/issues/8556
-
class SynchronizedDelegator < SimpleDelegator
-
1
def setup
-
@old_abort = Thread.abort_on_exception
-
Thread.abort_on_exception = true
-
end
-
-
1
def teardown
-
Thread.abort_on_exception = @old_abort
-
end
-
-
1
def initialize(obj)
-
__setobj__(obj)
-
@monitor = Monitor.new
-
end
-
-
1
def method_missing(method, *args, &block)
-
monitor = @monitor
-
begin
-
monitor.enter
-
super
-
ensure
-
monitor.exit
-
end
-
end
-
-
# Work-around for 1.8 std-lib not passing block around to delegate.
-
# @private
-
def method_missing(method, *args, &block)
-
monitor = @monitor
-
begin
-
monitor.enter
-
target = self.__getobj__
-
if target.respond_to?(method)
-
target.__send__(method, *args, &block)
-
else
-
super(method, *args, &block)
-
end
-
ensure
-
monitor.exit
-
end
-
1
end if RUBY_VERSION[0, 3] == '1.8'
-
-
1
end unless defined?(SynchronizedDelegator)
-
1
module ThreadSafe
-
1
VERSION = "0.3.4"
-
end
-
-
# NOTE: <= 0.2.0 used Threadsafe::VERSION
-
# @private
-
1
module Threadsafe
-
-
# @private
-
1
def self.const_missing(name)
-
name = name.to_sym
-
if ThreadSafe.const_defined?(name)
-
warn "[DEPRECATION] `Threadsafe::#{name}' is deprecated, use `ThreadSafe::#{name}' instead."
-
ThreadSafe.const_get(name)
-
else
-
warn "[DEPRECATION] the `Threadsafe' module is deprecated, please use `ThreadSafe` instead."
-
super
-
end
-
end
-
-
end
-
1
module Tilt
-
1
VERSION = '1.4.1'
-
-
1
@preferred_mappings = Hash.new
-
32
@template_mappings = Hash.new { |h, k| h[k] = [] }
-
-
# Hash of template path pattern => template implementation class mappings.
-
1
def self.mappings
-
52
@template_mappings
-
end
-
-
1
def self.normalize(ext)
-
52
ext.to_s.downcase.sub(/^\./, '')
-
end
-
-
# Register a template implementation by file extension.
-
1
def self.register(template_class, *extensions)
-
29
if template_class.respond_to?(:to_str)
-
# Support register(ext, template_class) too
-
extensions, template_class = [template_class], extensions[0]
-
end
-
-
29
extensions.each do |ext|
-
52
ext = normalize(ext)
-
52
mappings[ext].unshift(template_class).uniq!
-
end
-
end
-
-
# Makes a template class preferred for the given file extensions. If you
-
# don't provide any extensions, it will be preferred for all its already
-
# registered extensions:
-
#
-
# # Prefer RDiscount for its registered file extensions:
-
# Tilt.prefer(Tilt::RDiscountTemplate)
-
#
-
# # Prefer RDiscount only for the .md extensions:
-
# Tilt.prefer(Tilt::RDiscountTemplate, '.md')
-
1
def self.prefer(template_class, *extensions)
-
if extensions.empty?
-
mappings.each do |ext, klasses|
-
@preferred_mappings[ext] = template_class if klasses.include? template_class
-
end
-
else
-
extensions.each do |ext|
-
ext = normalize(ext)
-
register(template_class, ext)
-
@preferred_mappings[ext] = template_class
-
end
-
end
-
end
-
-
# Returns true when a template exists on an exact match of the provided file extension
-
1
def self.registered?(ext)
-
mappings.key?(ext.downcase) && !mappings[ext.downcase].empty?
-
end
-
-
# Create a new template for the given file using the file's extension
-
# to determine the the template mapping.
-
1
def self.new(file, line=nil, options={}, &block)
-
if template_class = self[file]
-
template_class.new(file, line, options, &block)
-
else
-
fail "No template engine registered for #{File.basename(file)}"
-
end
-
end
-
-
# Lookup a template class for the given filename or file
-
# extension. Return nil when no implementation is found.
-
1
def self.[](file)
-
pattern = file.to_s.downcase
-
until pattern.empty? || registered?(pattern)
-
pattern = File.basename(pattern)
-
pattern.sub!(/^[^.]*\.?/, '')
-
end
-
-
# Try to find a preferred engine.
-
preferred_klass = @preferred_mappings[pattern]
-
return preferred_klass if preferred_klass
-
-
# Fall back to the general list of mappings.
-
klasses = @template_mappings[pattern]
-
-
# Try to find an engine which is already loaded.
-
template = klasses.detect do |klass|
-
if klass.respond_to?(:engine_initialized?)
-
klass.engine_initialized?
-
end
-
end
-
-
return template if template
-
-
# Try each of the classes until one succeeds. If all of them fails,
-
# we'll raise the error of the first class.
-
first_failure = nil
-
-
klasses.each do |klass|
-
begin
-
klass.new { '' }
-
rescue Exception => ex
-
first_failure ||= ex
-
next
-
else
-
return klass
-
end
-
end
-
-
raise first_failure if first_failure
-
end
-
-
# Deprecated module.
-
1
module CompileSite
-
end
-
-
# Extremely simple template cache implementation. Calling applications
-
# create a Tilt::Cache instance and use #fetch with any set of hashable
-
# arguments (such as those to Tilt.new):
-
# cache = Tilt::Cache.new
-
# cache.fetch(path, line, options) { Tilt.new(path, line, options) }
-
#
-
# Subsequent invocations return the already loaded template object.
-
1
class Cache
-
1
def initialize
-
@cache = {}
-
end
-
-
1
def fetch(*key)
-
@cache[key] ||= yield
-
end
-
-
1
def clear
-
@cache = {}
-
end
-
end
-
-
-
# Template Implementations ================================================
-
-
1
require 'tilt/string'
-
1
register StringTemplate, 'str'
-
-
1
require 'tilt/erb'
-
1
register ERBTemplate, 'erb', 'rhtml'
-
1
register ErubisTemplate, 'erb', 'rhtml', 'erubis'
-
-
1
require 'tilt/etanni'
-
1
register EtanniTemplate, 'etn', 'etanni'
-
-
1
require 'tilt/haml'
-
1
register HamlTemplate, 'haml'
-
-
1
require 'tilt/css'
-
1
register SassTemplate, 'sass'
-
1
register ScssTemplate, 'scss'
-
1
register LessTemplate, 'less'
-
-
1
require 'tilt/csv'
-
1
register CSVTemplate, 'rcsv'
-
-
1
require 'tilt/coffee'
-
1
register CoffeeScriptTemplate, 'coffee'
-
-
1
require 'tilt/nokogiri'
-
1
register NokogiriTemplate, 'nokogiri'
-
-
1
require 'tilt/builder'
-
1
register BuilderTemplate, 'builder'
-
-
1
require 'tilt/markaby'
-
1
register MarkabyTemplate, 'mab'
-
-
1
require 'tilt/liquid'
-
1
register LiquidTemplate, 'liquid'
-
-
1
require 'tilt/radius'
-
1
register RadiusTemplate, 'radius'
-
-
1
require 'tilt/markdown'
-
1
register MarukuTemplate, 'markdown', 'mkd', 'md'
-
1
register KramdownTemplate, 'markdown', 'mkd', 'md'
-
1
register BlueClothTemplate, 'markdown', 'mkd', 'md'
-
1
register RDiscountTemplate, 'markdown', 'mkd', 'md'
-
1
register RedcarpetTemplate::Redcarpet1, 'markdown', 'mkd', 'md'
-
1
register RedcarpetTemplate::Redcarpet2, 'markdown', 'mkd', 'md'
-
1
register RedcarpetTemplate, 'markdown', 'mkd', 'md'
-
-
1
require 'tilt/textile'
-
1
register RedClothTemplate, 'textile'
-
-
1
require 'tilt/rdoc'
-
1
register RDocTemplate, 'rdoc'
-
-
1
require 'tilt/wiki'
-
1
register CreoleTemplate, 'wiki', 'creole'
-
1
register WikiClothTemplate, 'wiki', 'mediawiki', 'mw'
-
-
1
require 'tilt/yajl'
-
1
register YajlTemplate, 'yajl'
-
-
1
require 'tilt/asciidoc'
-
1
register AsciidoctorTemplate, 'ad', 'adoc', 'asciidoc'
-
-
1
require 'tilt/plain'
-
1
register PlainTemplate, 'html'
-
end
-
1
require 'tilt/template'
-
-
# AsciiDoc see: http://asciidoc.org/
-
1
module Tilt
-
# Asciidoctor implementation for AsciiDoc see:
-
# http://asciidoctor.github.com/
-
#
-
# Asciidoctor is an open source, pure-Ruby processor for
-
# converting AsciiDoc documents or strings into HTML 5,
-
# DocBook 4.5 and other formats.
-
1
class AsciidoctorTemplate < Template
-
1
self.default_mime_type = 'text/html'
-
-
1
def self.engine_initialized?
-
defined? ::Asciidoctor::Document
-
end
-
-
1
def initialize_engine
-
require_template_library 'asciidoctor'
-
end
-
-
1
def prepare
-
options[:header_footer] = false if options[:header_footer].nil?
-
end
-
-
1
def evaluate(scope, locals, &block)
-
@output ||= Asciidoctor.render(data, options, &block)
-
end
-
-
1
def allows_script?
-
false
-
end
-
end
-
end
-
1
require 'tilt/template'
-
-
1
module Tilt
-
# Builder template implementation. See:
-
# http://builder.rubyforge.org/
-
1
class BuilderTemplate < Template
-
1
self.default_mime_type = 'text/xml'
-
-
1
def self.engine_initialized?
-
defined? ::Builder
-
end
-
-
1
def initialize_engine
-
require_template_library 'builder'
-
end
-
-
1
def prepare; end
-
-
1
def evaluate(scope, locals, &block)
-
return super(scope, locals, &block) if data.respond_to?(:to_str)
-
xml = ::Builder::XmlMarkup.new(:indent => 2)
-
data.call(xml)
-
xml.target!
-
end
-
-
1
def precompiled_preamble(locals)
-
return super if locals.include? :xml
-
"xml = ::Builder::XmlMarkup.new(:indent => 2)\n#{super}"
-
end
-
-
1
def precompiled_postamble(locals)
-
"xml.target!"
-
end
-
-
1
def precompiled_template(locals)
-
data.to_str
-
end
-
end
-
end
-
-
1
require 'tilt/template'
-
-
1
module Tilt
-
# CoffeeScript template implementation. See:
-
# http://coffeescript.org/
-
#
-
# CoffeeScript templates do not support object scopes, locals, or yield.
-
1
class CoffeeScriptTemplate < Template
-
1
self.default_mime_type = 'application/javascript'
-
-
1
@@default_bare = false
-
-
1
def self.default_bare
-
@@default_bare
-
end
-
-
1
def self.default_bare=(value)
-
@@default_bare = value
-
end
-
-
# DEPRECATED
-
1
def self.default_no_wrap
-
@@default_bare
-
end
-
-
# DEPRECATED
-
1
def self.default_no_wrap=(value)
-
@@default_bare = value
-
end
-
-
1
def self.engine_initialized?
-
defined? ::CoffeeScript
-
end
-
-
1
def initialize_engine
-
require_template_library 'coffee_script'
-
end
-
-
1
def prepare
-
if !options.key?(:bare) and !options.key?(:no_wrap)
-
options[:bare] = self.class.default_bare
-
end
-
end
-
-
1
def evaluate(scope, locals, &block)
-
@output ||= CoffeeScript.compile(data, options)
-
end
-
-
1
def allows_script?
-
false
-
end
-
end
-
end
-
-
1
require 'tilt/template'
-
-
1
module Tilt
-
# Sass template implementation. See:
-
# http://haml.hamptoncatlin.com/
-
#
-
# Sass templates do not support object scopes, locals, or yield.
-
1
class SassTemplate < Template
-
1
self.default_mime_type = 'text/css'
-
-
1
def self.engine_initialized?
-
defined? ::Sass::Engine
-
end
-
-
1
def initialize_engine
-
require_template_library 'sass'
-
end
-
-
1
def prepare
-
@engine = ::Sass::Engine.new(data, sass_options)
-
end
-
-
1
def evaluate(scope, locals, &block)
-
@output ||= @engine.render
-
end
-
-
1
def allows_script?
-
false
-
end
-
-
1
private
-
1
def sass_options
-
options.merge(:filename => eval_file, :line => line, :syntax => :sass)
-
end
-
end
-
-
# Sass's new .scss type template implementation.
-
1
class ScssTemplate < SassTemplate
-
1
self.default_mime_type = 'text/css'
-
-
1
private
-
1
def sass_options
-
options.merge(:filename => eval_file, :line => line, :syntax => :scss)
-
end
-
end
-
-
# Lessscss template implementation. See:
-
# http://lesscss.org/
-
#
-
# Less templates do not support object scopes, locals, or yield.
-
1
class LessTemplate < Template
-
1
self.default_mime_type = 'text/css'
-
-
1
def self.engine_initialized?
-
defined? ::Less
-
end
-
-
1
def initialize_engine
-
require_template_library 'less'
-
end
-
-
1
def prepare
-
if ::Less.const_defined? :Engine
-
@engine = ::Less::Engine.new(data)
-
else
-
parser = ::Less::Parser.new(options.merge :filename => eval_file, :line => line)
-
@engine = parser.parse(data)
-
end
-
end
-
-
1
def evaluate(scope, locals, &block)
-
@output ||= @engine.to_css(options)
-
end
-
-
1
def allows_script?
-
false
-
end
-
end
-
end
-
-
1
require 'tilt/template'
-
-
1
module Tilt
-
-
# CSV Template implementation. See:
-
# http://ruby-doc.org/stdlib/libdoc/csv/rdoc/CSV.html
-
#
-
# == Example
-
#
-
# # Example of csv template
-
# tpl = <<-EOS
-
# # header
-
# csv << ['NAME', 'ID']
-
#
-
# # data rows
-
# @people.each do |person|
-
# csv << [person[:name], person[:id]]
-
# end
-
# EOS
-
#
-
# @people = [
-
# {:name => "Joshua Peek", :id => 1},
-
# {:name => "Ryan Tomayko", :id => 2},
-
# {:name => "Simone Carletti", :id => 3}
-
# ]
-
#
-
# template = Tilt::CSVTemplate.new { tpl }
-
# template.render(self)
-
#
-
1
class CSVTemplate < Template
-
1
self.default_mime_type = 'text/csv'
-
-
1
def self.engine_initialized?
-
engine
-
end
-
-
1
def self.engine
-
if RUBY_VERSION >= '1.9.0' && defined? ::CSV
-
::CSV
-
elsif defined? ::FasterCSV
-
::FasterCSV
-
end
-
end
-
-
1
def initialize_engine
-
if RUBY_VERSION >= '1.9.0'
-
require_template_library 'csv'
-
else
-
require_template_library 'fastercsv'
-
end
-
end
-
-
1
def prepare
-
@code =<<-RUBY
-
#{self.class.engine}.generate do |csv|
-
#{data}
-
end
-
RUBY
-
end
-
-
1
def precompiled_template(locals)
-
@code
-
end
-
-
1
def precompiled(locals)
-
source, offset = super
-
[source, offset + 1]
-
end
-
-
end
-
end
-
1
require 'tilt/template'
-
-
1
module Tilt
-
# ERB template implementation. See:
-
# http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/classes/ERB.html
-
1
class ERBTemplate < Template
-
1
@@default_output_variable = '_erbout'
-
-
1
def self.default_output_variable
-
@@default_output_variable
-
end
-
-
1
def self.default_output_variable=(name)
-
@@default_output_variable = name
-
end
-
-
1
def self.engine_initialized?
-
defined? ::ERB
-
end
-
-
1
def initialize_engine
-
require_template_library 'erb'
-
end
-
-
1
def prepare
-
@outvar = options[:outvar] || self.class.default_output_variable
-
options[:trim] = '<>' if !(options[:trim] == false) && (options[:trim].nil? || options[:trim] == true)
-
@engine = ::ERB.new(data, options[:safe], options[:trim], @outvar)
-
end
-
-
1
def precompiled_template(locals)
-
source = @engine.src
-
source
-
end
-
-
1
def precompiled_preamble(locals)
-
<<-RUBY
-
begin
-
__original_outvar = #{@outvar} if defined?(#{@outvar})
-
#{super}
-
RUBY
-
end
-
-
1
def precompiled_postamble(locals)
-
<<-RUBY
-
#{super}
-
ensure
-
#{@outvar} = __original_outvar
-
end
-
RUBY
-
end
-
-
# ERB generates a line to specify the character coding of the generated
-
# source in 1.9. Account for this in the line offset.
-
1
if RUBY_VERSION >= '1.9.0'
-
1
def precompiled(locals)
-
source, offset = super
-
[source, offset + 1]
-
end
-
end
-
end
-
-
# Erubis template implementation. See:
-
# http://www.kuwata-lab.com/erubis/
-
#
-
# ErubisTemplate supports the following additional options, which are not
-
# passed down to the Erubis engine:
-
#
-
# :engine_class allows you to specify a custom engine class to use
-
# instead of the default (which is ::Erubis::Eruby).
-
#
-
# :escape_html when true, ::Erubis::EscapedEruby will be used as
-
# the engine class instead of the default. All content
-
# within <%= %> blocks will be automatically html escaped.
-
1
class ErubisTemplate < ERBTemplate
-
1
def self.engine_initialized?
-
defined? ::Erubis::Eruby
-
end
-
-
1
def initialize_engine
-
require_template_library 'erubis'
-
end
-
-
1
def prepare
-
@outvar = options.delete(:outvar) || self.class.default_output_variable
-
@options.merge!(:preamble => false, :postamble => false, :bufvar => @outvar)
-
engine_class = options.delete(:engine_class)
-
engine_class = ::Erubis::EscapedEruby if options.delete(:escape_html)
-
@engine = (engine_class || ::Erubis::Eruby).new(data, options)
-
end
-
-
1
def precompiled_preamble(locals)
-
[super, "#{@outvar} = _buf = ''"].join("\n")
-
end
-
-
1
def precompiled_postamble(locals)
-
[@outvar, super].join("\n")
-
end
-
-
# Erubis doesn't have ERB's line-off-by-one under 1.9 problem.
-
# Override and adjust back.
-
1
if RUBY_VERSION >= '1.9.0'
-
1
def precompiled(locals)
-
source, offset = super
-
[source, offset - 1]
-
end
-
end
-
end
-
end
-
-
1
require 'tilt/template'
-
-
1
module Tilt
-
1
class EtanniTemplate < Template
-
1
def prepare
-
separator = data.hash.abs
-
chomp = "<<#{separator}.chomp!"
-
start = "\n_out_ << #{chomp}\n"
-
stop = "\n#{separator}\n"
-
replacement = "#{stop}\\1#{start}"
-
-
temp = data.strip
-
temp.gsub!(/<\?r\s+(.*?)\s+\?>/m, replacement)
-
-
@code = "_out_ = [<<#{separator}.chomp!]\n#{temp}#{stop}_out_.join"
-
end
-
-
1
def precompiled_template(locals)
-
@code
-
end
-
-
1
def precompiled(locals)
-
source, offset = super
-
[source, offset + 1]
-
end
-
end
-
end
-
1
require 'tilt/template'
-
-
1
module Tilt
-
# Haml template implementation. See:
-
# http://haml.hamptoncatlin.com/
-
1
class HamlTemplate < Template
-
1
self.default_mime_type = 'text/html'
-
-
1
def self.engine_initialized?
-
defined? ::Haml::Engine
-
end
-
-
1
def initialize_engine
-
require_template_library 'haml'
-
end
-
-
1
def prepare
-
options = @options.merge(:filename => eval_file, :line => line)
-
@engine = ::Haml::Engine.new(data, options)
-
end
-
-
1
def evaluate(scope, locals, &block)
-
if @engine.respond_to?(:precompiled_method_return_value, true)
-
super
-
else
-
@engine.render(scope, locals, &block)
-
end
-
end
-
-
# Precompiled Haml source. Taken from the precompiled_with_ambles
-
# method in Haml::Precompiler:
-
# http://github.com/nex3/haml/blob/master/lib/haml/precompiler.rb#L111-126
-
1
def precompiled_template(locals)
-
@engine.precompiled
-
end
-
-
1
def precompiled_preamble(locals)
-
local_assigns = super
-
@engine.instance_eval do
-
<<-RUBY
-
begin
-
extend Haml::Helpers
-
_hamlout = @haml_buffer = Haml::Buffer.new(@haml_buffer, #{options_for_buffer.inspect})
-
_erbout = _hamlout.buffer
-
__in_erb_template = true
-
_haml_locals = locals
-
#{local_assigns}
-
RUBY
-
end
-
end
-
-
1
def precompiled_postamble(locals)
-
@engine.instance_eval do
-
<<-RUBY
-
#{precompiled_method_return_value}
-
ensure
-
@haml_buffer = @haml_buffer.upper
-
end
-
RUBY
-
end
-
end
-
end
-
end
-
-
1
require 'tilt/template'
-
-
1
module Tilt
-
# Liquid template implementation. See:
-
# http://liquid.rubyforge.org/
-
#
-
# Liquid is designed to be a *safe* template system and threfore
-
# does not provide direct access to execuatable scopes. In order to
-
# support a +scope+, the +scope+ must be able to represent itself
-
# as a hash by responding to #to_h. If the +scope+ does not respond
-
# to #to_h it will be ignored.
-
#
-
# LiquidTemplate does not support yield blocks.
-
#
-
# It's suggested that your program require 'liquid' at load
-
# time when using this template engine.
-
1
class LiquidTemplate < Template
-
1
def self.engine_initialized?
-
defined? ::Liquid::Template
-
end
-
-
1
def initialize_engine
-
require_template_library 'liquid'
-
end
-
-
1
def prepare
-
@engine = ::Liquid::Template.parse(data)
-
end
-
-
1
def evaluate(scope, locals, &block)
-
locals = locals.inject({}){ |h,(k,v)| h[k.to_s] = v ; h }
-
if scope.respond_to?(:to_h)
-
scope = scope.to_h.inject({}){ |h,(k,v)| h[k.to_s] = v ; h }
-
locals = scope.merge(locals)
-
end
-
locals['yield'] = block.nil? ? '' : yield
-
locals['content'] = locals['yield']
-
@engine.render(locals)
-
end
-
-
1
def allows_script?
-
false
-
end
-
end
-
end
-
1
require 'tilt/template'
-
-
1
module Tilt
-
# Markaby
-
# http://github.com/markaby/markaby
-
1
class MarkabyTemplate < Template
-
1
def self.builder_class
-
@builder_class ||= Class.new(Markaby::Builder) do
-
def __capture_markaby_tilt__(&block)
-
__run_markaby_tilt__ do
-
text capture(&block)
-
end
-
end
-
end
-
end
-
-
1
def self.engine_initialized?
-
defined? ::Markaby
-
end
-
-
1
def initialize_engine
-
require_template_library 'markaby'
-
end
-
-
1
def prepare
-
end
-
-
1
def evaluate(scope, locals, &block)
-
builder = self.class.builder_class.new({}, scope)
-
builder.locals = locals
-
-
if data.kind_of? Proc
-
(class << builder; self end).send(:define_method, :__run_markaby_tilt__, &data)
-
else
-
builder.instance_eval <<-CODE, __FILE__, __LINE__
-
def __run_markaby_tilt__
-
#{data}
-
end
-
CODE
-
end
-
-
if block
-
builder.__capture_markaby_tilt__(&block)
-
else
-
builder.__run_markaby_tilt__
-
end
-
-
builder.to_s
-
end
-
end
-
end
-
-
1
require 'tilt/template'
-
-
1
module Tilt
-
# Discount Markdown implementation. See:
-
# http://github.com/rtomayko/rdiscount
-
#
-
# RDiscount is a simple text filter. It does not support +scope+ or
-
# +locals+. The +:smart+ and +:filter_html+ options may be set true
-
# to enable those flags on the underlying RDiscount object.
-
1
class RDiscountTemplate < Template
-
1
self.default_mime_type = 'text/html'
-
-
1
ALIAS = {
-
:escape_html => :filter_html,
-
:smartypants => :smart
-
}
-
-
1
FLAGS = [:smart, :filter_html, :smartypants, :escape_html]
-
-
1
def flags
-
FLAGS.select { |flag| options[flag] }.map { |flag| ALIAS[flag] || flag }
-
end
-
-
1
def self.engine_initialized?
-
defined? ::RDiscount
-
end
-
-
1
def initialize_engine
-
require_template_library 'rdiscount'
-
end
-
-
1
def prepare
-
@engine = RDiscount.new(data, *flags)
-
@output = nil
-
end
-
-
1
def evaluate(scope, locals, &block)
-
@output ||= @engine.to_html
-
end
-
-
1
def allows_script?
-
false
-
end
-
end
-
-
# Upskirt Markdown implementation. See:
-
# https://github.com/tanoku/redcarpet
-
#
-
# Supports both Redcarpet 1.x and 2.x
-
1
class RedcarpetTemplate < Template
-
1
def self.engine_initialized?
-
defined? ::Redcarpet
-
end
-
-
1
def initialize_engine
-
require_template_library 'redcarpet'
-
end
-
-
1
def prepare
-
klass = [Redcarpet2, Redcarpet1].detect { |e| e.engine_initialized? }
-
@engine = klass.new(file, line, options) { data }
-
end
-
-
1
def evaluate(scope, locals, &block)
-
@engine.evaluate(scope, locals, &block)
-
end
-
-
1
def allows_script?
-
false
-
end
-
-
# Compatibility mode for Redcarpet 1.x
-
1
class Redcarpet1 < RDiscountTemplate
-
1
self.default_mime_type = 'text/html'
-
-
1
def self.engine_initialized?
-
defined? ::RedcarpetCompat
-
end
-
-
1
def prepare
-
@engine = RedcarpetCompat.new(data, *flags)
-
@output = nil
-
end
-
end
-
-
# Future proof mode for Redcarpet 2.x (not yet released)
-
1
class Redcarpet2 < Template
-
1
self.default_mime_type = 'text/html'
-
-
1
def self.engine_initialized?
-
defined? ::Redcarpet::Render and defined? ::Redcarpet::Markdown
-
end
-
-
1
def generate_renderer
-
renderer = options.delete(:renderer) || ::Redcarpet::Render::HTML
-
return renderer unless options.delete(:smartypants)
-
return renderer if renderer.is_a?(Class) && renderer <= ::Redcarpet::Render::SmartyPants
-
-
if renderer == ::Redcarpet::Render::XHTML
-
::Redcarpet::Render::SmartyHTML.new(:xhtml => true)
-
elsif renderer == ::Redcarpet::Render::HTML
-
::Redcarpet::Render::SmartyHTML
-
elsif renderer.is_a? Class
-
Class.new(renderer) { include ::Redcarpet::Render::SmartyPants }
-
else
-
renderer.extend ::Redcarpet::Render::SmartyPants
-
end
-
end
-
-
1
def prepare
-
# try to support the same aliases
-
RDiscountTemplate::ALIAS.each do |opt, aka|
-
next if options.key? opt or not options.key? aka
-
options[opt] = options.delete(aka)
-
end
-
-
# only raise an exception if someone is trying to enable :escape_html
-
options.delete(:escape_html) unless options[:escape_html]
-
-
@engine = ::Redcarpet::Markdown.new(generate_renderer, options)
-
@output = nil
-
end
-
-
1
def evaluate(scope, locals, &block)
-
@output ||= @engine.render(data)
-
end
-
-
1
def allows_script?
-
false
-
end
-
end
-
end
-
-
# BlueCloth Markdown implementation. See:
-
# http://deveiate.org/projects/BlueCloth/
-
1
class BlueClothTemplate < Template
-
1
self.default_mime_type = 'text/html'
-
-
1
def self.engine_initialized?
-
defined? ::BlueCloth
-
end
-
-
1
def initialize_engine
-
require_template_library 'bluecloth'
-
end
-
-
1
def prepare
-
@engine = BlueCloth.new(data, options)
-
@output = nil
-
end
-
-
1
def evaluate(scope, locals, &block)
-
@output ||= @engine.to_html
-
end
-
-
1
def allows_script?
-
false
-
end
-
end
-
-
# Maruku markdown implementation. See:
-
# http://maruku.rubyforge.org/
-
1
class MarukuTemplate < Template
-
1
def self.engine_initialized?
-
defined? ::Maruku
-
end
-
-
1
def initialize_engine
-
require_template_library 'maruku'
-
end
-
-
1
def prepare
-
@engine = Maruku.new(data, options)
-
@output = nil
-
end
-
-
1
def evaluate(scope, locals, &block)
-
@output ||= @engine.to_html
-
end
-
-
1
def allows_script?
-
false
-
end
-
end
-
-
# Kramdown Markdown implementation. See:
-
# http://kramdown.rubyforge.org/
-
1
class KramdownTemplate < Template
-
1
DUMB_QUOTES = [39, 39, 34, 34]
-
-
1
def self.engine_initialized?
-
defined? ::Kramdown
-
end
-
-
1
def initialize_engine
-
require_template_library 'kramdown'
-
end
-
-
1
def prepare
-
options[:smart_quotes] = DUMB_QUOTES unless options[:smartypants]
-
@engine = Kramdown::Document.new(data, options)
-
@output = nil
-
end
-
-
1
def evaluate(scope, locals, &block)
-
@output ||= @engine.to_html
-
end
-
-
1
def allows_script?
-
false
-
end
-
end
-
end
-
-
1
require 'tilt/template'
-
-
1
module Tilt
-
# Nokogiri template implementation. See:
-
# http://nokogiri.org/
-
1
class NokogiriTemplate < Template
-
1
DOCUMENT_HEADER = /^<\?xml version=\"1\.0\"\?>\n?/
-
1
self.default_mime_type = 'text/xml'
-
-
1
def self.engine_initialized?
-
defined? ::Nokogiri
-
end
-
-
1
def initialize_engine
-
require_template_library 'nokogiri'
-
end
-
-
1
def prepare; end
-
-
1
def evaluate(scope, locals)
-
if data.respond_to?(:to_str)
-
wrapper = proc { yield.sub(DOCUMENT_HEADER, "") } if block_given?
-
super(scope, locals, &wrapper)
-
else
-
::Nokogiri::XML::Builder.new.tap(&data).to_xml
-
end
-
end
-
-
1
def precompiled_preamble(locals)
-
return super if locals.include? :xml
-
"xml = ::Nokogiri::XML::Builder.new { |xml| }\n#{super}"
-
end
-
-
1
def precompiled_postamble(locals)
-
"xml.to_xml"
-
end
-
-
1
def precompiled_template(locals)
-
data.to_str
-
end
-
end
-
end
-
-
1
require 'tilt/template'
-
-
-
1
module Tilt
-
# Raw text (no template functionality).
-
1
class PlainTemplate < Template
-
1
self.default_mime_type = 'text/html'
-
-
1
def self.engine_initialized?
-
true
-
end
-
-
1
def prepare
-
end
-
-
1
def evaluate(scope, locals, &block)
-
@output ||= data
-
end
-
end
-
end
-
1
require 'tilt/template'
-
-
1
module Tilt
-
# Radius Template
-
# http://github.com/jlong/radius/
-
1
class RadiusTemplate < Template
-
1
def self.engine_initialized?
-
defined? ::Radius
-
end
-
-
1
def self.context_class
-
@context_class ||= Class.new(Radius::Context) do
-
attr_accessor :tilt_scope
-
-
def tag_missing(name, attributes)
-
tilt_scope.__send__(name)
-
end
-
-
def dup
-
i = super
-
i.tilt_scope = tilt_scope
-
i
-
end
-
end
-
end
-
-
1
def initialize_engine
-
require_template_library 'radius'
-
end
-
-
1
def prepare
-
end
-
-
1
def evaluate(scope, locals, &block)
-
context = self.class.context_class.new
-
context.tilt_scope = scope
-
context.define_tag("yield") do
-
block.call
-
end
-
locals.each do |tag, value|
-
context.define_tag(tag) do
-
value
-
end
-
end
-
-
options = {:tag_prefix => 'r'}.merge(@options)
-
parser = Radius::Parser.new(context, options)
-
parser.parse(data)
-
end
-
-
1
def allows_script?
-
false
-
end
-
end
-
end
-
1
require 'tilt/template'
-
-
1
module Tilt
-
# RDoc template. See:
-
# http://rdoc.rubyforge.org/
-
#
-
# It's suggested that your program `require 'rdoc/markup'` and
-
# `require 'rdoc/markup/to_html'` at load time when using this template
-
# engine in a threaded environment.
-
1
class RDocTemplate < Template
-
1
self.default_mime_type = 'text/html'
-
-
1
def self.engine_initialized?
-
defined? ::RDoc::Markup::ToHtml
-
end
-
-
1
def initialize_engine
-
require_template_library 'rdoc'
-
require_template_library 'rdoc/markup'
-
require_template_library 'rdoc/markup/to_html'
-
end
-
-
1
def markup
-
begin
-
# RDoc 4.0
-
require 'rdoc/options'
-
RDoc::Markup::ToHtml.new(RDoc::Options.new, nil)
-
rescue ArgumentError
-
# RDoc < 4.0
-
RDoc::Markup::ToHtml.new
-
end
-
end
-
-
1
def prepare
-
@engine = markup.convert(data)
-
@output = nil
-
end
-
-
1
def evaluate(scope, locals, &block)
-
@output ||= @engine.to_s
-
end
-
-
1
def allows_script?
-
false
-
end
-
end
-
end
-
1
require 'tilt/template'
-
-
1
module Tilt
-
# The template source is evaluated as a Ruby string. The #{} interpolation
-
# syntax can be used to generated dynamic output.
-
1
class StringTemplate < Template
-
1
def prepare
-
hash = "TILT#{data.hash.abs}"
-
@code = "<<#{hash}.chomp\n#{data}\n#{hash}"
-
end
-
-
1
def precompiled_template(locals)
-
@code
-
end
-
-
1
def precompiled(locals)
-
source, offset = super
-
[source, offset + 1]
-
end
-
end
-
end
-
1
module Tilt
-
1
TOPOBJECT = Object.superclass || Object
-
-
# Base class for template implementations. Subclasses must implement
-
# the #prepare method and one of the #evaluate or #precompiled_template
-
# methods.
-
1
class Template
-
# Template source; loaded from a file or given directly.
-
1
attr_reader :data
-
-
# The name of the file where the template data was loaded from.
-
1
attr_reader :file
-
-
# The line number in #file where template data was loaded from.
-
1
attr_reader :line
-
-
# A Hash of template engine specific options. This is passed directly
-
# to the underlying engine and is not used by the generic template
-
# interface.
-
1
attr_reader :options
-
-
# Used to determine if this class's initialize_engine method has
-
# been called yet.
-
1
@engine_initialized = false
-
1
class << self
-
1
attr_accessor :engine_initialized
-
1
alias engine_initialized? engine_initialized
-
-
1
attr_accessor :default_mime_type
-
end
-
-
# Create a new template with the file, line, and options specified. By
-
# default, template data is read from the file. When a block is given,
-
# it should read template data and return as a String. When file is nil,
-
# a block is required.
-
#
-
# All arguments are optional.
-
1
def initialize(file=nil, line=1, options={}, &block)
-
@file, @line, @options = nil, 1, {}
-
-
[options, line, file].compact.each do |arg|
-
case
-
when arg.respond_to?(:to_str) ; @file = arg.to_str
-
when arg.respond_to?(:to_int) ; @line = arg.to_int
-
when arg.respond_to?(:to_hash) ; @options = arg.to_hash.dup
-
when arg.respond_to?(:path) ; @file = arg.path
-
else raise TypeError
-
end
-
end
-
-
raise ArgumentError, "file or block required" if (@file || block).nil?
-
-
# call the initialize_engine method if this is the very first time
-
# an instance of this class has been created.
-
if !self.class.engine_initialized?
-
initialize_engine
-
self.class.engine_initialized = true
-
end
-
-
# used to hold compiled template methods
-
@compiled_method = {}
-
-
# used on 1.9 to set the encoding if it is not set elsewhere (like a magic comment)
-
# currently only used if template compiles to ruby
-
@default_encoding = @options.delete :default_encoding
-
-
# load template data and prepare (uses binread to avoid encoding issues)
-
@reader = block || lambda { |t| read_template_file }
-
@data = @reader.call(self)
-
-
if @data.respond_to?(:force_encoding)
-
@data.force_encoding(default_encoding) if default_encoding
-
-
if !@data.valid_encoding?
-
raise Encoding::InvalidByteSequenceError, "#{eval_file} is not valid #{@data.encoding}"
-
end
-
end
-
-
prepare
-
end
-
-
# The encoding of the source data. Defaults to the
-
# default_encoding-option if present. You may override this method
-
# in your template class if you have a better hint of the data's
-
# encoding.
-
1
def default_encoding
-
@default_encoding
-
end
-
-
1
def read_template_file
-
data = File.open(file, 'rb') { |io| io.read }
-
if data.respond_to?(:force_encoding)
-
# Set it to the default external (without verifying)
-
data.force_encoding(Encoding.default_external) if Encoding.default_external
-
end
-
data
-
end
-
-
# Render the template in the given scope with the locals specified. If a
-
# block is given, it is typically available within the template via
-
# +yield+.
-
1
def render(scope=Object.new, locals={}, &block)
-
evaluate scope, locals || {}, &block
-
end
-
-
# The basename of the template file.
-
1
def basename(suffix='')
-
File.basename(file, suffix) if file
-
end
-
-
# The template file's basename with all extensions chomped off.
-
1
def name
-
basename.split('.', 2).first if basename
-
end
-
-
# The filename used in backtraces to describe the template.
-
1
def eval_file
-
file || '(__TEMPLATE__)'
-
end
-
-
# Whether or not this template engine allows executing Ruby script
-
# within the template. If this is false, +scope+ and +locals+ will
-
# generally not be used, nor will the provided block be avaiable
-
# via +yield+.
-
# This should be overridden by template subclasses.
-
1
def allows_script?
-
true
-
end
-
-
1
protected
-
# Called once and only once for each template subclass the first time
-
# the template class is initialized. This should be used to require the
-
# underlying template library and perform any initial setup.
-
1
def initialize_engine
-
end
-
-
# Like Kernel#require but issues a warning urging a manual require when
-
# running under a threaded environment.
-
1
def require_template_library(name)
-
if Thread.list.size > 1
-
warn "WARN: tilt autoloading '#{name}' in a non thread-safe way; " +
-
"explicit require '#{name}' suggested."
-
end
-
require name
-
end
-
-
# Do whatever preparation is necessary to setup the underlying template
-
# engine. Called immediately after template data is loaded. Instance
-
# variables set in this method are available when #evaluate is called.
-
#
-
# Subclasses must provide an implementation of this method.
-
1
def prepare
-
if respond_to?(:compile!)
-
# backward compat with tilt < 0.6; just in case
-
warn 'Tilt::Template#compile! is deprecated; implement #prepare instead.'
-
compile!
-
else
-
raise NotImplementedError
-
end
-
end
-
-
# Execute the compiled template and return the result string. Template
-
# evaluation is guaranteed to be performed in the scope object with the
-
# locals specified and with support for yielding to the block.
-
#
-
# This method is only used by source generating templates. Subclasses that
-
# override render() may not support all features.
-
1
def evaluate(scope, locals, &block)
-
method = compiled_method(locals.keys)
-
method.bind(scope).call(locals, &block)
-
end
-
-
# Generates all template source by combining the preamble, template, and
-
# postamble and returns a two-tuple of the form: [source, offset], where
-
# source is the string containing (Ruby) source code for the template and
-
# offset is the integer line offset where line reporting should begin.
-
#
-
# Template subclasses may override this method when they need complete
-
# control over source generation or want to adjust the default line
-
# offset. In most cases, overriding the #precompiled_template method is
-
# easier and more appropriate.
-
1
def precompiled(locals)
-
preamble = precompiled_preamble(locals)
-
template = precompiled_template(locals)
-
postamble = precompiled_postamble(locals)
-
source = ''
-
-
# Ensure that our generated source code has the same encoding as the
-
# the source code generated by the template engine.
-
if source.respond_to?(:force_encoding)
-
template_encoding = extract_encoding(template)
-
-
source.force_encoding(template_encoding)
-
template.force_encoding(template_encoding)
-
end
-
-
# https://github.com/rtomayko/tilt/issues/193
-
warn "precompiled_preamble should return String (not Array)" if preamble.is_a?(Array)
-
warn "precompiled_postamble should return String (not Array)" if postamble.is_a?(Array)
-
source << [preamble, template, postamble].join("\n")
-
-
[source, preamble.count("\n")+1]
-
end
-
-
# A string containing the (Ruby) source code for the template. The
-
# default Template#evaluate implementation requires either this
-
# method or the #precompiled method be overridden. When defined,
-
# the base Template guarantees correct file/line handling, locals
-
# support, custom scopes, proper encoding, and support for template
-
# compilation.
-
1
def precompiled_template(locals)
-
raise NotImplementedError
-
end
-
-
# Generates preamble code for initializing template state, and performing
-
# locals assignment. The default implementation performs locals
-
# assignment only. Lines included in the preamble are subtracted from the
-
# source line offset, so adding code to the preamble does not effect line
-
# reporting in Kernel::caller and backtraces.
-
1
def precompiled_preamble(locals)
-
locals.map do |k,v|
-
if k.to_s =~ /\A[a-z_][a-zA-Z_0-9]*\z/
-
"#{k} = locals[#{k.inspect}]"
-
else
-
raise "invalid locals key: #{k.inspect} (keys must be variable names)"
-
end
-
end.join("\n")
-
end
-
-
# Generates postamble code for the precompiled template source. The
-
# string returned from this method is appended to the precompiled
-
# template source.
-
1
def precompiled_postamble(locals)
-
''
-
end
-
-
# The compiled method for the locals keys provided.
-
1
def compiled_method(locals_keys)
-
@compiled_method[locals_keys] ||=
-
compile_template_method(locals_keys)
-
end
-
-
1
private
-
1
def compile_template_method(locals)
-
source, offset = precompiled(locals)
-
method_name = "__tilt_#{Thread.current.object_id.abs}"
-
method_source = ""
-
-
if method_source.respond_to?(:force_encoding)
-
method_source.force_encoding(source.encoding)
-
end
-
-
method_source << <<-RUBY
-
TOPOBJECT.class_eval do
-
def #{method_name}(locals)
-
Thread.current[:tilt_vars] = [self, locals]
-
class << self
-
this, locals = Thread.current[:tilt_vars]
-
this.instance_eval do
-
RUBY
-
offset += method_source.count("\n")
-
method_source << source
-
method_source << "\nend;end;end;end"
-
Object.class_eval method_source, eval_file, line - offset
-
unbind_compiled_method(method_name)
-
end
-
-
1
def unbind_compiled_method(method_name)
-
method = TOPOBJECT.instance_method(method_name)
-
TOPOBJECT.class_eval { remove_method(method_name) }
-
method
-
end
-
-
1
def extract_encoding(script)
-
extract_magic_comment(script) || script.encoding
-
end
-
-
1
def extract_magic_comment(script)
-
binary script do
-
script[/\A[ \t]*\#.*coding\s*[=:]\s*([[:alnum:]\-_]+).*$/n, 1]
-
end
-
end
-
-
1
def binary(string)
-
original_encoding = string.encoding
-
string.force_encoding(Encoding::BINARY)
-
yield
-
ensure
-
string.force_encoding(original_encoding)
-
end
-
end
-
end
-
1
require 'tilt/template'
-
-
1
module Tilt
-
# RedCloth implementation. See:
-
# http://redcloth.org/
-
1
class RedClothTemplate < Template
-
1
def self.engine_initialized?
-
defined? ::RedCloth
-
end
-
-
1
def initialize_engine
-
require_template_library 'redcloth'
-
end
-
-
1
def prepare
-
@engine = RedCloth.new(data)
-
options.each {|k, v| @engine.send("#{k}=", v) if @engine.respond_to? "#{k}="}
-
@output = nil
-
end
-
-
1
def evaluate(scope, locals, &block)
-
@output ||= @engine.to_html
-
end
-
-
1
def allows_script?
-
false
-
end
-
end
-
end
-
-
1
require 'tilt/template'
-
-
1
module Tilt
-
# Creole implementation. See:
-
# http://www.wikicreole.org/
-
1
class CreoleTemplate < Template
-
1
def self.engine_initialized?
-
defined? ::Creole
-
end
-
-
1
def initialize_engine
-
require_template_library 'creole'
-
end
-
-
1
def prepare
-
opts = {}
-
[:allowed_schemes, :extensions, :no_escape].each do |k|
-
opts[k] = options[k] if options[k]
-
end
-
@engine = Creole::Parser.new(data, opts)
-
@output = nil
-
end
-
-
1
def evaluate(scope, locals, &block)
-
@output ||= @engine.to_html
-
end
-
-
1
def allows_script?
-
false
-
end
-
end
-
-
# WikiCloth implementation. See:
-
# http://redcloth.org/
-
1
class WikiClothTemplate < Template
-
1
def self.engine_initialized?
-
defined? ::WikiCloth::Parser
-
end
-
-
1
def initialize_engine
-
require_template_library 'wikicloth'
-
end
-
-
1
def prepare
-
@parser = options.delete(:parser) || WikiCloth::Parser
-
@engine = @parser.new options.merge(:data => data)
-
@output = nil
-
end
-
-
1
def evaluate(scope, locals, &block)
-
@output ||= @engine.to_html
-
end
-
-
1
def allows_script?
-
false
-
end
-
end
-
end
-
1
require 'tilt/template'
-
-
1
module Tilt
-
-
# Yajl Template implementation
-
#
-
# Yajl is a fast JSON parsing and encoding library for Ruby
-
# See https://github.com/brianmario/yajl-ruby
-
#
-
# The template source is evaluated as a Ruby string,
-
# and the result is converted #to_json.
-
#
-
# == Example
-
#
-
# # This is a template example.
-
# # The template can contain any Ruby statement.
-
# tpl <<-EOS
-
# @counter = 0
-
#
-
# # The json variable represents the buffer
-
# # and holds the data to be serialized into json.
-
# # It defaults to an empty hash, but you can override it at any time.
-
# json = {
-
# :"user#{@counter += 1}" => { :name => "Joshua Peek", :id => @counter },
-
# :"user#{@counter += 1}" => { :name => "Ryan Tomayko", :id => @counter },
-
# :"user#{@counter += 1}" => { :name => "Simone Carletti", :id => @counter },
-
# }
-
#
-
# # Since the json variable is a Hash,
-
# # you can use conditional statements or any other Ruby statement
-
# # to populate it.
-
# json[:"user#{@counter += 1}"] = { :name => "Unknown" } if 1 == 2
-
#
-
# # The last line doesn't affect the returned value.
-
# nil
-
# EOS
-
#
-
# template = Tilt::YajlTemplate.new { tpl }
-
# template.render(self)
-
#
-
1
class YajlTemplate < Template
-
-
1
self.default_mime_type = 'application/json'
-
-
1
def self.engine_initialized?
-
defined? ::Yajl
-
end
-
-
1
def initialize_engine
-
require_template_library 'yajl'
-
end
-
-
1
def prepare
-
end
-
-
1
def evaluate(scope, locals, &block)
-
decorate super(scope, locals, &block)
-
end
-
-
1
def precompiled_preamble(locals)
-
return super if locals.include? :json
-
"json = {}\n#{super}"
-
end
-
-
1
def precompiled_postamble(locals)
-
"Yajl::Encoder.new.encode(json)"
-
end
-
-
1
def precompiled_template(locals)
-
data.to_str
-
end
-
-
-
# Decorates the +json+ input according to given +options+.
-
#
-
# json - The json String to decorate.
-
# options - The option Hash to customize the behavior.
-
#
-
# Returns the decorated String.
-
1
def decorate(json)
-
callback, variable = options[:callback], options[:variable]
-
if callback && variable
-
"var #{variable} = #{json}; #{callback}(#{variable});"
-
elsif variable
-
"var #{variable} = #{json};"
-
elsif callback
-
"#{callback}(#{json});"
-
else
-
json
-
end
-
end
-
end
-
-
end
-
1
require 'treetop/ruby_extensions/string'
-
1
class String
-
1
def column_of(index)
-
return 1 if index == 0
-
newline_index = rindex("\n", index - 1)
-
if newline_index
-
index - newline_index
-
else
-
index + 1
-
end
-
end
-
-
1
def line_of(index)
-
self[0...index].count("\n") + 1
-
end
-
-
1
unless method_defined?(:blank?)
-
def blank?
-
self == ""
-
end
-
end
-
-
# The following methods are lifted from Facets 2.0.2
-
1
def tabto(n)
-
if self =~ /^( *)\S/
-
# Inlined due to collision with ActiveSupport 4.0: indent(n - $1.length)
-
m = n - $1.length
-
if m >= 0
-
gsub(/^/, ' ' * m)
-
else
-
gsub(/^ {0,#{-m}}/, "")
-
end
-
else
-
self
-
end
-
end
-
-
1
def treetop_camelize
-
to_s.gsub(/\/(.?)/){ "::" + $1.upcase }.gsub(/(^|_)(.)/){ $2.upcase }
-
end
-
end
-
1
require 'treetop/ruby_extensions'
-
-
1
require 'treetop/runtime/compiled_parser'
-
1
require 'treetop/runtime/syntax_node'
-
1
require 'treetop/runtime/terminal_parse_failure'
-
1
require 'treetop/runtime/interval_skip_list'
-
1
module Treetop
-
1
module Runtime
-
1
class CompiledParser
-
1
include Treetop::Runtime
-
-
1
attr_reader :input, :index, :max_terminal_failure_index
-
1
attr_writer :root
-
1
attr_accessor :consume_all_input
-
1
alias :consume_all_input? :consume_all_input
-
-
1
def initialize
-
self.consume_all_input = true
-
end
-
-
1
def parse(input, options = {})
-
prepare_to_parse(input)
-
@index = options[:index] if options[:index]
-
result = send("_nt_#{options[:root] || root}")
-
should_consume_all = options.include?(:consume_all_input) ? options[:consume_all_input] : consume_all_input?
-
return nil if (should_consume_all && index != input.size)
-
return SyntaxNode.new(input, index...(index + 1)) if result == true
-
return result
-
end
-
-
1
def failure_index
-
max_terminal_failure_index
-
end
-
-
1
def failure_line
-
@terminal_failures && input.line_of(failure_index)
-
end
-
-
1
def failure_column
-
@terminal_failures && input.column_of(failure_index)
-
end
-
-
1
def failure_reason
-
return nil unless (tf = terminal_failures) && tf.size > 0
-
"Expected " +
-
(tf.size == 1 ?
-
tf[0].expected_string :
-
"one of #{tf.map{|f| f.expected_string}.uniq*', '}"
-
) +
-
" at line #{failure_line}, column #{failure_column} (byte #{failure_index+1})" +
-
" after #{input[index...failure_index]}"
-
end
-
-
1
def terminal_failures
-
if @terminal_failures.empty? || @terminal_failures[0].is_a?(TerminalParseFailure)
-
@terminal_failures
-
else
-
@terminal_failures.map! {|tf_ary| TerminalParseFailure.new(*tf_ary) }
-
end
-
end
-
-
-
1
protected
-
-
1
attr_reader :node_cache, :input_length
-
1
attr_writer :index
-
-
1
def prepare_to_parse(input)
-
@input = input
-
@input_length = input.length
-
reset_index
-
@node_cache = Hash.new {|hash, key| hash[key] = Hash.new}
-
@regexps = {}
-
@terminal_failures = []
-
@max_terminal_failure_index = 0
-
end
-
-
1
def reset_index
-
@index = 0
-
end
-
-
1
def parse_anything(node_class = SyntaxNode, inline_module = nil)
-
if index < input.length
-
result = instantiate_node(node_class,input, index...(index + 1))
-
result.extend(inline_module) if inline_module
-
@index += 1
-
result
-
else
-
terminal_parse_failure("any character")
-
end
-
end
-
-
1
def instantiate_node(node_type,*args)
-
if node_type.respond_to? :new
-
node_type.new(*args)
-
else
-
SyntaxNode.new(*args).extend(node_type)
-
end
-
end
-
-
1
def has_terminal?(terminal, regex, index)
-
if regex
-
rx = @regexps[terminal] ||= Regexp.new(terminal)
-
input.index(rx, index) == index
-
else
-
input[index, terminal.size] == terminal
-
end
-
end
-
-
1
def terminal_parse_failure(expected_string)
-
return nil if index < max_terminal_failure_index
-
if index > max_terminal_failure_index
-
@max_terminal_failure_index = index
-
@terminal_failures = []
-
end
-
@terminal_failures << [index, expected_string]
-
return nil
-
end
-
end
-
end
-
end
-
1
require 'treetop/runtime/interval_skip_list/interval_skip_list'
-
1
require 'treetop/runtime/interval_skip_list/head_node'
-
1
require 'treetop/runtime/interval_skip_list/node'
-
1
class IntervalSkipList
-
1
class HeadNode
-
1
attr_reader :height, :forward, :forward_markers
-
-
1
def initialize(height)
-
@height = height
-
@forward = Array.new(height, nil)
-
@forward_markers = Array.new(height) {|i| []}
-
end
-
-
1
def top_level
-
height - 1
-
end
-
end
-
end
-
1
class IntervalSkipList
-
1
attr_reader :probability
-
-
1
def initialize
-
@head = HeadNode.new(max_height)
-
@ranges = {}
-
@probability = 0.5
-
end
-
-
1
def max_height
-
3
-
end
-
-
1
def empty?
-
head.forward[0].nil?
-
end
-
-
1
def expire(range, length_change)
-
expired_markers, first_node_after_range = overlapping(range)
-
expired_markers.each { |marker| delete(marker) }
-
first_node_after_range.propagate_length_change(length_change)
-
end
-
-
1
def overlapping(range)
-
markers, first_node = containing_with_node(range.first)
-
-
cur_node = first_node
-
begin
-
markers.concat(cur_node.forward_markers.flatten)
-
cur_node = cur_node.forward[0]
-
end while cur_node.key < range.last
-
-
return markers.uniq, cur_node
-
end
-
-
1
def containing(n)
-
containing_with_node(n).first
-
end
-
-
1
def insert(range, marker)
-
ranges[marker] = range
-
first_node = insert_node(range.first)
-
first_node.endpoint_of.push(marker)
-
last_node = insert_node(range.last)
-
last_node.endpoint_of.push(marker)
-
-
cur_node = first_node
-
cur_level = first_node.top_level
-
while next_node_at_level_inside_range?(cur_node, cur_level, range)
-
while can_ascend_from?(cur_node, cur_level) && next_node_at_level_inside_range?(cur_node, cur_level + 1, range)
-
cur_level += 1
-
end
-
cur_node = mark_forward_path_at_level(cur_node, cur_level, marker)
-
end
-
-
while node_inside_range?(cur_node, range)
-
while can_descend_from?(cur_level) && next_node_at_level_outside_range?(cur_node, cur_level, range)
-
cur_level -= 1
-
end
-
cur_node = mark_forward_path_at_level(cur_node, cur_level, marker)
-
end
-
end
-
-
1
def delete(marker)
-
range = ranges[marker]
-
path_to_first_node = make_path
-
first_node = find(range.first, path_to_first_node)
-
-
cur_node = first_node
-
cur_level = first_node.top_level
-
while next_node_at_level_inside_range?(cur_node, cur_level, range)
-
while can_ascend_from?(cur_node, cur_level) && next_node_at_level_inside_range?(cur_node, cur_level + 1, range)
-
cur_level += 1
-
end
-
cur_node = unmark_forward_path_at_level(cur_node, cur_level, marker)
-
end
-
-
while node_inside_range?(cur_node, range)
-
while can_descend_from?(cur_level) && next_node_at_level_outside_range?(cur_node, cur_level, range)
-
cur_level -= 1
-
end
-
cur_node = unmark_forward_path_at_level(cur_node, cur_level, marker)
-
end
-
last_node = cur_node
-
-
first_node.endpoint_of.delete(marker)
-
if first_node.endpoint_of.empty?
-
first_node.delete(path_to_first_node)
-
end
-
-
last_node.endpoint_of.delete(marker)
-
if last_node.endpoint_of.empty?
-
path_to_last_node = make_path
-
find(range.last, path_to_last_node)
-
last_node.delete(path_to_last_node)
-
end
-
end
-
-
1
protected
-
1
attr_reader :head, :ranges
-
-
1
def insert_node(key)
-
path = make_path
-
found_node = find(key, path)
-
if found_node && found_node.key == key
-
return found_node
-
else
-
return Node.new(key, next_node_height, path)
-
end
-
end
-
-
1
def containing_with_node(n)
-
containing = []
-
cur_node = head
-
(max_height - 1).downto(0) do |cur_level|
-
while (next_node = cur_node.forward[cur_level]) && next_node.key <= n
-
cur_node = next_node
-
if cur_node.key == n
-
return containing + (cur_node.markers - cur_node.endpoint_of), cur_node
-
end
-
end
-
containing.concat(cur_node.forward_markers[cur_level])
-
end
-
-
return containing, cur_node
-
end
-
-
1
def delete_node(key)
-
path = make_path
-
found_node = find(key, path)
-
found_node.delete(path) if found_node.key == key
-
end
-
-
1
def find(key, path)
-
cur_node = head
-
(max_height - 1).downto(0) do |cur_level|
-
while (next_node = cur_node.forward[cur_level]) && next_node.key < key
-
cur_node = next_node
-
end
-
path[cur_level] = cur_node
-
end
-
cur_node.forward[0]
-
end
-
-
1
def make_path
-
Array.new(max_height, nil)
-
end
-
-
1
def next_node_height
-
height = 1
-
while rand < probability && height < max_height
-
height += 1
-
end
-
height
-
end
-
-
1
def can_ascend_from?(node, level)
-
level < node.top_level
-
end
-
-
1
def can_descend_from?(level)
-
level > 0
-
end
-
-
1
def node_inside_range?(node, range)
-
node.key < range.last
-
end
-
-
1
def next_node_at_level_inside_range?(node, level, range)
-
node.forward[level] && node.forward[level].key <= range.last
-
end
-
-
1
def next_node_at_level_outside_range?(node, level, range)
-
(node.forward[level].nil? || node.forward[level].key > range.last)
-
end
-
-
1
def mark_forward_path_at_level(node, level, marker)
-
node.forward_markers[level].push(marker)
-
next_node = node.forward[level]
-
next_node.markers.push(marker)
-
node = next_node
-
end
-
-
1
def unmark_forward_path_at_level(node, level, marker)
-
node.forward_markers[level].delete(marker)
-
next_node = node.forward[level]
-
next_node.markers.delete(marker)
-
node = next_node
-
end
-
-
1
def nodes
-
nodes = []
-
cur_node = head.forward[0]
-
until cur_node.nil?
-
nodes << cur_node
-
cur_node = cur_node.forward[0]
-
end
-
nodes
-
end
-
end
-
1
class IntervalSkipList
-
1
class Node < HeadNode
-
1
attr_accessor :key
-
1
attr_reader :markers, :endpoint_of
-
-
1
def initialize(key, height, path)
-
super(height)
-
@key = key
-
@markers = []
-
@endpoint_of = []
-
update_forward_pointers(path)
-
promote_markers(path)
-
end
-
-
1
def all_forward_markers
-
markers.flatten
-
end
-
-
1
def delete(path)
-
0.upto(top_level) do |i|
-
path[i].forward[i] = forward[i]
-
end
-
demote_markers(path)
-
end
-
-
1
def propagate_length_change(length_change)
-
cur_node = self
-
while cur_node do
-
cur_node.key += length_change
-
cur_node = cur_node.forward[0]
-
end
-
end
-
-
1
protected
-
-
1
def update_forward_pointers(path)
-
0.upto(top_level) do |i|
-
forward[i] = path[i].forward[i]
-
path[i].forward[i] = self
-
end
-
end
-
-
1
def promote_markers(path)
-
promoted = []
-
new_promoted = []
-
0.upto(top_level) do |i|
-
incoming_markers = path[i].forward_markers[i]
-
markers.concat(incoming_markers)
-
-
incoming_markers.each do |marker|
-
if can_be_promoted_higher?(marker, i)
-
new_promoted.push(marker)
-
forward[i].delete_marker_from_path(marker, i, forward[i+1])
-
else
-
forward_markers[i].push(marker)
-
end
-
end
-
-
promoted.each do |marker|
-
if can_be_promoted_higher?(marker, i)
-
new_promoted.push(marker)
-
forward[i].delete_marker_from_path(marker, i, forward[i+1])
-
else
-
forward_markers[i].push(marker)
-
end
-
end
-
-
promoted = new_promoted
-
new_promoted = []
-
end
-
end
-
-
-
1
def can_be_promoted_higher?(marker, level)
-
level < top_level && forward[level + 1] && forward[level + 1].markers.include?(marker)
-
end
-
-
1
def delete_marker_from_path(marker, level, terminus)
-
cur_node = self
-
until cur_node == terminus
-
cur_node.forward_markers[level].delete(marker)
-
cur_node.markers.delete(marker)
-
cur_node = cur_node.forward[level]
-
end
-
end
-
-
1
def demote_markers(path)
-
demote_inbound_markers(path)
-
demote_outbound_markers(path)
-
end
-
-
1
def demote_inbound_markers(path)
-
demoted = []
-
new_demoted = []
-
-
top_level.downto(0) do |i|
-
incoming_markers = path[i].forward_markers[i].dup
-
incoming_markers.each do |marker|
-
unless forward_node_with_marker_at_or_above_level?(marker, i)
-
path[i].forward_markers[i].delete(marker)
-
new_demoted.push(marker)
-
end
-
end
-
-
demoted.each do |marker|
-
path[i + 1].place_marker_on_inbound_path(marker, i, path[i])
-
-
if forward[i].markers.include?(marker)
-
path[i].forward_markers[i].push(marker)
-
else
-
new_demoted.push(marker)
-
end
-
end
-
-
demoted = new_demoted
-
new_demoted = []
-
end
-
end
-
-
1
def demote_outbound_markers(path)
-
demoted = []
-
new_demoted = []
-
-
top_level.downto(0) do |i|
-
forward_markers[i].each do |marker|
-
new_demoted.push(marker) unless path[i].forward_markers[i].include?(marker)
-
end
-
-
demoted.each do |marker|
-
forward[i].place_marker_on_outbound_path(marker, i, forward[i + 1])
-
new_demoted.push(marker) unless path[i].forward_markers[i].include?(marker)
-
end
-
-
demoted = new_demoted
-
new_demoted = []
-
end
-
end
-
-
1
def forward_node_with_marker_at_or_above_level?(marker, level)
-
level.upto(top_level) do |i|
-
return true if forward[i].markers.include?(marker)
-
end
-
false
-
end
-
-
1
def place_marker_on_outbound_path(marker, level, terminus)
-
cur_node = self
-
until cur_node == terminus
-
cur_node.forward_markers[level].push(marker)
-
cur_node.markers.push(marker)
-
cur_node = cur_node.forward[level]
-
end
-
end
-
-
1
def place_marker_on_inbound_path(marker, level, terminus)
-
cur_node = self
-
until cur_node == terminus
-
cur_node.forward_markers[level].push(marker)
-
cur_node = cur_node.forward[level]
-
cur_node.markers.push(marker)
-
end
-
end
-
end
-
end
-
1
module Treetop
-
1
module Runtime
-
1
class TerminalParseFailure
-
1
attr_reader :index, :expected_string
-
-
1
def initialize(index, expected_string)
-
@index = index
-
@expected_string = expected_string
-
end
-
-
1
def to_s
-
"String matching #{expected_string} expected."
-
end
-
end
-
end
-
end
-
1
require 'turbolinks/version'
-
1
require 'turbolinks/xhr_headers'
-
1
require 'turbolinks/xhr_url_for'
-
1
require 'turbolinks/cookies'
-
1
require 'turbolinks/x_domain_blocker'
-
1
require 'turbolinks/redirection'
-
-
1
module Turbolinks
-
1
class Engine < ::Rails::Engine
-
1
initializer :turbolinks do |config|
-
1
ActiveSupport.on_load(:action_controller) do
-
1
ActionController::Base.class_eval do
-
1
include XHRHeaders, Cookies, XDomainBlocker, Redirection
-
1
before_filter :set_xhr_redirected_to, :set_request_method_cookie
-
1
after_filter :abort_xdomain_redirect
-
end
-
-
1
ActionDispatch::Request.class_eval do
-
1
def referer
-
self.headers['X-XHR-Referer'] || super
-
end
-
1
alias referrer referer
-
end
-
end
-
-
ActiveSupport.on_load(:action_view) do
-
1
(ActionView::RoutingUrlFor rescue ActionView::Helpers::UrlHelper).module_eval do
-
1
include XHRUrlFor
-
end
-
1
end unless RUBY_VERSION =~ /^1\.8/
-
end
-
end
-
end
-
1
module Turbolinks
-
# Sets a request_method cookie containing the request method of the current request.
-
# The Turbolinks script will not initialize if this cookie is set to anything other than GET.
-
1
module Cookies
-
1
private
-
1
def set_request_method_cookie
-
cookies[:request_method] = request.request_method
-
end
-
end
-
end
-
1
module Turbolinks
-
# Provides a means of using Turbolinks to perform redirects. The server
-
# will respond with a JavaScript call to Turbolinks.visit(url).
-
1
module Redirection
-
1
extend ActiveSupport::Concern
-
-
1
def redirect_via_turbolinks_to(url = {}, response_status = {})
-
redirect_to(url, response_status)
-
-
self.status = 200
-
self.response_body = "Turbolinks.visit('#{location}');"
-
response.content_type = Mime::JS
-
end
-
end
-
end
-
1
module Turbolinks
-
1
VERSION = '2.3.0'
-
end
-
1
module Turbolinks
-
# Changes the response status to 403 Forbidden if all of these conditions are true:
-
# - The current request originated from Turbolinks
-
# - The request is being redirected to a different domain
-
1
module XDomainBlocker
-
1
private
-
1
def same_origin?(a, b)
-
a = URI.parse URI.escape(a)
-
b = URI.parse URI.escape(b)
-
[a.scheme, a.host, a.port] == [b.scheme, b.host, b.port]
-
end
-
-
1
def abort_xdomain_redirect
-
to_uri = response.headers['Location'] || ""
-
current = request.headers['X-XHR-Referer'] || ""
-
unless to_uri.blank? || current.blank? || same_origin?(current, to_uri)
-
self.status = 403
-
end
-
end
-
end
-
end
-
1
module Turbolinks
-
# Intercepts calls to _compute_redirect_to_location (used by redirect_to) for two purposes.
-
#
-
# 1. Corrects the behavior of redirect_to with the :back option by using the X-XHR-Referer
-
# request header instead of the standard Referer request header.
-
#
-
# 2. Stores the return value (the redirect target url) to persist through to the redirect
-
# request, where it will be used to set the X-XHR-Redirected-To response header. The
-
# Turbolinks script will detect the header and use replaceState to reflect the redirected
-
# url.
-
1
module XHRHeaders
-
1
extend ActiveSupport::Concern
-
-
1
def _compute_redirect_to_location(*args)
-
options, request = _normalize_redirect_params(args)
-
-
store_for_turbolinks begin
-
if options == :back && request.headers["X-XHR-Referer"]
-
super(*[(request if args.length == 2), request.headers["X-XHR-Referer"]].compact)
-
else
-
super(*args)
-
end
-
end
-
end
-
-
1
private
-
1
def store_for_turbolinks(url)
-
session[:_turbolinks_redirect_to] = url if request.headers["X-XHR-Referer"]
-
url
-
end
-
-
1
def set_xhr_redirected_to
-
if session[:_turbolinks_redirect_to]
-
response.headers['X-XHR-Redirected-To'] = session.delete :_turbolinks_redirect_to
-
end
-
end
-
-
# Ensure backwards compatibility
-
# Rails < 4.2: _compute_redirect_to_location(options)
-
# Rails >= 4.2: _compute_redirect_to_location(request, options)
-
1
def _normalize_redirect_params(args)
-
options, req = args.reverse
-
[options, req || request]
-
end
-
end
-
end
-
1
module Turbolinks
-
# Corrects the behavior of url_for (and link_to, which uses url_for) with the :back
-
# option by using the X-XHR-Referer request header instead of the standard Referer
-
# request header.
-
1
module XHRUrlFor
-
1
def self.included(base)
-
1
base.alias_method_chain :url_for, :xhr_referer
-
end
-
-
1
def url_for_with_xhr_referer(options = {})
-
options = (controller.request.headers["X-XHR-Referer"] || options) if options == :back
-
url_for_without_xhr_referer options
-
end
-
end
-
end
-
# Top level module for TZInfo.
-
1
module TZInfo
-
end
-
-
1
require 'tzinfo/ruby_core_support'
-
1
require 'tzinfo/offset_rationals'
-
1
require 'tzinfo/time_or_datetime'
-
-
1
require 'tzinfo/timezone_definition'
-
-
1
require 'tzinfo/timezone_offset'
-
1
require 'tzinfo/timezone_transition'
-
1
require 'tzinfo/timezone_transition_definition'
-
-
1
require 'tzinfo/timezone_index_definition'
-
-
1
require 'tzinfo/timezone_info'
-
1
require 'tzinfo/data_timezone_info'
-
1
require 'tzinfo/linked_timezone_info'
-
1
require 'tzinfo/transition_data_timezone_info'
-
1
require 'tzinfo/zoneinfo_timezone_info'
-
-
1
require 'tzinfo/data_source'
-
1
require 'tzinfo/ruby_data_source'
-
1
require 'tzinfo/zoneinfo_data_source'
-
-
1
require 'tzinfo/timezone_period'
-
1
require 'tzinfo/timezone'
-
1
require 'tzinfo/info_timezone'
-
1
require 'tzinfo/data_timezone'
-
1
require 'tzinfo/linked_timezone'
-
1
require 'tzinfo/timezone_proxy'
-
-
1
require 'tzinfo/country_index_definition'
-
1
require 'tzinfo/country_info'
-
1
require 'tzinfo/ruby_country_info'
-
1
require 'tzinfo/zoneinfo_country_info'
-
-
1
require 'tzinfo/country'
-
1
require 'tzinfo/country_timezone'
-
1
require 'thread_safe'
-
-
1
module TZInfo
-
# Raised by Country#get if the code given is not valid.
-
1
class InvalidCountryCode < StandardError
-
end
-
-
# The Country class represents an ISO 3166-1 country. It can be used to
-
# obtain a list of Timezones for a country. For example:
-
#
-
# us = Country.get('US')
-
# us.zone_identifiers
-
# us.zones
-
# us.zone_info
-
#
-
# The Country class is thread-safe. It is safe to use class and instance
-
# methods of Country in concurrently executing threads. Instances of Country
-
# can be shared across thread boundaries.
-
#
-
# Country information available through TZInfo is intended as an aid for
-
# users, to help them select time zone data appropriate for their practical
-
# needs. It is not intended to take or endorse any position on legal or
-
# territorial claims.
-
1
class Country
-
1
include Comparable
-
-
# Defined countries.
-
#
-
# @!visibility private
-
1
@@countries = nil
-
-
# Whether the countries index has been loaded yet.
-
#
-
# @!visibility private
-
1
@@index_loaded = false
-
-
# Gets a Country by its ISO 3166-1 alpha-2 code. Raises an
-
# InvalidCountryCode exception if it couldn't be found.
-
1
def self.get(identifier)
-
instance = @@countries[identifier]
-
-
unless instance
-
# Thread-safety: It is possible that multiple equivalent Country
-
# instances could be created here in concurrently executing threads.
-
# The consequences of this are that the data may be loaded more than
-
# once (depending on the data source) and memoized calculations could
-
# be discarded. The performance benefit of ensuring that only a single
-
# instance is created is unlikely to be worth the overhead of only
-
# allowing one Country to be loaded at a time.
-
info = data_source.load_country_info(identifier)
-
instance = Country.new(info)
-
@@countries[identifier] = instance
-
end
-
-
instance
-
end
-
-
# If identifier is a CountryInfo object, initializes the Country instance,
-
# otherwise calls get(identifier).
-
1
def self.new(identifier)
-
if identifier.kind_of?(CountryInfo)
-
instance = super()
-
instance.send :setup, identifier
-
instance
-
else
-
get(identifier)
-
end
-
end
-
-
# Returns an Array of all the valid country codes.
-
1
def self.all_codes
-
data_source.country_codes
-
end
-
-
# Returns an Array of all the defined Countries.
-
1
def self.all
-
data_source.country_codes.collect {|code| get(code)}
-
end
-
-
# The ISO 3166-1 alpha-2 country code.
-
1
def code
-
@info.code
-
end
-
-
# The name of the country.
-
1
def name
-
@info.name
-
end
-
-
# Alias for name.
-
1
def to_s
-
name
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}: #{@info.code}>"
-
end
-
-
# Returns a frozen array of all the zone identifiers for the country. These
-
# are in an order that
-
#
-
# 1. makes some geographical sense, and
-
# 2. puts the most populous zones first, where that does not contradict 1.
-
#
-
# Returned zone identifiers may refer to cities and regions outside of the
-
# country. This will occur if the zone covers multiple countries. Any zones
-
# referring to a city or region in a different country will be listed after
-
# those relating to this country.
-
1
def zone_identifiers
-
@info.zone_identifiers
-
end
-
1
alias zone_names zone_identifiers
-
-
# An array of all the Timezones for this country. Returns TimezoneProxy
-
# objects to avoid the overhead of loading Timezone definitions until
-
# a conversion is actually required. The Timezones are returned in an order
-
# that
-
#
-
# 1. makes some geographical sense, and
-
# 2. puts the most populous zones first, where that does not contradict 1.
-
#
-
# Identifiers of the zones returned may refer to cities and regions outside
-
# of the country. This will occur if the zone covers multiple countries. Any
-
# zones referring to a city or region in a different country will be listed
-
# after those relating to this country.
-
1
def zones
-
zone_identifiers.collect {|id|
-
Timezone.get_proxy(id)
-
}
-
end
-
-
# Returns a frozen array of all the timezones for the for the country as
-
# CountryTimezone instances (containing extra information about each zone).
-
# These are in an order that
-
#
-
# 1. makes some geographical sense, and
-
# 2. puts the most populous zones first, where that does not contradict 1.
-
#
-
# Identifiers and descriptions of the zones returned may refer to cities and
-
# regions outside of the country. This will occur if the zone covers
-
# multiple countries. Any zones referring to a city or region in a different
-
# country will be listed after those relating to this country.
-
1
def zone_info
-
@info.zones
-
end
-
-
# Compare two Countries based on their code. Returns -1 if c is less
-
# than self, 0 if c is equal to self and +1 if c is greater than self.
-
#
-
# Returns nil if c is not comparable with Country instances.
-
1
def <=>(c)
-
return nil unless c.is_a?(Country)
-
code <=> c.code
-
end
-
-
# Returns true if and only if the code of c is equal to the code of this
-
# Country.
-
1
def eql?(c)
-
self == c
-
end
-
-
# Returns a hash value for this Country.
-
1
def hash
-
code.hash
-
end
-
-
# Dumps this Country for marshalling.
-
1
def _dump(limit)
-
code
-
end
-
-
# Loads a marshalled Country.
-
1
def self._load(data)
-
Country.get(data)
-
end
-
-
1
private
-
# Called by Country.new to initialize a new Country instance. The info
-
# parameter is a CountryInfo that defines the country.
-
1
def setup(info)
-
@info = info
-
end
-
-
# Initializes @@countries.
-
1
def self.init_countries
-
1
@@countries = ThreadSafe::Cache.new
-
end
-
1
init_countries
-
-
# Returns the current DataSource
-
1
def self.data_source
-
DataSource.get
-
end
-
end
-
end
-
1
module TZInfo
-
# The country index file includes CountryIndexDefinition which provides
-
# a country method used to define each country in the index.
-
#
-
# @private
-
1
module CountryIndexDefinition #:nodoc:
-
1
def self.append_features(base)
-
super
-
base.extend(ClassMethods)
-
base.instance_eval { @countries = {} }
-
end
-
-
# Class methods for inclusion.
-
#
-
# @private
-
1
module ClassMethods #:nodoc:
-
# Defines a country with an ISO 3166 country code, name and block. The
-
# block will be evaluated to obtain all the timezones for the country.
-
# Calls Country.country_defined with the definition of each country.
-
1
def country(code, name, &block)
-
@countries[code] = RubyCountryInfo.new(code, name, &block)
-
end
-
-
# Returns a frozen hash of all the countries that have been defined in
-
# the index.
-
1
def countries
-
@countries.freeze
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
# Represents a country and references to its timezones as returned by a
-
# DataSource.
-
1
class CountryInfo
-
# The ISO 3166 country code.
-
1
attr_reader :code
-
-
# The name of the country.
-
1
attr_reader :name
-
-
# Constructs a new CountryInfo with an ISO 3166 country code and name
-
1
def initialize(code, name)
-
249
@code = code
-
249
@name = name
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}: #@code>"
-
end
-
-
# Returns a frozen array of all the zone identifiers for the country.
-
# The identifiers are ordered by importance according to the DataSource.
-
1
def zone_identifiers
-
raise_not_implemented('zone_identifiers')
-
end
-
-
# Returns a frozen array of all the timezones for the for the country as
-
# CountryTimezone instances.
-
#
-
# The timezones are ordered by importance according to the DataSource.
-
1
def zones
-
raise_not_implemented('zones')
-
end
-
-
1
private
-
-
1
def raise_not_implemented(method_name)
-
raise NotImplementedError, "Subclasses must override #{method_name}"
-
end
-
end
-
end
-
1
module TZInfo
-
# A Timezone within a Country. This contains extra information about the
-
# Timezone that is specific to the Country (a Timezone could be used by
-
# multiple countries).
-
1
class CountryTimezone
-
# The zone identifier.
-
1
attr_reader :identifier
-
-
# A description of this timezone in relation to the country, e.g.
-
# "Eastern Time". This is usually nil for countries having only a single
-
# Timezone.
-
1
attr_reader :description
-
-
1
class << self
-
# Creates a new CountryTimezone with a timezone identifier, latitude,
-
# longitude and description. The latitude and longitude are specified as
-
# rationals - a numerator and denominator. For performance reasons, the
-
# numerators and denominators must be specified in their lowest form.
-
#
-
# For use internally within TZInfo.
-
#
-
# @!visibility private
-
1
alias :new! :new
-
-
# Creates a new CountryTimezone with a timezone identifier, latitude,
-
# longitude and description. The latitude and longitude must be specified
-
# as instances of Rational.
-
#
-
# CountryTimezone instances should normally only be constructed when
-
# creating new DataSource implementations.
-
1
def new(identifier, latitude, longitude, description = nil)
-
416
super(identifier, latitude, nil, longitude, nil, description)
-
end
-
end
-
-
# Creates a new CountryTimezone with a timezone identifier, latitude,
-
# longitude and description. The latitude and longitude are specified as
-
# rationals - a numerator and denominator. For performance reasons, the
-
# numerators and denominators must be specified in their lowest form.
-
#
-
# @!visibility private
-
1
def initialize(identifier, latitude_numerator, latitude_denominator,
-
longitude_numerator, longitude_denominator, description = nil) #:nodoc:
-
416
@identifier = identifier
-
-
416
if latitude_numerator.kind_of?(Rational)
-
416
@latitude = latitude_numerator
-
else
-
@latitude = nil
-
@latitude_numerator = latitude_numerator
-
@latitude_denominator = latitude_denominator
-
end
-
-
416
if longitude_numerator.kind_of?(Rational)
-
416
@longitude = longitude_numerator
-
else
-
@longitude = nil
-
@longitude_numerator = longitude_numerator
-
@longitude_denominator = longitude_denominator
-
end
-
-
416
@description = description
-
end
-
-
# The Timezone (actually a TimezoneProxy for performance reasons).
-
1
def timezone
-
Timezone.get_proxy(@identifier)
-
end
-
-
# if description is not nil, this method returns description; otherwise it
-
# returns timezone.friendly_identifier(true).
-
1
def description_or_friendly_identifier
-
description || timezone.friendly_identifier(true)
-
end
-
-
# The latitude of this timezone in degrees as a Rational.
-
1
def latitude
-
# Thread-safety: It is possible that the value of @latitude may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @latitude is only
-
# calculated once.
-
@latitude ||= RubyCoreSupport.rational_new!(@latitude_numerator, @latitude_denominator)
-
end
-
-
# The longitude of this timezone in degrees as a Rational.
-
1
def longitude
-
# Thread-safety: It is possible that the value of @longitude may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @longitude is only
-
# calculated once.
-
@longitude ||= RubyCoreSupport.rational_new!(@longitude_numerator, @longitude_denominator)
-
end
-
-
# Returns true if and only if the given CountryTimezone is equal to the
-
# current CountryTimezone (has the same identifer, latitude, longitude
-
# and description).
-
1
def ==(ct)
-
ct.kind_of?(CountryTimezone) &&
-
identifier == ct.identifier && latitude == ct.latitude &&
-
longitude == ct.longitude && description == ct.description
-
end
-
-
# Returns true if and only if the given CountryTimezone is equal to the
-
# current CountryTimezone (has the same identifer, latitude, longitude
-
# and description).
-
1
def eql?(ct)
-
self == ct
-
end
-
-
# Returns a hash of this CountryTimezone.
-
1
def hash
-
@identifier.hash ^
-
(@latitude ? @latitude.numerator.hash ^ @latitude.denominator.hash : @latitude_numerator.hash ^ @latitude_denominator.hash) ^
-
(@longitude ? @longitude.numerator.hash ^ @longitude.denominator.hash : @longitude_numerator.hash ^ @longitude_denominator.hash) ^
-
@description.hash
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}: #@identifier>"
-
end
-
end
-
end
-
1
require 'thread'
-
-
1
module TZInfo
-
# InvalidDataSource is raised if the DataSource is used doesn't implement one
-
# of the required methods.
-
1
class InvalidDataSource < StandardError
-
end
-
-
# DataSourceNotFound is raised if no data source could be found (i.e.
-
# if 'tzinfo/data' cannot be found on the load path and no valid zoneinfo
-
# directory can be found on the system).
-
1
class DataSourceNotFound < StandardError
-
end
-
-
# The base class for data sources of timezone and country data.
-
#
-
# Use DataSource.set to change the data source being used.
-
1
class DataSource
-
# The currently selected data source.
-
1
@@instance = nil
-
-
# Mutex used to ensure the default data source is only created once.
-
1
@@default_mutex = Mutex.new
-
-
# Returns the currently selected DataSource instance.
-
1
def self.get
-
# If a DataSource hasn't been manually set when the first request is
-
# made to obtain a DataSource, then a Default data source is created.
-
-
# This is done at the first request rather than when TZInfo is loaded to
-
# avoid unnecessary (or in some cases potentially harmful) attempts to
-
# find a suitable DataSource.
-
-
# A Mutex is used to ensure that only a single default instance is
-
# created (having two different DataSources in use simultaneously could
-
# cause unexpected results).
-
-
1
unless @@instance
-
1
@@default_mutex.synchronize do
-
1
set(create_default_data_source) unless @@instance
-
end
-
end
-
-
1
@@instance
-
end
-
-
# Sets the currently selected data source for Timezone and Country data.
-
#
-
# This should usually be set to one of the two standard data source types:
-
#
-
# * +:ruby+ - read data from the Ruby modules included in the TZInfo::Data
-
# library (tzinfo-data gem).
-
# * +:zoneinfo+ - read data from the zoneinfo files included with most
-
# Unix-like operating sytems (e.g. in /usr/share/zoneinfo).
-
#
-
# To set TZInfo to use one of the standard data source types, call
-
# \TZInfo::DataSource.set in one of the following ways:
-
#
-
# TZInfo::DataSource.set(:ruby)
-
# TZInfo::DataSource.set(:zoneinfo)
-
# TZInfo::DataSource.set(:zoneinfo, zoneinfo_dir)
-
# TZInfo::DataSource.set(:zoneinfo, zoneinfo_dir, iso3166_tab_file)
-
#
-
# \DataSource.set(:zoneinfo) will automatically search for the zoneinfo
-
# directory by checking the paths specified in
-
# ZoneinfoDataSource.search_paths. ZoneinfoDirectoryNotFound will be raised
-
# if no valid zoneinfo directory could be found.
-
#
-
# \DataSource.set(:zoneinfo, zoneinfo_dir) uses the specified zoneinfo
-
# directory as the data source. If the directory is not a valid zoneinfo
-
# directory, an InvalidZoneinfoDirectory exception will be raised.
-
#
-
# \DataSource.set(:zoneinfo, zoneinfo_dir, iso3166_tab_file) uses the
-
# specified zoneinfo directory as the data source, but loads the iso3166.tab
-
# file from an alternate path. If the directory is not a valid zoneinfo
-
# directory, an InvalidZoneinfoDirectory exception will be raised.
-
#
-
# Custom data sources can be created by subclassing TZInfo::DataSource and
-
# implementing the following methods:
-
#
-
# * \load_timezone_info
-
# * \timezone_identifiers
-
# * \data_timezone_identifiers
-
# * \linked_timezone_identifiers
-
# * \load_country_info
-
# * \country_codes
-
#
-
# To have TZInfo use the custom data source, call \DataSource.set
-
# as follows:
-
#
-
# TZInfo::DataSource.set(CustomDataSource.new)
-
#
-
# To avoid inconsistent data, \DataSource.set should be called before
-
# accessing any Timezone or Country data.
-
#
-
# If \DataSource.set is not called, TZInfo will by default use TZInfo::Data
-
# as the data source. If TZInfo::Data is not available (i.e. if require
-
# 'tzinfo/data' fails), then TZInfo will search for a zoneinfo directory
-
# instead (using the search path specified by
-
# TZInfo::ZoneinfoDataSource::DEFAULT_SEARCH_PATH).
-
1
def self.set(data_source_or_type, *args)
-
1
if data_source_or_type.kind_of?(DataSource)
-
1
@@instance = data_source_or_type
-
elsif data_source_or_type == :ruby
-
@@instance = RubyDataSource.new
-
elsif data_source_or_type == :zoneinfo
-
@@instance = ZoneinfoDataSource.new(*args)
-
else
-
raise ArgumentError, 'data_source_or_type must be a DataSource instance or a data source type (:ruby)'
-
end
-
end
-
-
# Returns a TimezoneInfo instance for a given identifier. The TimezoneInfo
-
# instance should derive from either DataTimzoneInfo for timezones that
-
# define their own data or LinkedTimezoneInfo for links or aliases to
-
# other timezones.
-
#
-
# Raises InvalidTimezoneIdentifier if the timezone is not found or the
-
# identifier is invalid.
-
1
def load_timezone_info(identifier)
-
raise_invalid_data_source('load_timezone_info')
-
end
-
-
# Returns an array of all the available timezone identifiers.
-
1
def timezone_identifiers
-
raise_invalid_data_source('timezone_identifiers')
-
end
-
-
# Returns an array of all the available timezone identifiers for
-
# data timezones (i.e. those that actually contain definitions).
-
1
def data_timezone_identifiers
-
raise_invalid_data_source('data_timezone_identifiers')
-
end
-
-
# Returns an array of all the available timezone identifiers that
-
# are links to other timezones.
-
1
def linked_timezone_identifiers
-
raise_invalid_data_source('linked_timezone_identifiers')
-
end
-
-
# Returns a CountryInfo instance for the given ISO 3166-1 alpha-2
-
# country code. Raises InvalidCountryCode if the country could not be found
-
# or the code is invalid.
-
1
def load_country_info(code)
-
raise_invalid_data_source('load_country_info')
-
end
-
-
# Returns an array of all the available ISO 3166-1 alpha-2
-
# country codes.
-
1
def country_codes
-
raise_invalid_data_source('country_codes')
-
end
-
-
# Returns the name of this DataSource.
-
1
def to_s
-
"Default DataSource"
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}>"
-
end
-
-
1
private
-
-
# Creates a DataSource instance for use as the default. Used if
-
# no preference has been specified manually.
-
1
def self.create_default_data_source
-
1
has_tzinfo_data = false
-
-
1
begin
-
1
require 'tzinfo/data'
-
has_tzinfo_data = true
-
rescue LoadError
-
end
-
-
1
return RubyDataSource.new if has_tzinfo_data
-
-
1
begin
-
1
return ZoneinfoDataSource.new
-
rescue ZoneinfoDirectoryNotFound
-
raise DataSourceNotFound, "No source of timezone data could be found.\nPlease refer to http://tzinfo.github.io/datasourcenotfound for help resolving this error."
-
end
-
end
-
-
1
def raise_invalid_data_source(method_name)
-
raise InvalidDataSource, "#{method_name} not defined"
-
end
-
end
-
end
-
1
module TZInfo
-
-
# A Timezone based on a DataTimezoneInfo.
-
#
-
# @private
-
1
class DataTimezone < InfoTimezone #:nodoc:
-
-
# Returns the TimezonePeriod for the given UTC time. utc can either be
-
# a DateTime, Time or integer timestamp (Time.to_i). Any timezone
-
# information in utc is ignored (it is treated as a UTC time).
-
#
-
# If no TimezonePeriod could be found, PeriodNotFound is raised.
-
1
def period_for_utc(utc)
-
1
info.period_for_utc(utc)
-
end
-
-
# Returns the set of TimezonePeriod instances that are valid for the given
-
# local time as an array. If you just want a single period, use
-
# period_for_local instead and specify how abiguities should be resolved.
-
# Raises PeriodNotFound if no periods are found for the given time.
-
1
def periods_for_local(local)
-
info.periods_for_local(local)
-
end
-
-
# Returns an Array of TimezoneTransition instances representing the times
-
# where the UTC offset of the timezone changes.
-
#
-
# Transitions are returned up to a given date and time up to a given date
-
# and time, specified in UTC (utc_to).
-
#
-
# A from date and time may also be supplied using the utc_from parameter
-
# (also specified in UTC). If utc_from is not nil, only transitions from
-
# that date and time onwards will be returned.
-
#
-
# Comparisons with utc_to are exclusive. Comparisons with utc_from are
-
# inclusive. If a transition falls precisely on utc_to, it will be excluded.
-
# If a transition falls on utc_from, it will be included.
-
#
-
# Transitions returned are ordered by when they occur, from earliest to
-
# latest.
-
#
-
# utc_to and utc_from can be specified using either DateTime, Time or
-
# integer timestamps (Time.to_i).
-
#
-
# If utc_from is specified and utc_to is not greater than utc_from, then
-
# transitions_up_to raises an ArgumentError exception.
-
1
def transitions_up_to(utc_to, utc_from = nil)
-
info.transitions_up_to(utc_to, utc_from)
-
end
-
-
# Returns the canonical zone for this Timezone.
-
#
-
# For a DataTimezone, this is always self.
-
1
def canonical_zone
-
self
-
end
-
end
-
end
-
1
module TZInfo
-
# Represents a defined timezone containing transition data.
-
1
class DataTimezoneInfo < TimezoneInfo
-
-
# Returns the TimezonePeriod for the given UTC time.
-
1
def period_for_utc(utc)
-
raise_not_implemented('period_for_utc')
-
end
-
-
# Returns the set of TimezonePeriods for the given local time as an array.
-
# Results returned are ordered by increasing UTC start date.
-
# Returns an empty array if no periods are found for the given time.
-
1
def periods_for_local(local)
-
raise_not_implemented('periods_for_local')
-
end
-
-
# Returns an Array of TimezoneTransition instances representing the times
-
# where the UTC offset of the timezone changes.
-
#
-
# Transitions are returned up to a given date and time up to a given date
-
# and time, specified in UTC (utc_to).
-
#
-
# A from date and time may also be supplied using the utc_from parameter
-
# (also specified in UTC). If utc_from is not nil, only transitions from
-
# that date and time onwards will be returned.
-
#
-
# Comparisons with utc_to are exclusive. Comparisons with utc_from are
-
# inclusive. If a transition falls precisely on utc_to, it will be excluded.
-
# If a transition falls on utc_from, it will be included.
-
#
-
# Transitions returned are ordered by when they occur, from earliest to
-
# latest.
-
#
-
# utc_to and utc_from can be specified using either DateTime, Time or
-
# integer timestamps (Time.to_i).
-
#
-
# If utc_from is specified and utc_to is not greater than utc_from, then
-
# transitions_up_to raises an ArgumentError exception.
-
1
def transitions_up_to(utc_to, utc_from = nil)
-
raise_not_implemented('transitions_up_to')
-
end
-
-
# Constructs a Timezone instance for the timezone represented by this
-
# DataTimezoneInfo.
-
1
def create_timezone
-
1
DataTimezone.new(self)
-
end
-
-
1
private
-
-
1
def raise_not_implemented(method_name)
-
raise NotImplementedError, "Subclasses must override #{method_name}"
-
end
-
end
-
end
-
1
module TZInfo
-
-
# A Timezone based on a TimezoneInfo.
-
#
-
# @private
-
1
class InfoTimezone < Timezone #:nodoc:
-
-
# Constructs a new InfoTimezone with a TimezoneInfo instance.
-
1
def self.new(info)
-
1
tz = super()
-
1
tz.send(:setup, info)
-
1
tz
-
end
-
-
# The identifier of the timezone, e.g. "Europe/Paris".
-
1
def identifier
-
1
@info.identifier
-
end
-
-
1
protected
-
# The TimezoneInfo for this Timezone.
-
1
def info
-
1
@info
-
end
-
-
1
def setup(info)
-
1
@info = info
-
end
-
end
-
end
-
1
module TZInfo
-
-
# A Timezone based on a LinkedTimezoneInfo.
-
#
-
# @private
-
1
class LinkedTimezone < InfoTimezone #:nodoc:
-
# Returns the TimezonePeriod for the given UTC time. utc can either be
-
# a DateTime, Time or integer timestamp (Time.to_i). Any timezone
-
# information in utc is ignored (it is treated as a UTC time).
-
#
-
# If no TimezonePeriod could be found, PeriodNotFound is raised.
-
1
def period_for_utc(utc)
-
@linked_timezone.period_for_utc(utc)
-
end
-
-
# Returns the set of TimezonePeriod instances that are valid for the given
-
# local time as an array. If you just want a single period, use
-
# period_for_local instead and specify how abiguities should be resolved.
-
# Raises PeriodNotFound if no periods are found for the given time.
-
1
def periods_for_local(local)
-
@linked_timezone.periods_for_local(local)
-
end
-
-
# Returns an Array of TimezoneTransition instances representing the times
-
# where the UTC offset of the timezone changes.
-
#
-
# Transitions are returned up to a given date and time up to a given date
-
# and time, specified in UTC (utc_to).
-
#
-
# A from date and time may also be supplied using the utc_from parameter
-
# (also specified in UTC). If utc_from is not nil, only transitions from
-
# that date and time onwards will be returned.
-
#
-
# Comparisons with utc_to are exclusive. Comparisons with utc_from are
-
# inclusive. If a transition falls precisely on utc_to, it will be excluded.
-
# If a transition falls on utc_from, it will be included.
-
#
-
# Transitions returned are ordered by when they occur, from earliest to
-
# latest.
-
#
-
# utc_to and utc_from can be specified using either DateTime, Time or
-
# integer timestamps (Time.to_i).
-
#
-
# If utc_from is specified and utc_to is not greater than utc_from, then
-
# transitions_up_to raises an ArgumentError exception.
-
1
def transitions_up_to(utc_to, utc_from = nil)
-
@linked_timezone.transitions_up_to(utc_to, utc_from)
-
end
-
-
# Returns the canonical zone for this Timezone.
-
#
-
# For a LinkedTimezone, this is the canonical zone of the link target.
-
1
def canonical_zone
-
@linked_timezone.canonical_zone
-
end
-
-
1
protected
-
1
def setup(info)
-
super(info)
-
@linked_timezone = Timezone.get(info.link_to_identifier)
-
end
-
end
-
end
-
1
module TZInfo
-
# Represents a timezone that is defined as a link or alias to another zone.
-
1
class LinkedTimezoneInfo < TimezoneInfo
-
-
# The zone that provides the data (that this zone is an alias for).
-
1
attr_reader :link_to_identifier
-
-
# Constructs a new LinkedTimezoneInfo with an identifier and the identifier
-
# of the zone linked to.
-
1
def initialize(identifier, link_to_identifier)
-
super(identifier)
-
@link_to_identifier = link_to_identifier
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}: #@identifier,#@link_to_identifier>"
-
end
-
-
# Constructs a Timezone instance for the timezone represented by this
-
# DataTimezoneInfo.
-
1
def create_timezone
-
LinkedTimezone.new(self)
-
end
-
end
-
end
-
1
require 'rational' unless defined?(Rational)
-
-
1
module TZInfo
-
-
# Provides a method for getting Rationals for a timezone offset in seconds.
-
# Pre-reduced rationals are returned for all the half-hour intervals between
-
# -14 and +14 hours to avoid having to call gcd at runtime.
-
#
-
# @private
-
1
module OffsetRationals #:nodoc:
-
1
@@rational_cache = {
-
-50400 => RubyCoreSupport.rational_new!(-7,12),
-
-48600 => RubyCoreSupport.rational_new!(-9,16),
-
-46800 => RubyCoreSupport.rational_new!(-13,24),
-
-45000 => RubyCoreSupport.rational_new!(-25,48),
-
-43200 => RubyCoreSupport.rational_new!(-1,2),
-
-41400 => RubyCoreSupport.rational_new!(-23,48),
-
-39600 => RubyCoreSupport.rational_new!(-11,24),
-
-37800 => RubyCoreSupport.rational_new!(-7,16),
-
-36000 => RubyCoreSupport.rational_new!(-5,12),
-
-34200 => RubyCoreSupport.rational_new!(-19,48),
-
-32400 => RubyCoreSupport.rational_new!(-3,8),
-
-30600 => RubyCoreSupport.rational_new!(-17,48),
-
-28800 => RubyCoreSupport.rational_new!(-1,3),
-
-27000 => RubyCoreSupport.rational_new!(-5,16),
-
-25200 => RubyCoreSupport.rational_new!(-7,24),
-
-23400 => RubyCoreSupport.rational_new!(-13,48),
-
-21600 => RubyCoreSupport.rational_new!(-1,4),
-
-19800 => RubyCoreSupport.rational_new!(-11,48),
-
-18000 => RubyCoreSupport.rational_new!(-5,24),
-
-16200 => RubyCoreSupport.rational_new!(-3,16),
-
-14400 => RubyCoreSupport.rational_new!(-1,6),
-
-12600 => RubyCoreSupport.rational_new!(-7,48),
-
-10800 => RubyCoreSupport.rational_new!(-1,8),
-
-9000 => RubyCoreSupport.rational_new!(-5,48),
-
-7200 => RubyCoreSupport.rational_new!(-1,12),
-
-5400 => RubyCoreSupport.rational_new!(-1,16),
-
-3600 => RubyCoreSupport.rational_new!(-1,24),
-
-1800 => RubyCoreSupport.rational_new!(-1,48),
-
0 => RubyCoreSupport.rational_new!(0,1),
-
1800 => RubyCoreSupport.rational_new!(1,48),
-
3600 => RubyCoreSupport.rational_new!(1,24),
-
5400 => RubyCoreSupport.rational_new!(1,16),
-
7200 => RubyCoreSupport.rational_new!(1,12),
-
9000 => RubyCoreSupport.rational_new!(5,48),
-
10800 => RubyCoreSupport.rational_new!(1,8),
-
12600 => RubyCoreSupport.rational_new!(7,48),
-
14400 => RubyCoreSupport.rational_new!(1,6),
-
16200 => RubyCoreSupport.rational_new!(3,16),
-
18000 => RubyCoreSupport.rational_new!(5,24),
-
19800 => RubyCoreSupport.rational_new!(11,48),
-
21600 => RubyCoreSupport.rational_new!(1,4),
-
23400 => RubyCoreSupport.rational_new!(13,48),
-
25200 => RubyCoreSupport.rational_new!(7,24),
-
27000 => RubyCoreSupport.rational_new!(5,16),
-
28800 => RubyCoreSupport.rational_new!(1,3),
-
30600 => RubyCoreSupport.rational_new!(17,48),
-
32400 => RubyCoreSupport.rational_new!(3,8),
-
34200 => RubyCoreSupport.rational_new!(19,48),
-
36000 => RubyCoreSupport.rational_new!(5,12),
-
37800 => RubyCoreSupport.rational_new!(7,16),
-
39600 => RubyCoreSupport.rational_new!(11,24),
-
41400 => RubyCoreSupport.rational_new!(23,48),
-
43200 => RubyCoreSupport.rational_new!(1,2),
-
45000 => RubyCoreSupport.rational_new!(25,48),
-
46800 => RubyCoreSupport.rational_new!(13,24),
-
48600 => RubyCoreSupport.rational_new!(9,16),
-
50400 => RubyCoreSupport.rational_new!(7,12)}.freeze
-
-
# Returns a Rational expressing the fraction of a day that offset in
-
# seconds represents (i.e. equivalent to Rational(offset, 86400)).
-
1
def rational_for_offset(offset)
-
@@rational_cache[offset] || Rational(offset, 86400)
-
end
-
1
module_function :rational_for_offset
-
end
-
end
-
1
require 'date'
-
1
require 'rational' unless defined?(Rational)
-
-
1
module TZInfo
-
-
# Methods to support different versions of Ruby.
-
#
-
# @private
-
1
module RubyCoreSupport #:nodoc:
-
-
# Use Rational.new! for performance reasons in Ruby 1.8.
-
# This has been removed from 1.9, but Rational performs better.
-
1
if Rational.respond_to? :new!
-
def self.rational_new!(numerator, denominator = 1)
-
Rational.new!(numerator, denominator)
-
end
-
else
-
1
def self.rational_new!(numerator, denominator = 1)
-
58
Rational(numerator, denominator)
-
end
-
end
-
-
# Ruby 1.8.6 introduced new! and deprecated new0.
-
# Ruby 1.9.0 removed new0.
-
# Ruby trunk revision 31668 removed the new! method.
-
# Still support new0 for better performance on older versions of Ruby (new0 indicates
-
# that the rational has already been reduced to its lowest terms).
-
# Fallback to jd with conversion from ajd if new! and new0 are unavailable.
-
1
if DateTime.respond_to? :new!
-
def self.datetime_new!(ajd = 0, of = 0, sg = Date::ITALY)
-
DateTime.new!(ajd, of, sg)
-
end
-
elsif DateTime.respond_to? :new0
-
def self.datetime_new!(ajd = 0, of = 0, sg = Date::ITALY)
-
DateTime.new0(ajd, of, sg)
-
end
-
else
-
1
HALF_DAYS_IN_DAY = rational_new!(1, 2)
-
-
1
def self.datetime_new!(ajd = 0, of = 0, sg = Date::ITALY)
-
# Convert from an Astronomical Julian Day number to a civil Julian Day number.
-
jd = ajd + of + HALF_DAYS_IN_DAY
-
-
# Ruby trunk revision 31862 changed the behaviour of DateTime.jd so that it will no
-
# longer accept a fractional civil Julian Day number if further arguments are specified.
-
# Calculate the hours, minutes and seconds to pass to jd.
-
-
jd_i = jd.to_i
-
jd_i -= 1 if jd < 0
-
hours = (jd - jd_i) * 24
-
hours_i = hours.to_i
-
minutes = (hours - hours_i) * 60
-
minutes_i = minutes.to_i
-
seconds = (minutes - minutes_i) * 60
-
-
DateTime.jd(jd_i, hours_i, minutes_i, seconds, of, sg)
-
end
-
end
-
-
# DateTime in Ruby 1.8.6 doesn't consider times within the 60th second to be
-
# valid. When attempting to specify such a DateTime, subtract the fractional
-
# part and then add it back later
-
1
if Date.respond_to?(:valid_time?) && !Date.valid_time?(0, 0, rational_new!(59001, 1000)) # 0:0:59.001
-
def self.datetime_new(y=-4712, m=1, d=1, h=0, min=0, s=0, of=0, sg=Date::ITALY)
-
if !s.kind_of?(Integer) && s > 59
-
dt = DateTime.new(y, m, d, h, min, 59, of, sg)
-
dt + (s - 59) / 86400
-
else
-
DateTime.new(y, m, d, h, min, s, of, sg)
-
end
-
end
-
else
-
1
def self.datetime_new(y=-4712, m=1, d=1, h=0, min=0, s=0, of=0, sg=Date::ITALY)
-
DateTime.new(y, m, d, h, min, s, of, sg)
-
end
-
end
-
-
# Returns true if Time on the runtime platform supports Times defined
-
# by negative 32-bit timestamps, otherwise false.
-
1
begin
-
1
Time.at(-1)
-
1
Time.at(-2147483648)
-
-
1
def self.time_supports_negative
-
1
true
-
end
-
rescue ArgumentError
-
def self.time_supports_negative
-
false
-
end
-
end
-
-
# Returns true if Time on the runtime platform supports Times defined by
-
# 64-bit timestamps, otherwise false.
-
1
begin
-
1
Time.at(-2147483649)
-
1
Time.at(2147483648)
-
-
1
def self.time_supports_64bit
-
true
-
end
-
rescue RangeError
-
def self.time_supports_64bit
-
false
-
end
-
end
-
-
# Return the result of Time#nsec if it exists, otherwise return the
-
# result of Time#usec * 1000.
-
1
if Time.method_defined?(:nsec)
-
1
def self.time_nsec(time)
-
time.nsec
-
end
-
else
-
def self.time_nsec(time)
-
time.usec * 1000
-
end
-
end
-
-
# Call String#force_encoding if this version of Ruby has encoding support
-
# otherwise treat as a no-op.
-
1
if String.method_defined?(:force_encoding)
-
1
def self.force_encoding(str, encoding)
-
1
str.force_encoding(encoding)
-
end
-
else
-
def self.force_encoding(str, encoding)
-
str
-
end
-
end
-
-
-
# Wrapper for File.open that supports passing hash options for specifying
-
# encodings on Ruby 1.9+. The options are ignored on earlier versions of
-
# Ruby.
-
1
if RUBY_VERSION =~ /\A1\.[0-8]\./
-
def self.open_file(file_name, mode, opts, &block)
-
File.open(file_name, mode, &block)
-
end
-
else
-
1
def self.open_file(file_name, mode, opts, &block)
-
2
File.open(file_name, mode, opts, &block)
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
# Represents information about a country returned by RubyDataSource.
-
#
-
# @private
-
1
class RubyCountryInfo < CountryInfo #:nodoc:
-
# Constructs a new CountryInfo with an ISO 3166 country code, name and
-
# block. The block will be evaluated to obtain the timezones for the
-
# country when the zones are first needed.
-
1
def initialize(code, name, &block)
-
super(code, name)
-
@block = block
-
@zones = nil
-
@zone_identifiers = nil
-
end
-
-
# Returns a frozen array of all the zone identifiers for the country. These
-
# are in the order they were added using the timezone method.
-
1
def zone_identifiers
-
# Thread-safety: It is possible that the value of @zone_identifiers may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @zone_identifiers is only
-
# calculated once.
-
-
unless @zone_identifiers
-
@zone_identifiers = zones.collect {|zone| zone.identifier}.freeze
-
end
-
-
@zone_identifiers
-
end
-
-
# Returns a frozen array of all the timezones for the for the country as
-
# CountryTimezone instances. These are in the order they were added using
-
# the timezone method.
-
1
def zones
-
# Thread-safety: It is possible that the value of @zones may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @zones is only
-
# calculated once.
-
-
unless @zones
-
zones = Zones.new
-
@block.call(zones) if @block
-
@block = nil
-
@zones = zones.list.freeze
-
end
-
-
@zones
-
end
-
-
# An instance of the Zones class is passed to the block used to define
-
# timezones.
-
#
-
# @private
-
1
class Zones #:nodoc:
-
1
attr_reader :list
-
-
1
def initialize
-
@list = []
-
end
-
-
# Called by the index data to define a timezone for the country.
-
1
def timezone(identifier, latitude_numerator, latitude_denominator,
-
longitude_numerator, longitude_denominator, description = nil)
-
@list << CountryTimezone.new!(identifier, latitude_numerator,
-
latitude_denominator, longitude_numerator, longitude_denominator,
-
description)
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
# A DataSource that loads data from the set of Ruby modules included in the
-
# TZInfo::Data library (tzinfo-data gem).
-
#
-
# To have TZInfo use this DataSource, call TZInfo::DataSource.set as follows:
-
#
-
# TZInfo::DataSource.set(:ruby)
-
1
class RubyDataSource < DataSource
-
# Base path for require.
-
1
REQUIRE_PATH = File.join('tzinfo', 'data', 'definitions')
-
-
# Whether the timezone index has been loaded yet.
-
1
@@timezone_index_loaded = false
-
-
# Whether the country index has been loaded yet.
-
1
@@country_index_loaded = false
-
-
# Returns a TimezoneInfo instance for a given identifier.
-
# Raises InvalidTimezoneIdentifier if the timezone is not found or the
-
# identifier is invalid.
-
1
def load_timezone_info(identifier)
-
raise InvalidTimezoneIdentifier, 'Invalid identifier' if identifier !~ /^[A-Za-z0-9\+\-_]+(\/[A-Za-z0-9\+\-_]+)*$/
-
-
identifier = identifier.gsub(/-/, '__m__').gsub(/\+/, '__p__')
-
-
# Untaint identifier after it has been reassigned to a new string. We
-
# don't want to modify the original identifier. identifier may also be
-
# frozen and therefore cannot be untainted.
-
identifier.untaint
-
-
identifier = identifier.split('/')
-
begin
-
require_definition(identifier)
-
-
m = Data::Definitions
-
identifier.each {|part|
-
m = m.const_get(part)
-
}
-
-
m.get
-
rescue LoadError, NameError => e
-
raise InvalidTimezoneIdentifier, e.message
-
end
-
end
-
-
# Returns an array of all the available timezone identifiers.
-
1
def timezone_identifiers
-
load_timezone_index
-
Data::Indexes::Timezones.timezones
-
end
-
-
# Returns an array of all the available timezone identifiers for
-
# data timezones (i.e. those that actually contain definitions).
-
1
def data_timezone_identifiers
-
load_timezone_index
-
Data::Indexes::Timezones.data_timezones
-
end
-
-
# Returns an array of all the available timezone identifiers that
-
# are links to other timezones.
-
1
def linked_timezone_identifiers
-
load_timezone_index
-
Data::Indexes::Timezones.linked_timezones
-
end
-
-
# Returns a CountryInfo instance for the given ISO 3166-1 alpha-2
-
# country code. Raises InvalidCountryCode if the country could not be found
-
# or the code is invalid.
-
1
def load_country_info(code)
-
load_country_index
-
info = Data::Indexes::Countries.countries[code]
-
raise InvalidCountryCode, 'Invalid country code' unless info
-
info
-
end
-
-
# Returns an array of all the available ISO 3166-1 alpha-2
-
# country codes.
-
1
def country_codes
-
load_country_index
-
Data::Indexes::Countries.countries.keys.freeze
-
end
-
-
# Returns the name of this DataSource.
-
1
def to_s
-
"Ruby DataSource"
-
end
-
-
1
private
-
-
# Requires a zone definition by its identifier (split on /).
-
1
def require_definition(identifier)
-
require_data(*(['definitions'] + identifier))
-
end
-
-
# Requires an index by its name.
-
1
def self.require_index(name)
-
require_data(*['indexes', name])
-
end
-
-
# Requires a file from tzinfo/data.
-
1
def require_data(*file)
-
self.class.require_data(*file)
-
end
-
-
# Requires a file from tzinfo/data.
-
1
def self.require_data(*file)
-
require File.join('tzinfo', 'data', *file)
-
end
-
-
# Loads in the index of timezones if it hasn't already been loaded.
-
1
def load_timezone_index
-
self.class.load_timezone_index
-
end
-
-
# Loads in the index of timezones if it hasn't already been loaded.
-
1
def self.load_timezone_index
-
unless @@timezone_index_loaded
-
require_index('timezones')
-
@@timezone_index_loaded = true
-
end
-
end
-
-
# Loads in the index of countries if it hasn't already been loaded.
-
1
def load_country_index
-
self.class.load_country_index
-
end
-
-
# Loads in the index of countries if it hasn't already been loaded.
-
1
def self.load_country_index
-
unless @@country_index_loaded
-
require_index('countries')
-
@@country_index_loaded = true
-
end
-
end
-
end
-
end
-
1
require 'date'
-
1
require 'rational' unless defined?(Rational)
-
1
require 'time'
-
-
1
module TZInfo
-
# Used by TZInfo internally to represent either a Time, DateTime or
-
# an Integer timestamp (seconds since 1970-01-01 00:00:00).
-
1
class TimeOrDateTime
-
1
include Comparable
-
-
# Constructs a new TimeOrDateTime. timeOrDateTime can be a Time, DateTime
-
# or Integer. If using a Time or DateTime, any time zone information
-
# is ignored.
-
#
-
# Integer timestamps must be within the range supported by Time on the
-
# platform being used.
-
1
def initialize(timeOrDateTime)
-
@time = nil
-
@datetime = nil
-
@timestamp = nil
-
-
if timeOrDateTime.is_a?(Time)
-
@time = timeOrDateTime
-
-
# Avoid using the slower Rational class unless necessary.
-
nsec = RubyCoreSupport.time_nsec(@time)
-
usec = nsec % 1000 == 0 ? nsec / 1000 : Rational(nsec, 1000)
-
-
@time = Time.utc(@time.year, @time.mon, @time.mday, @time.hour, @time.min, @time.sec, usec) unless @time.utc?
-
@orig = @time
-
elsif timeOrDateTime.is_a?(DateTime)
-
@datetime = timeOrDateTime
-
@datetime = @datetime.new_offset(0) unless @datetime.offset == 0
-
@orig = @datetime
-
else
-
@timestamp = timeOrDateTime.to_i
-
-
if !RubyCoreSupport.time_supports_64bit && (@timestamp > 2147483647 || @timestamp < -2147483648 || (@timestamp < 0 && !RubyCoreSupport.time_supports_negative))
-
raise RangeError, 'Timestamp is outside the supported range of Time on this platform'
-
end
-
-
@orig = @timestamp
-
end
-
end
-
-
# Returns the time as a Time.
-
#
-
# When converting from a DateTime, the result is truncated to microsecond
-
# precision.
-
1
def to_time
-
# Thread-safety: It is possible that the value of @time may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @time is only
-
# calculated once.
-
-
unless @time
-
if @timestamp
-
@time = Time.at(@timestamp).utc
-
else
-
@time = Time.utc(year, mon, mday, hour, min, sec, usec)
-
end
-
end
-
-
@time
-
end
-
-
# Returns the time as a DateTime.
-
#
-
# When converting from a Time, the result is truncated to microsecond
-
# precision.
-
1
def to_datetime
-
# Thread-safety: It is possible that the value of @datetime may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @datetime is only
-
# calculated once.
-
-
unless @datetime
-
# Avoid using Rational unless necessary.
-
u = usec
-
s = u == 0 ? sec : Rational(sec * 1000000 + u, 1000000)
-
@datetime = RubyCoreSupport.datetime_new(year, mon, mday, hour, min, s)
-
end
-
-
@datetime
-
end
-
-
# Returns the time as an integer timestamp.
-
1
def to_i
-
# Thread-safety: It is possible that the value of @timestamp may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @timestamp is only
-
# calculated once.
-
-
unless @timestamp
-
@timestamp = to_time.to_i
-
end
-
-
@timestamp
-
end
-
-
# Returns the time as the original time passed to new.
-
1
def to_orig
-
@orig
-
end
-
-
# Returns a string representation of the TimeOrDateTime.
-
1
def to_s
-
if @orig.is_a?(Time)
-
"Time: #{@orig.to_s}"
-
elsif @orig.is_a?(DateTime)
-
"DateTime: #{@orig.to_s}"
-
else
-
"Timestamp: #{@orig.to_s}"
-
end
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}: #{@orig.inspect}>"
-
end
-
-
# Returns the year.
-
1
def year
-
if @time
-
@time.year
-
elsif @datetime
-
@datetime.year
-
else
-
to_time.year
-
end
-
end
-
-
# Returns the month of the year (1..12).
-
1
def mon
-
if @time
-
@time.mon
-
elsif @datetime
-
@datetime.mon
-
else
-
to_time.mon
-
end
-
end
-
1
alias :month :mon
-
-
# Returns the day of the month (1..n).
-
1
def mday
-
if @time
-
@time.mday
-
elsif @datetime
-
@datetime.mday
-
else
-
to_time.mday
-
end
-
end
-
1
alias :day :mday
-
-
# Returns the hour of the day (0..23).
-
1
def hour
-
if @time
-
@time.hour
-
elsif @datetime
-
@datetime.hour
-
else
-
to_time.hour
-
end
-
end
-
-
# Returns the minute of the hour (0..59).
-
1
def min
-
if @time
-
@time.min
-
elsif @datetime
-
@datetime.min
-
else
-
to_time.min
-
end
-
end
-
-
# Returns the second of the minute (0..60). (60 for a leap second).
-
1
def sec
-
if @time
-
@time.sec
-
elsif @datetime
-
@datetime.sec
-
else
-
to_time.sec
-
end
-
end
-
-
# Returns the number of microseconds for the time.
-
1
def usec
-
if @time
-
@time.usec
-
elsif @datetime
-
# Ruby 1.8 has sec_fraction (of which the documentation says
-
# 'I do NOT recommend you to use this method'). sec_fraction no longer
-
# exists in Ruby 1.9.
-
-
# Calculate the sec_fraction from the day_fraction.
-
((@datetime.day_fraction - OffsetRationals.rational_for_offset(@datetime.hour * 3600 + @datetime.min * 60 + @datetime.sec)) * 86400000000).to_i
-
else
-
0
-
end
-
end
-
-
# Compares this TimeOrDateTime with another Time, DateTime, timestamp
-
# (Integer) or TimeOrDateTime. Returns -1, 0 or +1 depending
-
# whether the receiver is less than, equal to, or greater than
-
# timeOrDateTime.
-
#
-
# Returns nil if the passed in timeOrDateTime is not comparable with
-
# TimeOrDateTime instances.
-
#
-
# Comparisons involving a DateTime will be performed using DateTime#<=>.
-
# Comparisons that don't involve a DateTime, but include a Time will be
-
# performed with Time#<=>. Otherwise comparisons will be performed with
-
# Integer#<=>.
-
1
def <=>(timeOrDateTime)
-
return nil unless timeOrDateTime.is_a?(TimeOrDateTime) ||
-
timeOrDateTime.is_a?(Time) ||
-
timeOrDateTime.is_a?(DateTime) ||
-
timeOrDateTime.respond_to?(:to_i)
-
-
unless timeOrDateTime.is_a?(TimeOrDateTime)
-
timeOrDateTime = TimeOrDateTime.wrap(timeOrDateTime)
-
end
-
-
orig = timeOrDateTime.to_orig
-
-
if @orig.is_a?(DateTime) || orig.is_a?(DateTime)
-
# If either is a DateTime, assume it is there for a reason
-
# (i.e. for its larger range of acceptable values on 32-bit systems).
-
to_datetime <=> timeOrDateTime.to_datetime
-
elsif @orig.is_a?(Time) || orig.is_a?(Time)
-
to_time <=> timeOrDateTime.to_time
-
else
-
to_i <=> timeOrDateTime.to_i
-
end
-
end
-
-
# Adds a number of seconds to the TimeOrDateTime. Returns a new
-
# TimeOrDateTime, preserving what the original constructed type was.
-
# If the original type is a Time and the resulting calculation goes out of
-
# range for Times, then an exception will be raised by the Time class.
-
1
def +(seconds)
-
if seconds == 0
-
self
-
else
-
if @orig.is_a?(DateTime)
-
TimeOrDateTime.new(@orig + OffsetRationals.rational_for_offset(seconds))
-
else
-
# + defined for Time and Integer
-
TimeOrDateTime.new(@orig + seconds)
-
end
-
end
-
end
-
-
# Subtracts a number of seconds from the TimeOrDateTime. Returns a new
-
# TimeOrDateTime, preserving what the original constructed type was.
-
# If the original type is a Time and the resulting calculation goes out of
-
# range for Times, then an exception will be raised by the Time class.
-
1
def -(seconds)
-
self + (-seconds)
-
end
-
-
# Similar to the + operator, but converts to a DateTime based TimeOrDateTime
-
# where the Time or Integer timestamp to go out of the allowed range for a
-
# Time, converts to a DateTime based TimeOrDateTime.
-
#
-
# Note that the range of Time varies based on the platform.
-
1
def add_with_convert(seconds)
-
if seconds == 0
-
self
-
else
-
if @orig.is_a?(DateTime)
-
TimeOrDateTime.new(@orig + OffsetRationals.rational_for_offset(seconds))
-
else
-
# A Time or timestamp.
-
result = to_i + seconds
-
-
if ((result > 2147483647 || result < -2147483648) && !RubyCoreSupport.time_supports_64bit) || (result < 0 && !RubyCoreSupport.time_supports_negative)
-
result = TimeOrDateTime.new(to_datetime + OffsetRationals.rational_for_offset(seconds))
-
else
-
result = TimeOrDateTime.new(@orig + seconds)
-
end
-
end
-
end
-
end
-
-
# Returns true if todt represents the same time and was originally
-
# constructed with the same type (DateTime, Time or timestamp) as this
-
# TimeOrDateTime.
-
1
def eql?(todt)
-
todt.kind_of?(TimeOrDateTime) && to_orig.eql?(todt.to_orig)
-
end
-
-
# Returns a hash of this TimeOrDateTime.
-
1
def hash
-
@orig.hash
-
end
-
-
# If no block is given, returns a TimeOrDateTime wrapping the given
-
# timeOrDateTime. If a block is specified, a TimeOrDateTime is constructed
-
# and passed to the block. The result of the block must be a TimeOrDateTime.
-
#
-
# The result of the block will be converted to the type of the originally
-
# passed in timeOrDateTime and then returned as the result of wrap.
-
#
-
# timeOrDateTime can be a Time, DateTime, timestamp (Integer) or
-
# TimeOrDateTime. If a TimeOrDateTime is passed in, no new TimeOrDateTime
-
# will be constructed and the value passed to wrap will be used when
-
# calling the block.
-
1
def self.wrap(timeOrDateTime)
-
t = timeOrDateTime.is_a?(TimeOrDateTime) ? timeOrDateTime : TimeOrDateTime.new(timeOrDateTime)
-
-
if block_given?
-
t = yield t
-
-
if timeOrDateTime.is_a?(TimeOrDateTime)
-
t
-
elsif timeOrDateTime.is_a?(Time)
-
t.to_time
-
elsif timeOrDateTime.is_a?(DateTime)
-
t.to_datetime
-
else
-
t.to_i
-
end
-
else
-
t
-
end
-
end
-
end
-
end
-
1
require 'date'
-
1
require 'set'
-
1
require 'thread_safe'
-
-
1
module TZInfo
-
# AmbiguousTime is raised to indicates that a specified time in a local
-
# timezone has more than one possible equivalent UTC time. This happens when
-
# transitioning from daylight savings time to standard time where the clocks
-
# are rolled back.
-
#
-
# AmbiguousTime is raised by period_for_local and local_to_utc when using an
-
# ambiguous time and not specifying any means to resolve the ambiguity.
-
1
class AmbiguousTime < StandardError
-
end
-
-
# PeriodNotFound is raised to indicate that no TimezonePeriod matching a given
-
# time could be found.
-
1
class PeriodNotFound < StandardError
-
end
-
-
# Raised by Timezone#get if the identifier given is not valid.
-
1
class InvalidTimezoneIdentifier < StandardError
-
end
-
-
# Raised if an attempt is made to use a timezone created with
-
# Timezone.new(nil).
-
1
class UnknownTimezone < StandardError
-
end
-
-
# Timezone is the base class of all timezones. It provides a factory method,
-
# 'get', to access timezones by identifier. Once a specific Timezone has been
-
# retrieved, DateTimes, Times and timestamps can be converted between the UTC
-
# and the local time for the zone. For example:
-
#
-
# tz = TZInfo::Timezone.get('America/New_York')
-
# puts tz.utc_to_local(DateTime.new(2005,8,29,15,35,0)).to_s
-
# puts tz.local_to_utc(Time.utc(2005,8,29,11,35,0)).to_s
-
# puts tz.utc_to_local(1125315300).to_s
-
#
-
# Each time conversion method returns an object of the same type it was
-
# passed.
-
#
-
# The Timezone class is thread-safe. It is safe to use class and instance
-
# methods of Timezone in concurrently executing threads. Instances of Timezone
-
# can be shared across thread boundaries.
-
1
class Timezone
-
1
include Comparable
-
-
# Cache of loaded zones by identifier to avoid using require if a zone
-
# has already been loaded.
-
#
-
# @!visibility private
-
1
@@loaded_zones = nil
-
-
# Default value of the dst parameter of the local_to_utc and
-
# period_for_local methods.
-
#
-
# @!visibility private
-
1
@@default_dst = nil
-
-
# Sets the default value of the optional dst parameter of the
-
# local_to_utc and period_for_local methods. Can be set to nil, true or
-
# false.
-
#
-
# The value of default_dst defaults to nil if unset.
-
1
def self.default_dst=(value)
-
@@default_dst = value.nil? ? nil : !!value
-
end
-
-
# Gets the default value of the optional dst parameter of the
-
# local_to_utc and period_for_local methods. Can be set to nil, true or
-
# false.
-
1
def self.default_dst
-
@@default_dst
-
end
-
-
# Returns a timezone by its identifier (e.g. "Europe/London",
-
# "America/Chicago" or "UTC").
-
#
-
# Raises InvalidTimezoneIdentifier if the timezone couldn't be found.
-
1
def self.get(identifier)
-
1
instance = @@loaded_zones[identifier]
-
-
1
unless instance
-
# Thread-safety: It is possible that multiple equivalent Timezone
-
# instances could be created here in concurrently executing threads.
-
# The consequences of this are that the data may be loaded more than
-
# once (depending on the data source) and memoized calculations could
-
# be discarded. The performance benefit of ensuring that only a single
-
# instance is created is unlikely to be worth the overhead of only
-
# allowing one Timezone to be loaded at a time.
-
1
info = data_source.load_timezone_info(identifier)
-
1
instance = info.create_timezone
-
1
@@loaded_zones[instance.identifier] = instance
-
end
-
-
1
instance
-
end
-
-
# Returns a proxy for the Timezone with the given identifier. The proxy
-
# will cause the real timezone to be loaded when an attempt is made to
-
# find a period or convert a time. get_proxy will not validate the
-
# identifier. If an invalid identifier is specified, no exception will be
-
# raised until the proxy is used.
-
1
def self.get_proxy(identifier)
-
TimezoneProxy.new(identifier)
-
end
-
-
# If identifier is nil calls super(), otherwise calls get. An identfier
-
# should always be passed in when called externally.
-
1
def self.new(identifier = nil)
-
2
if identifier
-
get(identifier)
-
else
-
2
super()
-
end
-
end
-
-
# Returns an array containing all the available Timezones.
-
#
-
# Returns TimezoneProxy objects to avoid the overhead of loading Timezone
-
# definitions until a conversion is actually required.
-
1
def self.all
-
get_proxies(all_identifiers)
-
end
-
-
# Returns an array containing the identifiers of all the available
-
# Timezones.
-
1
def self.all_identifiers
-
data_source.timezone_identifiers
-
end
-
-
# Returns an array containing all the available Timezones that are based
-
# on data (are not links to other Timezones).
-
#
-
# Returns TimezoneProxy objects to avoid the overhead of loading Timezone
-
# definitions until a conversion is actually required.
-
1
def self.all_data_zones
-
get_proxies(all_data_zone_identifiers)
-
end
-
-
# Returns an array containing the identifiers of all the available
-
# Timezones that are based on data (are not links to other Timezones)..
-
1
def self.all_data_zone_identifiers
-
data_source.data_timezone_identifiers
-
end
-
-
# Returns an array containing all the available Timezones that are links
-
# to other Timezones.
-
#
-
# Returns TimezoneProxy objects to avoid the overhead of loading Timezone
-
# definitions until a conversion is actually required.
-
1
def self.all_linked_zones
-
get_proxies(all_linked_zone_identifiers)
-
end
-
-
# Returns an array containing the identifiers of all the available
-
# Timezones that are links to other Timezones.
-
1
def self.all_linked_zone_identifiers
-
data_source.linked_timezone_identifiers
-
end
-
-
# Returns all the Timezones defined for all Countries. This is not the
-
# complete set of Timezones as some are not country specific (e.g.
-
# 'Etc/GMT').
-
#
-
# Returns TimezoneProxy objects to avoid the overhead of loading Timezone
-
# definitions until a conversion is actually required.
-
1
def self.all_country_zones
-
Country.all_codes.inject([]) do |zones,country|
-
zones += Country.get(country).zones
-
end.uniq
-
end
-
-
# Returns all the zone identifiers defined for all Countries. This is not the
-
# complete set of zone identifiers as some are not country specific (e.g.
-
# 'Etc/GMT'). You can obtain a Timezone instance for a given identifier
-
# with the get method.
-
1
def self.all_country_zone_identifiers
-
Country.all_codes.inject([]) do |zones,country|
-
zones += Country.get(country).zone_identifiers
-
end.uniq
-
end
-
-
# Returns all US Timezone instances. A shortcut for
-
# TZInfo::Country.get('US').zones.
-
#
-
# Returns TimezoneProxy objects to avoid the overhead of loading Timezone
-
# definitions until a conversion is actually required.
-
1
def self.us_zones
-
Country.get('US').zones
-
end
-
-
# Returns all US zone identifiers. A shortcut for
-
# TZInfo::Country.get('US').zone_identifiers.
-
1
def self.us_zone_identifiers
-
Country.get('US').zone_identifiers
-
end
-
-
# The identifier of the timezone, e.g. "Europe/Paris".
-
1
def identifier
-
raise_unknown_timezone
-
end
-
-
# An alias for identifier.
-
1
def name
-
# Don't use alias, as identifier gets overridden.
-
identifier
-
end
-
-
# Returns a friendlier version of the identifier.
-
1
def to_s
-
friendly_identifier
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}: #{identifier}>"
-
end
-
-
# Returns a friendlier version of the identifier. Set skip_first_part to
-
# omit the first part of the identifier (typically a region name) where
-
# there is more than one part.
-
#
-
# For example:
-
#
-
# Timezone.get('Europe/Paris').friendly_identifier(false) #=> "Europe - Paris"
-
# Timezone.get('Europe/Paris').friendly_identifier(true) #=> "Paris"
-
# Timezone.get('America/Indiana/Knox').friendly_identifier(false) #=> "America - Knox, Indiana"
-
# Timezone.get('America/Indiana/Knox').friendly_identifier(true) #=> "Knox, Indiana"
-
1
def friendly_identifier(skip_first_part = false)
-
parts = identifier.split('/')
-
if parts.empty?
-
# shouldn't happen
-
identifier
-
elsif parts.length == 1
-
parts[0]
-
else
-
if skip_first_part
-
result = ''
-
else
-
result = parts[0] + ' - '
-
end
-
-
parts[1, parts.length - 1].reverse_each {|part|
-
part.gsub!(/_/, ' ')
-
-
if part.index(/[a-z]/)
-
# Missing a space if a lower case followed by an upper case and the
-
# name isn't McXxxx.
-
part.gsub!(/([^M][a-z])([A-Z])/, '\1 \2')
-
part.gsub!(/([M][a-bd-z])([A-Z])/, '\1 \2')
-
-
# Missing an apostrophe if two consecutive upper case characters.
-
part.gsub!(/([A-Z])([A-Z])/, '\1\'\2')
-
end
-
-
result << part
-
result << ', '
-
}
-
-
result.slice!(result.length - 2, 2)
-
result
-
end
-
end
-
-
# Returns the TimezonePeriod for the given UTC time. utc can either be
-
# a DateTime, Time or integer timestamp (Time.to_i). Any timezone
-
# information in utc is ignored (it is treated as a UTC time).
-
1
def period_for_utc(utc)
-
raise_unknown_timezone
-
end
-
-
# Returns the set of TimezonePeriod instances that are valid for the given
-
# local time as an array. If you just want a single period, use
-
# period_for_local instead and specify how ambiguities should be resolved.
-
# Returns an empty array if no periods are found for the given time.
-
1
def periods_for_local(local)
-
raise_unknown_timezone
-
end
-
-
# Returns an Array of TimezoneTransition instances representing the times
-
# where the UTC offset of the timezone changes.
-
#
-
# Transitions are returned up to a given date and time up to a given date
-
# and time, specified in UTC (utc_to).
-
#
-
# A from date and time may also be supplied using the utc_from parameter
-
# (also specified in UTC). If utc_from is not nil, only transitions from
-
# that date and time onwards will be returned.
-
#
-
# Comparisons with utc_to are exclusive. Comparisons with utc_from are
-
# inclusive. If a transition falls precisely on utc_to, it will be excluded.
-
# If a transition falls on utc_from, it will be included.
-
#
-
# Transitions returned are ordered by when they occur, from earliest to
-
# latest.
-
#
-
# utc_to and utc_from can be specified using either DateTime, Time or
-
# integer timestamps (Time.to_i).
-
#
-
# If utc_from is specified and utc_to is not greater than utc_from, then
-
# transitions_up_to raises an ArgumentError exception.
-
1
def transitions_up_to(utc_to, utc_from = nil)
-
raise_unknown_timezone
-
end
-
-
# Returns the canonical Timezone instance for this Timezone.
-
#
-
# The IANA Time Zone database contains two types of definition: Zones and
-
# Links. Zones are defined by rules that set out when transitions occur.
-
# Links are just references to fully defined Zone, creating an alias for
-
# that Zone.
-
#
-
# Links are commonly used where a time zone has been renamed in a
-
# release of the Time Zone database. For example, the Zone US/Eastern was
-
# renamed as America/New_York. A US/Eastern Link was added in its place,
-
# linking to (and creating an alias for) for America/New_York.
-
#
-
# Links are also used for time zones that are currently identical to a full
-
# Zone, but that are administered seperately. For example, Europe/Vatican is
-
# a Link to (and alias for) Europe/Rome.
-
#
-
# For a full Zone, canonical_zone returns self.
-
#
-
# For a Link, canonical_zone returns a Timezone instance representing the
-
# full Zone that the link targets.
-
#
-
# TZInfo can be used with different data sources (see the documentation for
-
# TZInfo::DataSource). Please note that some DataSource implementations may
-
# not support distinguishing between full Zones and Links and will treat all
-
# time zones as full Zones. In this case, the canonical_zone will always
-
# return self.
-
#
-
# There are two built-in DataSource implementations. RubyDataSource (which
-
# will be used if the tzinfo-data gem is available) supports Link zones.
-
# ZoneinfoDataSource returns Link zones as if they were full Zones. If the
-
# canonical_zone or canonical_identifier methods are required, the
-
# tzinfo-data gem should be installed.
-
#
-
# The TZInfo::DataSource.get method can be used to check which DataSource
-
# implementation is being used.
-
1
def canonical_zone
-
raise_unknown_timezone
-
end
-
-
# Returns the TimezonePeriod for the given local time. local can either be
-
# a DateTime, Time or integer timestamp (Time.to_i). Any timezone
-
# information in local is ignored (it is treated as a time in the current
-
# timezone).
-
#
-
# Warning: There are local times that have no equivalent UTC times (e.g.
-
# in the transition from standard time to daylight savings time). There are
-
# also local times that have more than one UTC equivalent (e.g. in the
-
# transition from daylight savings time to standard time).
-
#
-
# In the first case (no equivalent UTC time), a PeriodNotFound exception
-
# will be raised.
-
#
-
# In the second case (more than one equivalent UTC time), an AmbiguousTime
-
# exception will be raised unless the optional dst parameter or block
-
# handles the ambiguity.
-
#
-
# If the ambiguity is due to a transition from daylight savings time to
-
# standard time, the dst parameter can be used to select whether the
-
# daylight savings time or local time is used. For example,
-
#
-
# Timezone.get('America/New_York').period_for_local(DateTime.new(2004,10,31,1,30,0))
-
#
-
# would raise an AmbiguousTime exception.
-
#
-
# Specifying dst=true would the daylight savings period from April to
-
# October 2004. Specifying dst=false would return the standard period
-
# from October 2004 to April 2005.
-
#
-
# If the dst parameter does not resolve the ambiguity, and a block is
-
# specified, it is called. The block must take a single parameter - an
-
# array of the periods that need to be resolved. The block can select and
-
# return a single period or return nil or an empty array
-
# to cause an AmbiguousTime exception to be raised.
-
#
-
# The default value of the dst parameter can be specified by setting
-
# Timezone.default_dst. If default_dst is not set, or is set to nil, then
-
# an AmbiguousTime exception will be raised in ambiguous situations unless
-
# a block is given to resolve the ambiguity.
-
1
def period_for_local(local, dst = Timezone.default_dst)
-
results = periods_for_local(local)
-
-
if results.empty?
-
raise PeriodNotFound
-
elsif results.size < 2
-
results.first
-
else
-
# ambiguous result try to resolve
-
-
if !dst.nil?
-
matches = results.find_all {|period| period.dst? == dst}
-
results = matches if !matches.empty?
-
end
-
-
if results.size < 2
-
results.first
-
else
-
# still ambiguous, try the block
-
-
if block_given?
-
results = yield results
-
end
-
-
if results.is_a?(TimezonePeriod)
-
results
-
elsif results && results.size == 1
-
results.first
-
else
-
raise AmbiguousTime, "#{local} is an ambiguous local time."
-
end
-
end
-
end
-
end
-
-
# Converts a time in UTC to the local timezone. utc can either be
-
# a DateTime, Time or timestamp (Time.to_i). The returned time has the same
-
# type as utc. Any timezone information in utc is ignored (it is treated as
-
# a UTC time).
-
1
def utc_to_local(utc)
-
TimeOrDateTime.wrap(utc) {|wrapped|
-
period_for_utc(wrapped).to_local(wrapped)
-
}
-
end
-
-
# Converts a time in the local timezone to UTC. local can either be
-
# a DateTime, Time or timestamp (Time.to_i). The returned time has the same
-
# type as local. Any timezone information in local is ignored (it is treated
-
# as a local time).
-
#
-
# Warning: There are local times that have no equivalent UTC times (e.g.
-
# in the transition from standard time to daylight savings time). There are
-
# also local times that have more than one UTC equivalent (e.g. in the
-
# transition from daylight savings time to standard time).
-
#
-
# In the first case (no equivalent UTC time), a PeriodNotFound exception
-
# will be raised.
-
#
-
# In the second case (more than one equivalent UTC time), an AmbiguousTime
-
# exception will be raised unless the optional dst parameter or block
-
# handles the ambiguity.
-
#
-
# If the ambiguity is due to a transition from daylight savings time to
-
# standard time, the dst parameter can be used to select whether the
-
# daylight savings time or local time is used. For example,
-
#
-
# Timezone.get('America/New_York').local_to_utc(DateTime.new(2004,10,31,1,30,0))
-
#
-
# would raise an AmbiguousTime exception.
-
#
-
# Specifying dst=true would return 2004-10-31 5:30:00. Specifying dst=false
-
# would return 2004-10-31 6:30:00.
-
#
-
# If the dst parameter does not resolve the ambiguity, and a block is
-
# specified, it is called. The block must take a single parameter - an
-
# array of the periods that need to be resolved. The block can return a
-
# single period to use to convert the time or return nil or an empty array
-
# to cause an AmbiguousTime exception to be raised.
-
#
-
# The default value of the dst parameter can be specified by setting
-
# Timezone.default_dst. If default_dst is not set, or is set to nil, then
-
# an AmbiguousTime exception will be raised in ambiguous situations unless
-
# a block is given to resolve the ambiguity.
-
1
def local_to_utc(local, dst = Timezone.default_dst)
-
TimeOrDateTime.wrap(local) {|wrapped|
-
if block_given?
-
period = period_for_local(wrapped, dst) {|periods| yield periods }
-
else
-
period = period_for_local(wrapped, dst)
-
end
-
-
period.to_utc(wrapped)
-
}
-
end
-
-
# Returns information about offsets used by the Timezone up to a given
-
# date and time, specified using UTC (utc_to). The information is returned
-
# as an Array of TimezoneOffset instances.
-
#
-
# A from date and time may also be supplied using the utc_from parameter
-
# (also specified in UTC). If utc_from is not nil, only offsets used from
-
# that date and time forward will be returned.
-
#
-
# Comparisons with utc_to are exclusive. Comparisons with utc_from are
-
# inclusive.
-
#
-
# Offsets may be returned in any order.
-
#
-
# utc_to and utc_from can be specified using either DateTime, Time or
-
# integer timestamps (Time.to_i).
-
#
-
# If utc_from is specified and utc_to is not greater than utc_from, then
-
# offsets_up_to raises an ArgumentError exception.
-
1
def offsets_up_to(utc_to, utc_from = nil)
-
utc_to = TimeOrDateTime.wrap(utc_to)
-
transitions = transitions_up_to(utc_to, utc_from)
-
-
if transitions.empty?
-
# No transitions in the range, find the period that covers it.
-
-
if utc_from
-
# Use the from date as it is inclusive.
-
period = period_for_utc(utc_from)
-
else
-
# utc_to is exclusive, so this can't be used with period_for_utc.
-
# However, any time earlier than utc_to can be used.
-
-
# Subtract 1 hour (since this is one of the cached OffsetRationals).
-
# Use add_with_convert so that conversion to DateTime is performed if
-
# required.
-
period = period_for_utc(utc_to.add_with_convert(-3600))
-
end
-
-
[period.offset]
-
else
-
result = Set.new
-
-
first = transitions.first
-
result << first.previous_offset unless utc_from && first.at == utc_from
-
-
transitions.each do |t|
-
result << t.offset
-
end
-
-
result.to_a
-
end
-
end
-
-
# Returns the canonical identifier for this Timezone.
-
#
-
# This is a shortcut for calling canonical_zone.identifier. Please refer
-
# to the canonical_zone documentation for further information.
-
1
def canonical_identifier
-
canonical_zone.identifier
-
end
-
-
# Returns the current time in the timezone as a Time.
-
1
def now
-
utc_to_local(Time.now.utc)
-
end
-
-
# Returns the TimezonePeriod for the current time.
-
1
def current_period
-
1
period_for_utc(Time.now.utc)
-
end
-
-
# Returns the current Time and TimezonePeriod as an array. The first element
-
# is the time, the second element is the period.
-
1
def current_period_and_time
-
utc = Time.now.utc
-
period = period_for_utc(utc)
-
[period.to_local(utc), period]
-
end
-
-
1
alias :current_time_and_period :current_period_and_time
-
-
# Converts a time in UTC to local time and returns it as a string
-
# according to the given format. The formatting is identical to
-
# Time.strftime and DateTime.strftime, except %Z is replaced with the
-
# timezone abbreviation for the specified time (for example, EST or EDT).
-
1
def strftime(format, utc = Time.now.utc)
-
period = period_for_utc(utc)
-
local = period.to_local(utc)
-
local = Time.at(local).utc unless local.kind_of?(Time) || local.kind_of?(DateTime)
-
abbreviation = period.abbreviation.to_s.gsub(/%/, '%%')
-
-
format = format.gsub(/(.?)%Z/) do
-
if $1 == '%'
-
# return %%Z so the real strftime treats it as a literal %Z too
-
'%%Z'
-
else
-
"#$1#{abbreviation}"
-
end
-
end
-
-
local.strftime(format)
-
end
-
-
# Compares two Timezones based on their identifier. Returns -1 if tz is less
-
# than self, 0 if tz is equal to self and +1 if tz is greater than self.
-
#
-
# Returns nil if tz is not comparable with Timezone instances.
-
1
def <=>(tz)
-
return nil unless tz.is_a?(Timezone)
-
identifier <=> tz.identifier
-
end
-
-
# Returns true if and only if the identifier of tz is equal to the
-
# identifier of this Timezone.
-
1
def eql?(tz)
-
self == tz
-
end
-
-
# Returns a hash of this Timezone.
-
1
def hash
-
identifier.hash
-
end
-
-
# Dumps this Timezone for marshalling.
-
1
def _dump(limit)
-
identifier
-
end
-
-
# Loads a marshalled Timezone.
-
1
def self._load(data)
-
Timezone.get(data)
-
end
-
-
1
private
-
# Initializes @@loaded_zones.
-
1
def self.init_loaded_zones
-
1
@@loaded_zones = ThreadSafe::Cache.new
-
end
-
1
init_loaded_zones
-
-
# Returns an array of proxies corresponding to the given array of
-
# identifiers.
-
1
def self.get_proxies(identifiers)
-
identifiers.collect {|identifier| get_proxy(identifier)}
-
end
-
-
# Returns the current DataSource.
-
1
def self.data_source
-
1
DataSource.get
-
end
-
-
# Raises an UnknownTimezone exception.
-
1
def raise_unknown_timezone
-
raise UnknownTimezone, 'TZInfo::Timezone constructed directly'
-
end
-
end
-
end
-
1
module TZInfo
-
-
# TimezoneDefinition is included into Timezone definition modules.
-
# TimezoneDefinition provides the methods for defining timezones.
-
#
-
# @private
-
1
module TimezoneDefinition #:nodoc:
-
# Add class methods to the includee.
-
1
def self.append_features(base)
-
super
-
base.extend(ClassMethods)
-
end
-
-
# Class methods for inclusion.
-
#
-
# @private
-
1
module ClassMethods #:nodoc:
-
# Returns and yields a TransitionDataTimezoneInfo object to define a
-
# timezone.
-
1
def timezone(identifier)
-
yield @timezone = TransitionDataTimezoneInfo.new(identifier)
-
end
-
-
# Defines a linked timezone.
-
1
def linked_timezone(identifier, link_to_identifier)
-
@timezone = LinkedTimezoneInfo.new(identifier, link_to_identifier)
-
end
-
-
# Returns the last TimezoneInfo to be defined with timezone or
-
# linked_timezone.
-
1
def get
-
@timezone
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
# The timezone index file includes TimezoneIndexDefinition which provides
-
# methods used to define timezones in the index.
-
#
-
# @private
-
1
module TimezoneIndexDefinition #:nodoc:
-
# Add class methods to the includee and initialize class instance variables.
-
1
def self.append_features(base)
-
super
-
base.extend(ClassMethods)
-
base.instance_eval do
-
@timezones = []
-
@data_timezones = []
-
@linked_timezones = []
-
end
-
end
-
-
# Class methods for inclusion.
-
#
-
# @private
-
1
module ClassMethods #:nodoc:
-
# Defines a timezone based on data.
-
1
def timezone(identifier)
-
@timezones << identifier
-
@data_timezones << identifier
-
end
-
-
# Defines a timezone which is a link to another timezone.
-
1
def linked_timezone(identifier)
-
@timezones << identifier
-
@linked_timezones << identifier
-
end
-
-
# Returns a frozen array containing the identifiers of all the timezones.
-
# Identifiers appear in the order they were defined in the index.
-
1
def timezones
-
@timezones.freeze
-
end
-
-
# Returns a frozen array containing the identifiers of all data timezones.
-
# Identifiers appear in the order they were defined in the index.
-
1
def data_timezones
-
@data_timezones.freeze
-
end
-
-
# Returns a frozen array containing the identifiers of all linked
-
# timezones. Identifiers appear in the order they were defined in
-
# the index.
-
1
def linked_timezones
-
@linked_timezones.freeze
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
# Represents a timezone defined by a data source.
-
1
class TimezoneInfo
-
-
# The timezone identifier.
-
1
attr_reader :identifier
-
-
# Constructs a new TimezoneInfo with an identifier.
-
1
def initialize(identifier)
-
1
@identifier = identifier
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}: #@identifier>"
-
end
-
-
# Constructs a Timezone instance for the timezone represented by this
-
# TimezoneInfo.
-
1
def create_timezone
-
raise_not_implemented('create_timezone')
-
end
-
-
1
private
-
-
1
def raise_not_implemented(method_name)
-
raise NotImplementedError, "Subclasses must override #{method_name}"
-
end
-
end
-
end
-
1
module TZInfo
-
# Represents an offset defined in a Timezone data file.
-
1
class TimezoneOffset
-
# The base offset of the timezone from UTC in seconds.
-
1
attr_reader :utc_offset
-
-
# The offset from standard time for the zone in seconds (i.e. non-zero if
-
# daylight savings is being observed).
-
1
attr_reader :std_offset
-
-
# The total offset of this observance from UTC in seconds
-
# (utc_offset + std_offset).
-
1
attr_reader :utc_total_offset
-
-
# The abbreviation that identifies this observance, e.g. "GMT"
-
# (Greenwich Mean Time) or "BST" (British Summer Time) for "Europe/London". The returned identifier is a
-
# symbol.
-
1
attr_reader :abbreviation
-
-
# Constructs a new TimezoneOffset. utc_offset and std_offset are specified
-
# in seconds.
-
1
def initialize(utc_offset, std_offset, abbreviation)
-
1
@utc_offset = utc_offset
-
1
@std_offset = std_offset
-
1
@abbreviation = abbreviation
-
-
1
@utc_total_offset = @utc_offset + @std_offset
-
end
-
-
# True if std_offset is non-zero.
-
1
def dst?
-
@std_offset != 0
-
end
-
-
# Converts a UTC Time, DateTime or integer timestamp to local time, based on
-
# the offset of this period.
-
1
def to_local(utc)
-
TimeOrDateTime.wrap(utc) {|wrapped|
-
wrapped + @utc_total_offset
-
}
-
end
-
-
# Converts a local Time, DateTime or integer timestamp to UTC, based on the
-
# offset of this period.
-
1
def to_utc(local)
-
TimeOrDateTime.wrap(local) {|wrapped|
-
wrapped - @utc_total_offset
-
}
-
end
-
-
# Returns true if and only if toi has the same utc_offset, std_offset
-
# and abbreviation as this TimezoneOffset.
-
1
def ==(toi)
-
toi.kind_of?(TimezoneOffset) &&
-
utc_offset == toi.utc_offset && std_offset == toi.std_offset && abbreviation == toi.abbreviation
-
end
-
-
# Returns true if and only if toi has the same utc_offset, std_offset
-
# and abbreviation as this TimezoneOffset.
-
1
def eql?(toi)
-
self == toi
-
end
-
-
# Returns a hash of this TimezoneOffset.
-
1
def hash
-
utc_offset.hash ^ std_offset.hash ^ abbreviation.hash
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}: #@utc_offset,#@std_offset,#@abbreviation>"
-
end
-
end
-
end
-
1
module TZInfo
-
# A period of time in a timezone where the same offset from UTC applies.
-
#
-
# All the methods that take times accept instances of Time or DateTime as well
-
# as Integer timestamps.
-
1
class TimezonePeriod
-
# The TimezoneTransition that defines the start of this TimezonePeriod
-
# (may be nil if unbounded).
-
1
attr_reader :start_transition
-
-
# The TimezoneTransition that defines the end of this TimezonePeriod
-
# (may be nil if unbounded).
-
1
attr_reader :end_transition
-
-
# The TimezoneOffset for this period.
-
1
attr_reader :offset
-
-
# Initializes a new TimezonePeriod.
-
#
-
# TimezonePeriod instances should not normally be constructed manually.
-
1
def initialize(start_transition, end_transition, offset = nil)
-
1
@start_transition = start_transition
-
1
@end_transition = end_transition
-
-
1
if offset
-
1
raise ArgumentError, 'Offset specified with transitions' if @start_transition || @end_transition
-
1
@offset = offset
-
else
-
if @start_transition
-
@offset = @start_transition.offset
-
elsif @end_transition
-
@offset = @end_transition.previous_offset
-
else
-
raise ArgumentError, 'No offset specified and no transitions to determine it from'
-
end
-
end
-
-
1
@utc_total_offset_rational = nil
-
end
-
-
# Base offset of the timezone from UTC (seconds).
-
1
def utc_offset
-
1
@offset.utc_offset
-
end
-
-
# Offset from the local time where daylight savings is in effect (seconds).
-
# E.g.: utc_offset could be -5 hours. Normally, std_offset would be 0.
-
# During daylight savings, std_offset would typically become +1 hours.
-
1
def std_offset
-
@offset.std_offset
-
end
-
-
# The identifier of this period, e.g. "GMT" (Greenwich Mean Time) or "BST"
-
# (British Summer Time) for "Europe/London". The returned identifier is a
-
# symbol.
-
1
def abbreviation
-
@offset.abbreviation
-
end
-
1
alias :zone_identifier :abbreviation
-
-
# Total offset from UTC (seconds). Equal to utc_offset + std_offset.
-
1
def utc_total_offset
-
@offset.utc_total_offset
-
end
-
-
# Total offset from UTC (days). Result is a Rational.
-
1
def utc_total_offset_rational
-
# Thread-safety: It is possible that the value of
-
# @utc_total_offset_rational may be calculated multiple times in
-
# concurrently executing threads. It is not worth the overhead of locking
-
# to ensure that @zone_identifiers is only calculated once.
-
-
unless @utc_total_offset_rational
-
@utc_total_offset_rational = OffsetRationals.rational_for_offset(utc_total_offset)
-
end
-
@utc_total_offset_rational
-
end
-
-
# The start time of the period in UTC as a DateTime. May be nil if unbounded.
-
1
def utc_start
-
@start_transition ? @start_transition.at.to_datetime : nil
-
end
-
-
# The start time of the period in UTC as a Time. May be nil if unbounded.
-
1
def utc_start_time
-
@start_transition ? @start_transition.at.to_time : nil
-
end
-
-
# The end time of the period in UTC as a DateTime. May be nil if unbounded.
-
1
def utc_end
-
@end_transition ? @end_transition.at.to_datetime : nil
-
end
-
-
# The end time of the period in UTC as a Time. May be nil if unbounded.
-
1
def utc_end_time
-
@end_transition ? @end_transition.at.to_time : nil
-
end
-
-
# The start time of the period in local time as a DateTime. May be nil if
-
# unbounded.
-
1
def local_start
-
@start_transition ? @start_transition.local_start_at.to_datetime : nil
-
end
-
-
# The start time of the period in local time as a Time. May be nil if
-
# unbounded.
-
1
def local_start_time
-
@start_transition ? @start_transition.local_start_at.to_time : nil
-
end
-
-
# The end time of the period in local time as a DateTime. May be nil if
-
# unbounded.
-
1
def local_end
-
@end_transition ? @end_transition.local_end_at.to_datetime : nil
-
end
-
-
# The end time of the period in local time as a Time. May be nil if
-
# unbounded.
-
1
def local_end_time
-
@end_transition ? @end_transition.local_end_at.to_time : nil
-
end
-
-
# true if daylight savings is in effect for this period; otherwise false.
-
1
def dst?
-
@offset.dst?
-
end
-
-
# true if this period is valid for the given UTC DateTime; otherwise false.
-
1
def valid_for_utc?(utc)
-
utc_after_start?(utc) && utc_before_end?(utc)
-
end
-
-
# true if the given UTC DateTime is after the start of the period
-
# (inclusive); otherwise false.
-
1
def utc_after_start?(utc)
-
!@start_transition || @start_transition.at <= utc
-
end
-
-
# true if the given UTC DateTime is before the end of the period
-
# (exclusive); otherwise false.
-
1
def utc_before_end?(utc)
-
!@end_transition || @end_transition.at > utc
-
end
-
-
# true if this period is valid for the given local DateTime; otherwise false.
-
1
def valid_for_local?(local)
-
local_after_start?(local) && local_before_end?(local)
-
end
-
-
# true if the given local DateTime is after the start of the period
-
# (inclusive); otherwise false.
-
1
def local_after_start?(local)
-
!@start_transition || @start_transition.local_start_at <= local
-
end
-
-
# true if the given local DateTime is before the end of the period
-
# (exclusive); otherwise false.
-
1
def local_before_end?(local)
-
!@end_transition || @end_transition.local_end_at > local
-
end
-
-
# Converts a UTC DateTime to local time based on the offset of this period.
-
1
def to_local(utc)
-
@offset.to_local(utc)
-
end
-
-
# Converts a local DateTime to UTC based on the offset of this period.
-
1
def to_utc(local)
-
@offset.to_utc(local)
-
end
-
-
# Returns true if this TimezonePeriod is equal to p. This compares the
-
# start_transition, end_transition and offset using ==.
-
1
def ==(p)
-
p.kind_of?(TimezonePeriod) &&
-
start_transition == p.start_transition &&
-
end_transition == p.end_transition &&
-
offset == p.offset
-
end
-
-
# Returns true if this TimezonePeriods is equal to p. This compares the
-
# start_transition, end_transition and offset using eql?
-
1
def eql?(p)
-
p.kind_of?(TimezonePeriod) &&
-
start_transition.eql?(p.start_transition) &&
-
end_transition.eql?(p.end_transition) &&
-
offset.eql?(p.offset)
-
end
-
-
# Returns a hash of this TimezonePeriod.
-
1
def hash
-
result = @start_transition.hash ^ @end_transition.hash
-
result ^= @offset.hash unless @start_transition || @end_transition
-
result
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
result = "#<#{self.class}: #{@start_transition.inspect},#{@end_transition.inspect}"
-
result << ",#{@offset.inspect}>" unless @start_transition || @end_transition
-
result + '>'
-
end
-
end
-
end
-
1
module TZInfo
-
-
# A proxy class representing a timezone with a given identifier. TimezoneProxy
-
# inherits from Timezone and can be treated like any Timezone loaded with
-
# Timezone.get.
-
#
-
# The first time an attempt is made to access the data for the timezone, the
-
# real Timezone is loaded. If the proxy's identifier was not valid, then an
-
# exception will be raised at this point.
-
1
class TimezoneProxy < Timezone
-
# Construct a new TimezoneProxy for the given identifier. The identifier
-
# is not checked when constructing the proxy. It will be validated on the
-
# when the real Timezone is loaded.
-
1
def self.new(identifier)
-
# Need to override new to undo the behaviour introduced in Timezone#new.
-
1
tzp = super()
-
1
tzp.send(:setup, identifier)
-
1
tzp
-
end
-
-
# The identifier of the timezone, e.g. "Europe/Paris".
-
1
def identifier
-
@real_timezone ? @real_timezone.identifier : @identifier
-
end
-
-
# Returns the TimezonePeriod for the given UTC time. utc can either be
-
# a DateTime, Time or integer timestamp (Time.to_i). Any timezone
-
# information in utc is ignored (it is treated as a UTC time).
-
1
def period_for_utc(utc)
-
1
real_timezone.period_for_utc(utc)
-
end
-
-
# Returns the set of TimezonePeriod instances that are valid for the given
-
# local time as an array. If you just want a single period, use
-
# period_for_local instead and specify how abiguities should be resolved.
-
# Returns an empty array if no periods are found for the given time.
-
1
def periods_for_local(local)
-
real_timezone.periods_for_local(local)
-
end
-
-
# Returns the canonical zone for this Timezone.
-
1
def canonical_zone
-
real_timezone.canonical_zone
-
end
-
-
# Dumps this TimezoneProxy for marshalling.
-
1
def _dump(limit)
-
identifier
-
end
-
-
# Loads a marshalled TimezoneProxy.
-
1
def self._load(data)
-
TimezoneProxy.new(data)
-
end
-
-
1
private
-
1
def setup(identifier)
-
1
@identifier = identifier
-
1
@real_timezone = nil
-
end
-
-
1
def real_timezone
-
# Thread-safety: It is possible that the value of @real_timezone may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @real_timezone is only
-
# calculated once.
-
1
@real_timezone ||= Timezone.get(@identifier)
-
end
-
end
-
end
-
1
module TZInfo
-
# Represents a transition from one timezone offset to another at a particular
-
# date and time.
-
1
class TimezoneTransition
-
# The offset this transition changes to (a TimezoneOffset instance).
-
1
attr_reader :offset
-
-
# The offset this transition changes from (a TimezoneOffset instance).
-
1
attr_reader :previous_offset
-
-
# Initializes a new TimezoneTransition.
-
#
-
# TimezoneTransition instances should not normally be constructed manually.
-
1
def initialize(offset, previous_offset)
-
@offset = offset
-
@previous_offset = previous_offset
-
@local_end_at = nil
-
@local_start_at = nil
-
end
-
-
# A TimeOrDateTime instance representing the UTC time when this transition
-
# occurs.
-
1
def at
-
raise_not_implemented('at')
-
end
-
-
# The UTC time when this transition occurs, returned as a DateTime instance.
-
1
def datetime
-
at.to_datetime
-
end
-
-
# The UTC time when this transition occurs, returned as a Time instance.
-
1
def time
-
at.to_time
-
end
-
-
# A TimeOrDateTime instance representing the local time when this transition
-
# causes the previous observance to end (calculated from at using
-
# previous_offset).
-
1
def local_end_at
-
# Thread-safety: It is possible that the value of @local_end_at may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @local_end_at is only
-
# calculated once.
-
-
@local_end_at = at.add_with_convert(@previous_offset.utc_total_offset) unless @local_end_at
-
@local_end_at
-
end
-
-
# The local time when this transition causes the previous observance to end,
-
# returned as a DateTime instance.
-
1
def local_end
-
local_end_at.to_datetime
-
end
-
-
# The local time when this transition causes the previous observance to end,
-
# returned as a Time instance.
-
1
def local_end_time
-
local_end_at.to_time
-
end
-
-
# A TimeOrDateTime instance representing the local time when this transition
-
# causes the next observance to start (calculated from at using offset).
-
1
def local_start_at
-
# Thread-safety: It is possible that the value of @local_start_at may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @local_start_at is only
-
# calculated once.
-
-
@local_start_at = at.add_with_convert(@offset.utc_total_offset) unless @local_start_at
-
@local_start_at
-
end
-
-
# The local time when this transition causes the next observance to start,
-
# returned as a DateTime instance.
-
1
def local_start
-
local_start_at.to_datetime
-
end
-
-
# The local time when this transition causes the next observance to start,
-
# returned as a Time instance.
-
1
def local_start_time
-
local_start_at.to_time
-
end
-
-
# Returns true if this TimezoneTransition is equal to the given
-
# TimezoneTransition. Two TimezoneTransition instances are
-
# considered to be equal by == if offset, previous_offset and at are all
-
# equal.
-
1
def ==(tti)
-
tti.kind_of?(TimezoneTransition) &&
-
offset == tti.offset && previous_offset == tti.previous_offset && at == tti.at
-
end
-
-
# Returns true if this TimezoneTransition is equal to the given
-
# TimezoneTransition. Two TimezoneTransition instances are
-
# considered to be equal by eql? if offset, previous_offset and at are all
-
# equal and the type used to define at in both instances is the same.
-
1
def eql?(tti)
-
tti.kind_of?(TimezoneTransition) &&
-
offset == tti.offset && previous_offset == tti.previous_offset && at.eql?(tti.at)
-
end
-
-
# Returns a hash of this TimezoneTransition instance.
-
1
def hash
-
@offset.hash ^ @previous_offset.hash ^ at.hash
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}: #{at.inspect},#{@offset.inspect}>"
-
end
-
-
1
private
-
-
1
def raise_not_implemented(method_name)
-
raise NotImplementedError, "Subclasses must override #{method_name}"
-
end
-
end
-
end
-
1
module TZInfo
-
# A TimezoneTransition defined by as integer timestamp, as a rational to
-
# create a DateTime or as both.
-
#
-
# @private
-
1
class TimezoneTransitionDefinition < TimezoneTransition #:nodoc:
-
# The numerator of the DateTime if the transition time is defined as a
-
# DateTime, otherwise the transition time as a timestamp.
-
1
attr_reader :numerator_or_time
-
1
protected :numerator_or_time
-
-
# Either the denominator of the DateTime if the transition time is defined
-
# as a DateTime, otherwise nil.
-
1
attr_reader :denominator
-
1
protected :denominator
-
-
# Creates a new TimezoneTransitionDefinition with the given offset,
-
# previous_offset (both TimezoneOffset instances) and UTC time.
-
#
-
# The time can be specified as a timestamp, as a rational to create a
-
# DateTime, or as both.
-
#
-
# If both a timestamp and rational are given, then the rational will only
-
# be used if the timestamp falls outside of the range of Time on the
-
# platform being used at runtime.
-
#
-
# DateTimes are created from the rational as follows:
-
#
-
# RubyCoreSupport.datetime_new!(RubyCoreSupport.rational_new!(numerator, denominator), 0, Date::ITALY)
-
#
-
# For performance reasons, the numerator and denominator must be specified
-
# in their lowest form.
-
1
def initialize(offset, previous_offset, numerator_or_timestamp, denominator_or_numerator = nil, denominator = nil)
-
super(offset, previous_offset)
-
-
if denominator
-
numerator = denominator_or_numerator
-
timestamp = numerator_or_timestamp
-
elsif denominator_or_numerator
-
numerator = numerator_or_timestamp
-
denominator = denominator_or_numerator
-
timestamp = nil
-
else
-
numerator = nil
-
denominator = nil
-
timestamp = numerator_or_timestamp
-
end
-
-
# Determine whether to use the timestamp or the numerator and denominator.
-
if numerator && (
-
!timestamp ||
-
(timestamp < 0 && !RubyCoreSupport.time_supports_negative) ||
-
((timestamp < -2147483648 || timestamp > 2147483647) && !RubyCoreSupport.time_supports_64bit)
-
)
-
-
@numerator_or_time = numerator
-
@denominator = denominator
-
else
-
@numerator_or_time = timestamp
-
@denominator = nil
-
end
-
-
@at = nil
-
end
-
-
# A TimeOrDateTime instance representing the UTC time when this transition
-
# occurs.
-
1
def at
-
# Thread-safety: It is possible that the value of @at may be calculated
-
# multiple times in concurrently executing threads. It is not worth the
-
# overhead of locking to ensure that @at is only calculated once.
-
-
unless @at
-
unless @denominator
-
@at = TimeOrDateTime.new(@numerator_or_time)
-
else
-
r = RubyCoreSupport.rational_new!(@numerator_or_time, @denominator)
-
dt = RubyCoreSupport.datetime_new!(r, 0, Date::ITALY)
-
@at = TimeOrDateTime.new(dt)
-
end
-
end
-
-
@at
-
end
-
-
# Returns true if this TimezoneTransitionDefinition is equal to the given
-
# TimezoneTransitionDefinition. Two TimezoneTransitionDefinition instances
-
# are considered to be equal by eql? if offset, previous_offset,
-
# numerator_or_time and denominator are all equal.
-
1
def eql?(tti)
-
tti.kind_of?(TimezoneTransitionDefinition) &&
-
offset == tti.offset && previous_offset == tti.previous_offset &&
-
numerator_or_time == tti.numerator_or_time && denominator == tti.denominator
-
end
-
-
# Returns a hash of this TimezoneTransitionDefinition instance.
-
1
def hash
-
@offset.hash ^ @previous_offset.hash ^ @numerator_or_time.hash ^ @denominator.hash
-
end
-
end
-
end
-
1
module TZInfo
-
# Raised if no offsets have been defined when calling period_for_utc or
-
# periods_for_local. Indicates an error in the timezone data.
-
1
class NoOffsetsDefined < StandardError
-
end
-
-
# Represents a data timezone defined by a set of offsets and a set
-
# of transitions.
-
#
-
# @private
-
1
class TransitionDataTimezoneInfo < DataTimezoneInfo #:nodoc:
-
-
# Constructs a new TransitionDataTimezoneInfo with its identifier.
-
1
def initialize(identifier)
-
1
super(identifier)
-
1
@offsets = {}
-
1
@transitions = []
-
1
@previous_offset = nil
-
1
@transitions_index = nil
-
end
-
-
# Defines a offset. The id uniquely identifies this offset within the
-
# timezone. utc_offset and std_offset define the offset in seconds of
-
# standard time from UTC and daylight savings from standard time
-
# respectively. abbreviation describes the timezone offset (e.g. GMT, BST,
-
# EST or EDT).
-
#
-
# The first offset to be defined is treated as the offset that applies
-
# until the first transition. This will usually be in Local Mean Time (LMT).
-
#
-
# ArgumentError will be raised if the id is already defined.
-
1
def offset(id, utc_offset, std_offset, abbreviation)
-
1
raise ArgumentError, 'Offset already defined' if @offsets.has_key?(id)
-
-
1
offset = TimezoneOffset.new(utc_offset, std_offset, abbreviation)
-
1
@offsets[id] = offset
-
1
@previous_offset = offset unless @previous_offset
-
end
-
-
# Defines a transition. Transitions must be defined in chronological order.
-
# ArgumentError will be raised if a transition is added out of order.
-
# offset_id refers to an id defined with offset. ArgumentError will be
-
# raised if the offset_id cannot be found. numerator_or_time and
-
# denomiator specify the time the transition occurs as. See
-
# TimezoneTransition for more detail about specifying times.
-
1
def transition(year, month, offset_id, numerator_or_timestamp, denominator_or_numerator = nil, denominator = nil)
-
offset = @offsets[offset_id]
-
raise ArgumentError, 'Offset not found' unless offset
-
-
if @transitions_index
-
if year < @last_year || (year == @last_year && month < @last_month)
-
raise ArgumentError, 'Transitions must be increasing date order'
-
end
-
-
# Record the position of the first transition with this index.
-
index = transition_index(year, month)
-
@transitions_index[index] ||= @transitions.length
-
-
# Fill in any gaps
-
(index - 1).downto(0) do |i|
-
break if @transitions_index[i]
-
@transitions_index[i] = @transitions.length
-
end
-
else
-
@transitions_index = [@transitions.length]
-
@start_year = year
-
@start_month = month
-
end
-
-
@transitions << TimezoneTransitionDefinition.new(offset, @previous_offset,
-
numerator_or_timestamp, denominator_or_numerator, denominator)
-
@last_year = year
-
@last_month = month
-
@previous_offset = offset
-
end
-
-
# Returns the TimezonePeriod for the given UTC time.
-
# Raises NoOffsetsDefined if no offsets have been defined.
-
1
def period_for_utc(utc)
-
1
unless @transitions.empty?
-
utc = TimeOrDateTime.wrap(utc)
-
index = transition_index(utc.year, utc.mon)
-
-
start_transition = nil
-
start = transition_before_end(index)
-
if start
-
start.downto(0) do |i|
-
if @transitions[i].at <= utc
-
start_transition = @transitions[i]
-
break
-
end
-
end
-
end
-
-
end_transition = nil
-
start = transition_after_start(index)
-
if start
-
start.upto(@transitions.length - 1) do |i|
-
if @transitions[i].at > utc
-
end_transition = @transitions[i]
-
break
-
end
-
end
-
end
-
-
if start_transition || end_transition
-
TimezonePeriod.new(start_transition, end_transition)
-
else
-
# Won't happen since there are transitions. Must always find one
-
# transition that is either >= or < the specified time.
-
raise 'No transitions found in search'
-
end
-
else
-
1
raise NoOffsetsDefined, 'No offsets have been defined' unless @previous_offset
-
1
TimezonePeriod.new(nil, nil, @previous_offset)
-
end
-
end
-
-
# Returns the set of TimezonePeriods for the given local time as an array.
-
# Results returned are ordered by increasing UTC start date.
-
# Returns an empty array if no periods are found for the given time.
-
# Raises NoOffsetsDefined if no offsets have been defined.
-
1
def periods_for_local(local)
-
unless @transitions.empty?
-
local = TimeOrDateTime.wrap(local)
-
index = transition_index(local.year, local.mon)
-
-
result = []
-
-
start_index = transition_after_start(index - 1)
-
if start_index && @transitions[start_index].local_end_at > local
-
if start_index > 0
-
if @transitions[start_index - 1].local_start_at <= local
-
result << TimezonePeriod.new(@transitions[start_index - 1], @transitions[start_index])
-
end
-
else
-
result << TimezonePeriod.new(nil, @transitions[start_index])
-
end
-
end
-
-
end_index = transition_before_end(index + 1)
-
-
if end_index
-
start_index = end_index unless start_index
-
-
start_index.upto(transition_before_end(index + 1)) do |i|
-
if @transitions[i].local_start_at <= local
-
if i + 1 < @transitions.length
-
if @transitions[i + 1].local_end_at > local
-
result << TimezonePeriod.new(@transitions[i], @transitions[i + 1])
-
end
-
else
-
result << TimezonePeriod.new(@transitions[i], nil)
-
end
-
end
-
end
-
end
-
-
result
-
else
-
raise NoOffsetsDefined, 'No offsets have been defined' unless @previous_offset
-
[TimezonePeriod.new(nil, nil, @previous_offset)]
-
end
-
end
-
-
# Returns an Array of TimezoneTransition instances representing the times
-
# where the UTC offset of the timezone changes.
-
#
-
# Transitions are returned up to a given date and time up to a given date
-
# and time, specified in UTC (utc_to).
-
#
-
# A from date and time may also be supplied using the utc_from parameter
-
# (also specified in UTC). If utc_from is not nil, only transitions from
-
# that date and time onwards will be returned.
-
#
-
# Comparisons with utc_to are exclusive. Comparisons with utc_from are
-
# inclusive. If a transition falls precisely on utc_to, it will be excluded.
-
# If a transition falls on utc_from, it will be included.
-
#
-
# Transitions returned are ordered by when they occur, from earliest to
-
# latest.
-
#
-
# utc_to and utc_from can be specified using either DateTime, Time or
-
# integer timestamps (Time.to_i).
-
#
-
# If utc_from is specified and utc_to is not greater than utc_from, then
-
# transitions_up_to raises an ArgumentError exception.
-
1
def transitions_up_to(utc_to, utc_from = nil)
-
utc_to = TimeOrDateTime.wrap(utc_to)
-
utc_from = utc_from ? TimeOrDateTime.wrap(utc_from) : nil
-
-
if utc_from && utc_to <= utc_from
-
raise ArgumentError, 'utc_to must be greater than utc_from'
-
end
-
-
unless @transitions.empty?
-
if utc_from
-
from = transition_after_start(transition_index(utc_from.year, utc_from.mon))
-
-
if from
-
while from < @transitions.length && @transitions[from].at < utc_from
-
from += 1
-
end
-
-
if from >= @transitions.length
-
return []
-
end
-
else
-
# utc_from is later than last transition.
-
return []
-
end
-
else
-
from = 0
-
end
-
-
to = transition_before_end(transition_index(utc_to.year, utc_to.mon))
-
-
if to
-
while to >= 0 && @transitions[to].at >= utc_to
-
to -= 1
-
end
-
-
if to < 0
-
return []
-
end
-
else
-
# utc_to is earlier than first transition.
-
return []
-
end
-
-
@transitions[from..to]
-
else
-
[]
-
end
-
end
-
-
1
private
-
# Returns the index into the @transitions_index array for a given year
-
# and month.
-
1
def transition_index(year, month)
-
index = (year - @start_year) * 2
-
index += 1 if month > 6
-
index -= 1 if @start_month > 6
-
index
-
end
-
-
# Returns the index into @transitions of the first transition that occurs
-
# on or after the start of the given index into @transitions_index.
-
# Returns nil if there are no such transitions.
-
1
def transition_after_start(index)
-
if index >= @transitions_index.length
-
nil
-
else
-
index = 0 if index < 0
-
@transitions_index[index]
-
end
-
end
-
-
# Returns the index into @transitions of the first transition that occurs
-
# before the end of the given index into @transitions_index.
-
# Returns nil if there are no such transitions.
-
1
def transition_before_end(index)
-
index = index + 1
-
-
if index <= 0
-
nil
-
elsif index >= @transitions_index.length
-
@transitions.length - 1
-
else
-
@transitions_index[index] - 1
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
# Represents information about a country returned by ZoneinfoDataSource.
-
#
-
# @private
-
1
class ZoneinfoCountryInfo < CountryInfo #:nodoc:
-
# Constructs a new CountryInfo with an ISO 3166 country code, name and
-
# an array of CountryTimezones.
-
1
def initialize(code, name, zones)
-
249
super(code, name)
-
249
@zones = zones.dup.freeze
-
249
@zone_identifiers = nil
-
end
-
-
# Returns a frozen array of all the zone identifiers for the country ordered
-
# geographically, most populous first.
-
1
def zone_identifiers
-
# Thread-safety: It is possible that the value of @zone_identifiers may be
-
# calculated multiple times in concurrently executing threads. It is not
-
# worth the overhead of locking to ensure that @zone_identifiers is only
-
# calculated once.
-
-
unless @zone_identifiers
-
@zone_identifiers = zones.collect {|zone| zone.identifier}.freeze
-
end
-
-
@zone_identifiers
-
end
-
-
# Returns a frozen array of all the timezones for the for the country
-
# ordered geographically, most populous first.
-
1
def zones
-
@zones
-
end
-
end
-
end
-
1
module TZInfo
-
# An InvalidZoneinfoDirectory exception is raised if the DataSource is
-
# set to a specific zoneinfo path, which is not a valid zoneinfo directory
-
# (i.e. a directory containing index files named iso3166.tab and zone.tab
-
# as well as other timezone files).
-
1
class InvalidZoneinfoDirectory < StandardError
-
end
-
-
# A ZoneinfoDirectoryNotFound exception is raised if no valid zoneinfo
-
# directory could be found when checking the paths listed in
-
# ZoneinfoDataSource.search_path. A valid zoneinfo directory is one that
-
# contains timezone files, a country code index file named iso3166.tab and a
-
# timezone index file named zone1970.tab or zone.tab.
-
1
class ZoneinfoDirectoryNotFound < StandardError
-
end
-
-
# A DataSource that loads data from a 'zoneinfo' directory containing
-
# compiled "TZif" version 3 (or earlier) files in addition to iso3166.tab and
-
# zone1970.tab or zone.tab index files.
-
#
-
# To have TZInfo load the system zoneinfo files, call TZInfo::DataSource.set
-
# as follows:
-
#
-
# TZInfo::DataSource.set(:zoneinfo)
-
#
-
# To load zoneinfo files from a particular directory, pass the directory to
-
# TZInfo::DataSource.set:
-
#
-
# TZInfo::DataSource.set(:zoneinfo, directory)
-
#
-
# Note that the platform used at runtime may limit the range of available
-
# transition data that can be loaded from zoneinfo files. There are two
-
# factors to consider:
-
#
-
# First of all, the zoneinfo support in TZInfo makes use of Ruby's Time class.
-
# On 32-bit builds of Ruby 1.8, the Time class only supports 32-bit
-
# timestamps. This means that only Times between 1901-12-13 20:45:52 and
-
# 2038-01-19 03:14:07 can be represented. Furthermore, certain platforms only
-
# allow for positive 32-bit timestamps (notably Windows), making the earliest
-
# representable time 1970-01-01 00:00:00.
-
#
-
# 64-bit builds of Ruby 1.8 and all builds of Ruby 1.9 support 64-bit
-
# timestamps. This means that there is no practical restriction on the range
-
# of the Time class on these platforms.
-
#
-
# TZInfo will only load transitions that fall within the supported range of
-
# the Time class. Any queries performed on times outside of this range may
-
# give inaccurate results.
-
#
-
# The second factor concerns the zoneinfo files. Versions of the 'zic' tool
-
# (used to build zoneinfo files) that were released prior to February 2006
-
# created zoneinfo files that used 32-bit integers for transition timestamps.
-
# Later versions of zic produce zoneinfo files that use 64-bit integers. If
-
# you have 32-bit zoneinfo files on your system, then any queries falling
-
# outside of the range 1901-12-13 20:45:52 to 2038-01-19 03:14:07 may be
-
# inaccurate.
-
#
-
# Most modern platforms include 64-bit zoneinfo files. However, Mac OS X (up
-
# to at least 10.8.4) still uses 32-bit zoneinfo files.
-
#
-
# To check whether your zoneinfo files contain 32-bit or 64-bit transition
-
# data, you can run the following code (substituting the identifier of the
-
# zone you want to test for zone_identifier):
-
#
-
# TZInfo::DataSource.set(:zoneinfo)
-
# dir = TZInfo::DataSource.get.zoneinfo_dir
-
# File.open(File.join(dir, zone_identifier), 'r') {|f| f.read(5) }
-
#
-
# If the last line returns "TZif\\x00", then you have a 32-bit zoneinfo file.
-
# If it returns "TZif2" or "TZif3" then you have a 64-bit zoneinfo file.
-
#
-
# If you require support for 64-bit transitions, but are restricted to 32-bit
-
# zoneinfo support, then you may want to consider using TZInfo::RubyDataSource
-
# instead.
-
1
class ZoneinfoDataSource < DataSource
-
# The default value of ZoneinfoDataSource.search_path.
-
1
DEFAULT_SEARCH_PATH = ['/usr/share/zoneinfo', '/usr/share/lib/zoneinfo', '/etc/zoneinfo'].freeze
-
-
# The default value of ZoneinfoDataSource.alternate_iso3166_tab_search_path.
-
1
DEFAULT_ALTERNATE_ISO3166_TAB_SEARCH_PATH = ['/usr/share/misc/iso3166.tab', '/usr/share/misc/iso3166'].freeze
-
-
# Paths to be checked to find the system zoneinfo directory.
-
1
@@search_path = DEFAULT_SEARCH_PATH.dup
-
-
# Paths to possible alternate iso3166.tab files (used to locate the
-
# system-wide iso3166.tab files on FreeBSD and OpenBSD).
-
1
@@alternate_iso3166_tab_search_path = DEFAULT_ALTERNATE_ISO3166_TAB_SEARCH_PATH.dup
-
-
# An Array of directories that will be checked to find the system zoneinfo
-
# directory.
-
#
-
# Directories are checked in the order they appear in the Array.
-
#
-
# The default value is ['/usr/share/zoneinfo', '/usr/share/lib/zoneinfo', '/etc/zoneinfo'].
-
1
def self.search_path
-
1
@@search_path
-
end
-
-
# Sets the directories to be checked when locating the system zoneinfo
-
# directory.
-
#
-
# Can be set to an Array of directories or a String containing directories
-
# separated with File::PATH_SEPARATOR.
-
#
-
# Directories are checked in the order they appear in the Array or String.
-
#
-
# Set to nil to revert to the default paths.
-
1
def self.search_path=(search_path)
-
@@search_path = process_search_path(search_path, DEFAULT_SEARCH_PATH)
-
end
-
-
# An Array of paths that will be checked to find an alternate iso3166.tab
-
# file if one was not included in the zoneinfo directory (for example, on
-
# FreeBSD and OpenBSD systems).
-
#
-
# Paths are checked in the order they appear in the array.
-
#
-
# The default value is ['/usr/share/misc/iso3166.tab', '/usr/share/misc/iso3166'].
-
1
def self.alternate_iso3166_tab_search_path
-
1
@@alternate_iso3166_tab_search_path
-
end
-
-
# Sets the paths to check to locate an alternate iso3166.tab file if one was
-
# not included in the zoneinfo directory.
-
#
-
# Can be set to an Array of directories or a String containing directories
-
# separated with File::PATH_SEPARATOR.
-
#
-
# Paths are checked in the order they appear in the array.
-
#
-
# Set to nil to revert to the default paths.
-
1
def self.alternate_iso3166_tab_search_path=(alternate_iso3166_tab_search_path)
-
@@alternate_iso3166_tab_search_path = process_search_path(alternate_iso3166_tab_search_path, DEFAULT_ALTERNATE_ISO3166_TAB_SEARCH_PATH)
-
end
-
-
# The zoneinfo directory being used.
-
1
attr_reader :zoneinfo_dir
-
-
# Creates a new ZoneinfoDataSource.
-
#
-
# If zoneinfo_dir is specified, it will be checked and used as the source
-
# of zoneinfo files.
-
#
-
# The directory must contain a file named iso3166.tab and a file named
-
# either zone1970.tab or zone.tab. These may either be included in the root
-
# of the directory or in a 'tab' sub-directory and named 'country.tab' and
-
# 'zone_sun.tab' respectively (as is the case on Solaris.
-
#
-
# Additionally, the path to iso3166.tab can be overridden using the
-
# alternate_iso3166_tab_path parameter.
-
#
-
# InvalidZoneinfoDirectory will be raised if the iso3166.tab and
-
# zone1970.tab or zone.tab files cannot be found using the zoneinfo_dir and
-
# alternate_iso3166_tab_path parameters.
-
#
-
# If zoneinfo_dir is not specified or nil, the paths referenced in
-
# search_path are searched in order to find a valid zoneinfo directory
-
# (one that contains zone1970.tab or zone.tab and iso3166.tab files as
-
# above).
-
#
-
# The paths referenced in alternate_iso3166_tab_search_path are also
-
# searched to find an iso3166.tab file if one of the searched zoneinfo
-
# directories doesn't contain an iso3166.tab file.
-
#
-
# If no valid directory can be found by searching, ZoneinfoDirectoryNotFound
-
# will be raised.
-
1
def initialize(zoneinfo_dir = nil, alternate_iso3166_tab_path = nil)
-
1
if zoneinfo_dir
-
iso3166_tab_path, zone_tab_path = validate_zoneinfo_dir(zoneinfo_dir, alternate_iso3166_tab_path)
-
-
unless iso3166_tab_path && zone_tab_path
-
raise InvalidZoneinfoDirectory, "#{zoneinfo_dir} is not a directory or doesn't contain a iso3166.tab file and a zone1970.tab or zone.tab file."
-
end
-
-
@zoneinfo_dir = zoneinfo_dir
-
else
-
1
@zoneinfo_dir, iso3166_tab_path, zone_tab_path = find_zoneinfo_dir
-
-
1
unless @zoneinfo_dir && iso3166_tab_path && zone_tab_path
-
raise ZoneinfoDirectoryNotFound, "None of the paths included in TZInfo::ZoneinfoDataSource.search_path are valid zoneinfo directories."
-
end
-
end
-
-
1
@zoneinfo_dir = File.expand_path(@zoneinfo_dir).freeze
-
1
@timezone_index = load_timezone_index.freeze
-
1
@country_index = load_country_index(iso3166_tab_path, zone_tab_path).freeze
-
end
-
-
# Returns a TimezoneInfo instance for a given identifier.
-
# Raises InvalidTimezoneIdentifier if the timezone is not found or the
-
# identifier is invalid.
-
1
def load_timezone_info(identifier)
-
1
begin
-
1
if @timezone_index.include?(identifier)
-
1
path = File.join(@zoneinfo_dir, identifier)
-
-
# Untaint path rather than identifier. We don't want to modify
-
# identifier. identifier may also be frozen and therefore cannot be
-
# untainted.
-
1
path.untaint
-
-
1
begin
-
1
ZoneinfoTimezoneInfo.new(identifier, path)
-
rescue InvalidZoneinfoFile => e
-
raise InvalidTimezoneIdentifier, e.message
-
end
-
else
-
raise InvalidTimezoneIdentifier, 'Invalid identifier'
-
end
-
rescue Errno::ENOENT, Errno::ENAMETOOLONG, Errno::ENOTDIR
-
raise InvalidTimezoneIdentifier, 'Invalid identifier'
-
rescue Errno::EACCES => e
-
raise InvalidTimezoneIdentifier, e.message
-
end
-
end
-
-
# Returns an array of all the available timezone identifiers.
-
1
def timezone_identifiers
-
@timezone_index
-
end
-
-
# Returns an array of all the available timezone identifiers for
-
# data timezones (i.e. those that actually contain definitions).
-
#
-
# For ZoneinfoDataSource, this will always be identical to
-
# timezone_identifers.
-
1
def data_timezone_identifiers
-
@timezone_index
-
end
-
-
# Returns an array of all the available timezone identifiers that
-
# are links to other timezones.
-
#
-
# For ZoneinfoDataSource, this will always be an empty array.
-
1
def linked_timezone_identifiers
-
[].freeze
-
end
-
-
# Returns a CountryInfo instance for the given ISO 3166-1 alpha-2
-
# country code. Raises InvalidCountryCode if the country could not be found
-
# or the code is invalid.
-
1
def load_country_info(code)
-
info = @country_index[code]
-
raise InvalidCountryCode, 'Invalid country code' unless info
-
info
-
end
-
-
# Returns an array of all the available ISO 3166-1 alpha-2
-
# country codes.
-
1
def country_codes
-
@country_index.keys.freeze
-
end
-
-
# Returns the name and information about this DataSource.
-
1
def to_s
-
"Zoneinfo DataSource: #{@zoneinfo_dir}"
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}: #{@zoneinfo_dir}>"
-
end
-
-
1
private
-
-
# Processes a path for use as the search_path or
-
# alternate_iso3166_tab_search_path.
-
1
def self.process_search_path(path, default)
-
if path
-
if path.kind_of?(String)
-
path.split(File::PATH_SEPARATOR)
-
else
-
path.collect {|p| p.to_s}
-
end
-
else
-
default.dup
-
end
-
end
-
-
# Validates a zoneinfo directory and returns the paths to the iso3166.tab
-
# and zone1970.tab or zone.tab files if valid. If the directory is not
-
# valid, returns nil.
-
#
-
# The path to the iso3166.tab file may be overriden by passing in a path.
-
# This is treated as either absolute or relative to the current working
-
# directory.
-
1
def validate_zoneinfo_dir(path, iso3166_tab_path = nil)
-
1
if File.directory?(path)
-
1
if iso3166_tab_path
-
return nil unless File.file?(iso3166_tab_path)
-
else
-
1
iso3166_tab_path = resolve_tab_path(path, ['iso3166.tab'], 'country.tab')
-
1
return nil unless iso3166_tab_path
-
end
-
-
1
zone_tab_path = resolve_tab_path(path, ['zone1970.tab', 'zone.tab'], 'zone_sun.tab')
-
1
return nil unless zone_tab_path
-
-
1
[iso3166_tab_path, zone_tab_path]
-
else
-
nil
-
end
-
end
-
-
# Attempts to resolve the path to a tab file given its standard names and
-
# tab sub-directory name (as used on Solaris).
-
1
def resolve_tab_path(zoneinfo_path, standard_names, tab_name)
-
2
standard_names.each do |standard_name|
-
3
path = File.join(zoneinfo_path, standard_name)
-
3
return path if File.file?(path)
-
end
-
-
path = File.join(zoneinfo_path, 'tab', tab_name)
-
return path if File.file?(path)
-
-
nil
-
end
-
-
# Finds a zoneinfo directory using search_path and
-
# alternate_iso3166_tab_search_path. Returns the paths to the directory,
-
# the iso3166.tab file and the zone.tab file or nil if not found.
-
1
def find_zoneinfo_dir
-
1
alternate_iso3166_tab_path = self.class.alternate_iso3166_tab_search_path.detect do |path|
-
2
File.file?(path)
-
end
-
-
1
self.class.search_path.each do |path|
-
# Try without the alternate_iso3166_tab_path first.
-
1
iso3166_tab_path, zone_tab_path = validate_zoneinfo_dir(path)
-
1
return path, iso3166_tab_path, zone_tab_path if iso3166_tab_path && zone_tab_path
-
-
if alternate_iso3166_tab_path
-
iso3166_tab_path, zone_tab_path = validate_zoneinfo_dir(path, alternate_iso3166_tab_path)
-
return path, iso3166_tab_path, zone_tab_path if iso3166_tab_path && zone_tab_path
-
end
-
end
-
-
# Not found.
-
nil
-
end
-
-
# Scans @zoneinfo_dir and returns an Array of available timezone
-
# identifiers.
-
1
def load_timezone_index
-
1
index = []
-
-
# Ignoring particular files:
-
# +VERSION is included on Mac OS X.
-
# localtime current local timezone (may be a link).
-
# posix, posixrules and right are directories containing other versions of the zoneinfo files.
-
# src is a directory containing the tzdata source included on Solaris.
-
# Factory is the compiled in default timezone.
-
-
1
enum_timezones(nil, ['+VERSION', 'localtime', 'posix', 'posixrules', 'right', 'src', 'Factory']) do |identifier|
-
584
index << identifier
-
end
-
-
1
index.sort
-
end
-
-
# Recursively scans a directory of timezones, calling the passed in block
-
# for each identifier found.
-
1
def enum_timezones(dir, exclude = [], &block)
-
22
Dir.foreach(dir ? File.join(@zoneinfo_dir, dir) : @zoneinfo_dir) do |entry|
-
654
unless entry =~ /\./ || exclude.include?(entry)
-
605
entry.untaint
-
605
path = dir ? File.join(dir, entry) : entry
-
605
full_path = File.join(@zoneinfo_dir, path)
-
-
605
if File.directory?(full_path)
-
21
enum_timezones(path, [], &block)
-
elsif File.file?(full_path)
-
584
yield path
-
end
-
end
-
end
-
end
-
-
# Uses the iso3166.tab and zone1970.tab or zone.tab files to build an index
-
# of the available countries and their timezones.
-
1
def load_country_index(iso3166_tab_path, zone_tab_path)
-
-
# Handle standard 3 to 4 column zone.tab files as well as the 4 to 5
-
# column format used by Solaris.
-
#
-
# On Solaris, an extra column before the comment gives an optional
-
# linked/alternate timezone identifier (or '-' if not set).
-
#
-
# Additionally, there is a section at the end of the file for timezones
-
# covering regions. These are given lower-case "country" codes. The timezone
-
# identifier column refers to a continent instead of an identifier. These
-
# lines will be ignored by TZInfo.
-
#
-
# Since the last column is optional in both formats, testing for the
-
# Solaris format is done in two passes. The first pass identifies if there
-
# are any lines using 5 columns.
-
-
-
# The first column is allowed to be a comma separated list of country
-
# codes, as used in zone1970.tab (introduced in tzdata 2014f).
-
#
-
# The first country code in the comma-separated list is the country that
-
# contains the city the zone identifer is based on. The first country
-
# code on each line is considered to be primary with the others
-
# secondary.
-
#
-
# The zones for each country are ordered primary first, then secondary.
-
# Within the primary and secondary groups, the zones are ordered by their
-
# order in the file.
-
-
1
file_is_5_column = false
-
1
zone_tab = []
-
-
1
RubyCoreSupport.open_file(zone_tab_path, 'r', :external_encoding => 'UTF-8', :internal_encoding => 'UTF-8') do |file|
-
1
file.each_line do |line|
-
452
line.chomp!
-
-
452
if line =~ /\A([A-Z]{2}(?:,[A-Z]{2})*)\t(?:([+\-])(\d{2})(\d{2})([+\-])(\d{3})(\d{2})|([+\-])(\d{2})(\d{2})(\d{2})([+\-])(\d{3})(\d{2})(\d{2}))\t([^\t]+)(?:\t([^\t]+))?(?:\t([^\t]+))?\z/
-
416
codes = $1
-
-
416
if $2
-
368
latitude = dms_to_rational($2, $3, $4)
-
368
longitude = dms_to_rational($5, $6, $7)
-
else
-
48
latitude = dms_to_rational($8, $9, $10, $11)
-
48
longitude = dms_to_rational($12, $13, $14, $15)
-
end
-
-
416
zone_identifier = $16
-
416
column4 = $17
-
416
column5 = $18
-
-
416
file_is_5_column = true if column5
-
-
416
zone_tab << [codes.split(','), zone_identifier, latitude, longitude, column4, column5]
-
end
-
end
-
end
-
-
1
primary_zones = {}
-
1
secondary_zones = {}
-
-
1
zone_tab.each do |codes, zone_identifier, latitude, longitude, column4, column5|
-
416
description = file_is_5_column ? column5 : column4
-
416
country_timezone = CountryTimezone.new(zone_identifier, latitude, longitude, description)
-
-
# codes will always have at least one element
-
-
416
(primary_zones[codes.first] ||= []) << country_timezone
-
-
416
codes[1..-1].each do |code|
-
(secondary_zones[code] ||= []) << country_timezone
-
end
-
end
-
-
1
countries = {}
-
-
1
RubyCoreSupport.open_file(iso3166_tab_path, 'r', :external_encoding => 'UTF-8', :internal_encoding => 'UTF-8') do |file|
-
1
file.each_line do |line|
-
275
line.chomp!
-
-
# Handle both the two column alpha-2 and name format used in the tz
-
# database as well as the 4 column alpha-2, alpha-3, numeric-3 and
-
# name format used by FreeBSD and OpenBSD.
-
-
275
if line =~ /\A([A-Z]{2})(?:\t[A-Z]{3}\t[0-9]{3})?\t(.+)\z/
-
249
code = $1
-
249
name = $2
-
249
zones = (primary_zones[code] || []) + (secondary_zones[code] || [])
-
-
249
countries[code] = ZoneinfoCountryInfo.new(code, name, zones)
-
end
-
end
-
end
-
-
1
countries
-
end
-
-
# Converts degrees, minutes and seconds to a Rational.
-
1
def dms_to_rational(sign, degrees, minutes, seconds = nil)
-
832
result = degrees.to_i + Rational(minutes.to_i, 60)
-
832
result += Rational(seconds.to_i, 3600) if seconds
-
832
result = -result if sign == '-'
-
832
result
-
end
-
end
-
end
-
1
module TZInfo
-
# An InvalidZoneinfoFile exception is raised if an attempt is made to load an
-
# invalid zoneinfo file.
-
1
class InvalidZoneinfoFile < StandardError
-
end
-
-
# Represents a timezone defined by a compiled zoneinfo TZif (\0, 2 or 3) file.
-
#
-
# @private
-
1
class ZoneinfoTimezoneInfo < TransitionDataTimezoneInfo #:nodoc:
-
-
# Minimum supported timestamp (inclusive).
-
#
-
# Time.utc(1700, 1, 1).to_i
-
1
MIN_TIMESTAMP = -8520336000
-
-
# Maximum supported timestamp (exclusive).
-
#
-
# Time.utc(2500, 1, 1).to_i
-
1
MAX_TIMESTAMP = 16725225600
-
-
# Constructs the new ZoneinfoTimezoneInfo with an identifier and path
-
# to the file.
-
1
def initialize(identifier, file_path)
-
1
super(identifier)
-
-
1
File.open(file_path, 'rb') do |file|
-
1
parse(file)
-
end
-
end
-
-
1
private
-
# Unpack will return unsigned 32-bit integers. Translate to
-
# signed 32-bit.
-
1
def make_signed_int32(long)
-
1
long >= 0x80000000 ? long - 0x100000000 : long
-
end
-
-
# Unpack will return a 64-bit integer as two unsigned 32-bit integers
-
# (most significant first). Translate to signed 64-bit
-
1
def make_signed_int64(high, low)
-
unsigned = (high << 32) | low
-
unsigned >= 0x8000000000000000 ? unsigned - 0x10000000000000000 : unsigned
-
end
-
-
# Read bytes from file and check that the correct number of bytes could
-
# be read. Raises InvalidZoneinfoFile if the number of bytes didn't match
-
# the number requested.
-
1
def check_read(file, bytes)
-
3
result = file.read(bytes)
-
-
3
unless result && result.length == bytes
-
raise InvalidZoneinfoFile, "Expected #{bytes} bytes reading '#{file.path}', but got #{result ? result.length : 0} bytes"
-
end
-
-
3
result
-
end
-
-
# Zoneinfo doesn't include the offset from standard time (std_offset).
-
# Derive the missing offsets by looking at changes in the total UTC
-
# offset.
-
#
-
# This will be run through forwards and then backwards by the parse
-
# method.
-
1
def derive_offsets(transitions, offsets)
-
2
previous_offset = nil
-
-
2
transitions.each do |t|
-
offset = offsets[t[:offset]]
-
-
if !offset[:std_offset] && offset[:is_dst] && previous_offset
-
difference = offset[:utc_total_offset] - previous_offset[:utc_total_offset]
-
-
if previous_offset[:is_dst]
-
if previous_offset[:std_offset]
-
std_offset = previous_offset[:std_offset] + difference
-
else
-
std_offset = nil
-
end
-
else
-
std_offset = difference
-
end
-
-
if std_offset && std_offset > 0
-
offset[:std_offset] = std_offset
-
offset[:utc_offset] = offset[:utc_total_offset] - std_offset
-
end
-
end
-
-
previous_offset = offset
-
end
-
end
-
-
# Parses a zoneinfo file and intializes the DataTimezoneInfo structures.
-
1
def parse(file)
-
1
magic, version, ttisgmtcnt, ttisstdcnt, leapcnt, timecnt, typecnt, charcnt =
-
check_read(file, 44).unpack('a4 a x15 NNNNNN')
-
-
1
if magic != 'TZif'
-
raise InvalidZoneinfoFile, "The file '#{file.path}' does not start with the expected header."
-
end
-
-
1
if (version == '2' || version == '3') && RubyCoreSupport.time_supports_64bit
-
# Skip the first 32-bit section and read the header of the second 64-bit section
-
file.seek(timecnt * 5 + typecnt * 6 + charcnt + leapcnt * 8 + ttisgmtcnt + ttisstdcnt, IO::SEEK_CUR)
-
-
prev_version = version
-
-
magic, version, ttisgmtcnt, ttisstdcnt, leapcnt, timecnt, typecnt, charcnt =
-
check_read(file, 44).unpack('a4 a x15 NNNNNN')
-
-
unless magic == 'TZif' && (version == prev_version)
-
raise InvalidZoneinfoFile, "The file '#{file.path}' contains an invalid 64-bit section header."
-
end
-
-
using_64bit = true
-
elsif version != '3' && version != '2' && version != "\0"
-
raise InvalidZoneinfoFile, "The file '#{file.path}' contains a version of the zoneinfo format that is not currently supported."
-
else
-
1
using_64bit = false
-
end
-
-
1
unless leapcnt == 0
-
raise InvalidZoneinfoFile, "The zoneinfo file '#{file.path}' contains leap second data. TZInfo requires zoneinfo files that omit leap seconds."
-
end
-
-
1
transitions = []
-
-
1
if using_64bit
-
(0...timecnt).each do |i|
-
high, low = check_read(file, 8).unpack('NN')
-
transition_time = make_signed_int64(high, low)
-
transitions << {:at => transition_time}
-
end
-
else
-
1
(0...timecnt).each do |i|
-
transition_time = make_signed_int32(check_read(file, 4).unpack('N')[0])
-
transitions << {:at => transition_time}
-
end
-
end
-
-
1
(0...timecnt).each do |i|
-
localtime_type = check_read(file, 1).unpack('C')[0]
-
transitions[i][:offset] = localtime_type
-
end
-
-
1
offsets = []
-
-
1
(0...typecnt).each do |i|
-
1
gmtoff, isdst, abbrind = check_read(file, 6).unpack('NCC')
-
1
gmtoff = make_signed_int32(gmtoff)
-
1
isdst = isdst == 1
-
1
offset = {:utc_total_offset => gmtoff, :is_dst => isdst, :abbr_index => abbrind}
-
-
1
unless isdst
-
1
offset[:utc_offset] = gmtoff
-
1
offset[:std_offset] = 0
-
end
-
-
1
offsets << offset
-
end
-
-
1
abbrev = check_read(file, charcnt)
-
-
1
offsets.each do |o|
-
1
abbrev_start = o[:abbr_index]
-
1
raise InvalidZoneinfoFile, "Abbreviation index is out of range in file '#{file.path}'" unless abbrev_start < abbrev.length
-
-
1
abbrev_end = abbrev.index("\0", abbrev_start)
-
1
raise InvalidZoneinfoFile, "Missing abbreviation null terminator in file '#{file.path}'" unless abbrev_end
-
-
1
o[:abbr] = RubyCoreSupport.force_encoding(abbrev[abbrev_start...abbrev_end], 'UTF-8')
-
end
-
-
1
transitions.each do |t|
-
if t[:offset] < 0 || t[:offset] >= offsets.length
-
raise InvalidZoneinfoFile, "Invalid offset referenced by transition in file '#{file.path}'."
-
end
-
end
-
-
# Derive the offsets from standard time (std_offset).
-
1
derive_offsets(transitions, offsets)
-
1
derive_offsets(transitions.reverse, offsets)
-
-
# Assign anything left a standard offset of one hour
-
1
offsets.each do |o|
-
1
if !o[:std_offset] && o[:is_dst]
-
o[:std_offset] = 3600
-
o[:utc_offset] = o[:utc_total_offset] - 3600
-
end
-
end
-
-
# Find the first non-dst offset. This is used as the offset for the time
-
# before the first transition.
-
1
first = nil
-
1
offsets.each_with_index do |o, i|
-
1
if !o[:is_dst]
-
1
first = i
-
1
break
-
end
-
end
-
-
1
if first
-
1
offset first, offsets[first][:utc_offset], offsets[first][:std_offset], offsets[first][:abbr].untaint.to_sym
-
end
-
-
1
offsets.each_with_index do |o, i|
-
1
offset i, o[:utc_offset], o[:std_offset], o[:abbr].untaint.to_sym unless i == first
-
end
-
-
1
if !using_64bit && !RubyCoreSupport.time_supports_negative
-
# Filter out transitions that are not supported by Time on this
-
# platform.
-
-
# Move the last transition before the epoch up to the epoch. This
-
# allows for accurate conversions for all supported timestamps on the
-
# platform.
-
-
before_epoch, after_epoch = transitions.partition {|t| t[:at] < 0}
-
-
if before_epoch.length > 0 && after_epoch.length > 0 && after_epoch.first[:at] != 0
-
last_before = before_epoch.last
-
last_before[:at] = 0
-
transitions = [last_before] + after_epoch
-
else
-
transitions = after_epoch
-
end
-
end
-
-
# Ignore transitions that occur outside of a defined window. The
-
# transition index cannot handle a large range of transition times.
-
#
-
# This is primarily intended to ignore the far in the past transition
-
# added in zic 2014c (at timestamp -2**63 in zic 2014c and at the
-
# approximate time of the big bang from zic 2014d).
-
1
transitions.each do |t|
-
at = t[:at]
-
if at >= MIN_TIMESTAMP && at < MAX_TIMESTAMP
-
time = Time.at(at).utc
-
transition time.year, time.mon, t[:offset], at
-
end
-
end
-
end
-
end
-
end
-
# encoding: UTF-8
-
-
1
require "execjs"
-
1
require "json"
-
1
require "uglifier/version"
-
-
# A wrapper around the UglifyJS interface
-
1
class Uglifier
-
1
Error = ExecJS::Error
-
1
JS = <<-JS
-
function comments(option) {
-
if (Object.prototype.toString.call(option) === '[object Array]') {
-
return new RegExp(option[0], option[1]);
-
} else if (option == "jsdoc") {
-
return function(node, comment) {
-
if (comment.type == "comment2") {
-
return /@preserve|@license|@cc_on/i.test(comment.value);
-
} else {
-
return false;
-
}
-
}
-
} else {
-
return option;
-
}
-
}
-
-
var options = %s;
-
var source = options.source;
-
var ast = UglifyJS.parse(source, options.parse_options);
-
ast.figure_out_scope();
-
-
if (options.compress) {
-
var compressor = UglifyJS.Compressor(options.compress);
-
ast = ast.transform(compressor);
-
ast.figure_out_scope();
-
}
-
-
if (options.mangle) {
-
ast.compute_char_frequency();
-
ast.mangle_names(options.mangle);
-
}
-
-
if (options.enclose) {
-
ast = ast.wrap_enclose(options.enclose);
-
}
-
-
var gen_code_options = options.output;
-
gen_code_options.comments = comments(options.output.comments);
-
-
if (options.generate_map) {
-
var source_map = UglifyJS.SourceMap(options.source_map_options);
-
gen_code_options.source_map = source_map;
-
}
-
-
var stream = UglifyJS.OutputStream(gen_code_options);
-
-
ast.print(stream);
-
if (options.generate_map) {
-
return [stream.toString(), source_map.toString()];
-
} else {
-
return stream.toString();
-
}
-
JS
-
-
# UglifyJS source patch
-
1
SourcePath = File.expand_path("../uglify.js", __FILE__)
-
# ES5 shims source path
-
1
ES5FallbackPath = File.expand_path("../es5.js", __FILE__)
-
# String.split shim source path
-
1
SplitFallbackPath = File.expand_path("../split.js", __FILE__)
-
-
# Default options for compilation
-
1
DEFAULTS = {
-
# rubocop:disable LineLength
-
:output => {
-
:ascii_only => true, # Escape non-ASCII characterss
-
:comments => :copyright, # Preserve comments (:all, :jsdoc, :copyright, :none)
-
:inline_script => false, # Escape occurrences of </script in strings
-
:quote_keys => false, # Quote keys in object literals
-
:max_line_len => 32 * 1024, # Maximum line length in minified code
-
:bracketize => false, # Bracketize if, for, do, while or with statements, even if their body is a single statement
-
:semicolons => true, # Separate statements with semicolons
-
:preserve_line => false, # Preserve line numbers in outputs
-
:beautify => false, # Beautify output
-
:indent_level => 4, # Indent level in spaces
-
:indent_start => 0, # Starting indent level
-
:space_colon => false, # Insert space before colons (only with beautifier)
-
:width => 80, # Specify line width when beautifier is used (only with beautifier)
-
:preamble => nil # Preamble for the generated JS file. Can be used to insert any code or comment.
-
},
-
:mangle => {
-
:eval => false, # Mangle names when eval of when is used in scope
-
:except => ["$super"], # Argument names to be excluded from mangling
-
:sort => false, # Assign shorter names to most frequently used variables. Often results in bigger output after gzip.
-
:toplevel => false # Mangle names declared in the toplevel scope
-
}, # Mangle variable and function names, set to false to skip mangling
-
:compress => {
-
:sequences => true, # Allow statements to be joined by commas
-
:properties => true, # Rewrite property access using the dot notation
-
:dead_code => true, # Remove unreachable code
-
:drop_debugger => true, # Remove debugger; statements
-
:unsafe => false, # Apply "unsafe" transformations
-
:conditionals => true, # Optimize for if-s and conditional expressions
-
:comparisons => true, # Apply binary node optimizations for comparisons
-
:evaluate => true, # Attempt to evaluate constant expressions
-
:booleans => true, # Various optimizations to boolean contexts
-
:loops => true, # Optimize loops when condition can be statically determined
-
:unused => true, # Drop unreferenced functions and variables
-
:hoist_funs => true, # Hoist function declarations
-
:hoist_vars => false, # Hoist var declarations
-
:if_return => true, # Optimizations for if/return and if/continue
-
:join_vars => true, # Join consecutive var statements
-
:cascade => true, # Cascade sequences
-
:negate_iife => true, # Negate immediately invoked function expressions to avoid extra parens
-
:pure_getters => false, # Assume that object property access does not have any side-effects
-
:pure_funcs => nil, # List of functions without side-effects. Can safely discard function calls when the result value is not used
-
:drop_console => false, # Drop calls to console.* functions
-
:angular => false, # Process @ngInject annotations
-
:keep_fargs => false # Preserve unused function arguments
-
}, # Apply transformations to code, set to false to skip
-
:define => {}, # Define values for symbol replacement
-
:enclose => false, # Enclose in output function wrapper, define replacements as key-value pairs
-
:source_filename => nil, # The filename of the input file
-
:source_root => nil, # The URL of the directory which contains :source_filename
-
:output_filename => nil, # The filename or URL where the minified output can be found
-
:input_source_map => nil, # The contents of the source map describing the input
-
:screw_ie8 => false # Don't bother to generate safe code for IE8
-
}
-
# rubocop:enable LineLength
-
-
# Minifies JavaScript code using implicit context.
-
#
-
# source should be a String or IO object containing valid JavaScript.
-
# options contain optional overrides to Uglifier::DEFAULTS
-
#
-
# Returns minified code as String
-
1
def self.compile(source, options = {})
-
new(options).compile(source)
-
end
-
-
# Minifies JavaScript code and generates a source map using implicit context.
-
#
-
# source should be a String or IO object containing valid JavaScript.
-
# options contain optional overrides to Uglifier::DEFAULTS
-
#
-
# Returns a pair of [minified code as String, source map as a String]
-
1
def self.compile_with_map(source, options = {})
-
new(options).compile_with_map(source)
-
end
-
-
# Initialize new context for Uglifier with given options
-
#
-
# options - Hash of options to override Uglifier::DEFAULTS
-
1
def initialize(options = {})
-
(options.keys - DEFAULTS.keys - [:comments, :squeeze, :copyright])[0..1].each do |missing|
-
raise ArgumentError, "Invalid option: #{missing}"
-
end
-
@options = options
-
@context = ExecJS.compile(File.open(ES5FallbackPath, "r:UTF-8").read +
-
File.open(SplitFallbackPath, "r:UTF-8").read +
-
File.open(SourcePath, "r:UTF-8").read)
-
end
-
-
# Minifies JavaScript code
-
#
-
# source should be a String or IO object containing valid JavaScript.
-
#
-
# Returns minified code as String
-
1
def compile(source)
-
run_uglifyjs(source, false)
-
end
-
1
alias_method :compress, :compile
-
-
# Minifies JavaScript code and generates a source map
-
#
-
# source should be a String or IO object containing valid JavaScript.
-
#
-
# Returns a pair of [minified code as String, source map as a String]
-
1
def compile_with_map(source)
-
run_uglifyjs(source, true)
-
end
-
-
1
private
-
-
# Run UglifyJS for given source code
-
1
def run_uglifyjs(source, generate_map)
-
@context.exec(Uglifier::JS % json_encode(
-
:source => read_source(source),
-
:output => output_options,
-
:compress => compressor_options,
-
:mangle => mangle_options,
-
:parse_options => parse_options,
-
:source_map_options => source_map_options,
-
:generate_map => generate_map,
-
:enclose => enclose_options
-
))
-
end
-
-
1
def read_source(source)
-
if source.respond_to?(:read)
-
source.read
-
else
-
source.to_s
-
end
-
end
-
-
1
def mangle_options
-
conditional_option(@options[:mangle], DEFAULTS[:mangle])
-
end
-
-
1
def compressor_options
-
defaults = conditional_option(
-
DEFAULTS[:compress],
-
:global_defs => @options[:define] || {},
-
:screw_ie8 => @options[:screw_ie8] || DEFAULTS[:screw_ie8]
-
)
-
conditional_option(@options[:compress] || @options[:squeeze], defaults)
-
end
-
-
1
def comment_options
-
case comment_setting
-
when :all, true
-
true
-
when :jsdoc
-
"jsdoc"
-
when :copyright
-
encode_regexp(/Copyright/i)
-
when Regexp
-
encode_regexp(comment_setting)
-
else
-
false
-
end
-
end
-
-
1
def comment_setting
-
if @options.has_key?(:output) && @options[:output].has_key?(:comments)
-
@options[:output][:comments]
-
elsif @options.has_key?(:comments)
-
@options[:comments]
-
elsif @options[:copyright] == false
-
:none
-
else
-
DEFAULTS[:output][:comments]
-
end
-
end
-
-
1
def output_options
-
DEFAULTS[:output].merge(@options[:output] || {}).merge(
-
:comments => comment_options,
-
:screw_ie8 => screw_ie8?
-
).reject { |key, _| key == :ie_proof }
-
end
-
-
1
def screw_ie8?
-
if (@options[:output] || {}).has_key?(:ie_proof)
-
false
-
else
-
@options[:screw_ie8] || DEFAULTS[:screw_ie8]
-
end
-
end
-
-
1
def source_map_options
-
{
-
:file => @options[:output_filename],
-
:root => @options[:source_root],
-
:orig => @options[:input_source_map]
-
}
-
end
-
-
1
def parse_options
-
{ :filename => @options[:source_filename] }
-
end
-
-
1
def enclose_options
-
if @options[:enclose]
-
@options[:enclose].map do |pair|
-
pair.first + ':' + pair.last
-
end
-
else
-
false
-
end
-
end
-
-
1
def json_encode(obj)
-
JSON.dump(obj)
-
end
-
-
1
def encode_regexp(regexp)
-
modifiers = if regexp.casefold?
-
"i"
-
else
-
""
-
end
-
-
[regexp.source, modifiers]
-
end
-
-
1
def conditional_option(value, defaults)
-
if value == true || value.nil?
-
defaults
-
elsif value
-
defaults.merge(value)
-
else
-
false
-
end
-
end
-
end
-
1
class Uglifier
-
1
VERSION = "2.5.3"
-
end
-
# encoding: utf-8
-
1
require 'forwardable'
-
-
1
require 'warden/mixins/common'
-
1
require 'warden/proxy'
-
1
require 'warden/manager'
-
1
require 'warden/errors'
-
1
require 'warden/session_serializer'
-
1
require 'warden/strategies'
-
1
require 'warden/strategies/base'
-
-
1
module Warden
-
1
class NotAuthenticated < StandardError; end
-
-
1
module Test
-
1
autoload :WardenHelpers, 'warden/test/warden_helpers'
-
1
autoload :Helpers, 'warden/test/helpers'
-
end
-
-
# Provides helper methods to warden for testing.
-
#
-
# To setup warden in test mode call the +test_mode!+ method on warden
-
#
-
# @example
-
# Warden.test_mode!
-
#
-
# This will provide a number of methods.
-
# Warden.on_next_request(&blk) - captures a block which is yielded the warden proxy on the next request
-
# Warden.test_reset! - removes any captured blocks that would have been executed on the next request
-
#
-
# Warden.test_reset! should be called in after blocks for rspec, or teardown methods for Test::Unit
-
1
def self.test_mode!
-
unless Warden::Test::WardenHelpers === Warden
-
Warden.extend Warden::Test::WardenHelpers
-
Warden::Manager.on_request do |proxy|
-
unless proxy.asset_request?
-
while blk = Warden._on_next_request.shift
-
blk.call(proxy)
-
end
-
end
-
end
-
end
-
true
-
end
-
end
-
# encoding: utf-8
-
-
1
module Warden
-
# This is a class which is yielded on use Warden::Manager. If you have a plugin
-
# and wants to add more configuration to warden, you just need to extend this
-
# class.
-
1
class Config < Hash
-
# Creates an accessor that simply sets and reads a key in the hash:
-
#
-
# class Config < Hash
-
# hash_accessor :failure_app
-
# end
-
#
-
# config = Config.new
-
# config.failure_app = Foo
-
# config[:failure_app] #=> Foo
-
#
-
# config[:failure_app] = Bar
-
# config.failure_app #=> Bar
-
#
-
1
def self.hash_accessor(*names) #:nodoc:
-
1
names.each do |name|
-
3
class_eval <<-METHOD, __FILE__, __LINE__ + 1
-
def #{name}
-
self[:#{name}]
-
end
-
-
def #{name}=(value)
-
self[:#{name}] = value
-
end
-
METHOD
-
end
-
end
-
-
1
hash_accessor :failure_app, :default_scope, :intercept_401
-
-
1
def initialize(other={})
-
1
merge!(other)
-
1
self[:default_scope] ||= :default
-
1
self[:scope_defaults] ||= {}
-
1
self[:default_strategies] ||= {}
-
1
self[:intercept_401] = true unless key?(:intercept_401)
-
end
-
-
1
def initialize_copy(other)
-
super
-
deep_dup(:scope_defaults, other)
-
deep_dup(:default_strategies, other)
-
end
-
-
# Do not raise an error if a missing strategy is given.
-
# :api: plugin
-
1
def silence_missing_strategies!
-
self[:silence_missing_strategies] = true
-
end
-
-
1
def silence_missing_strategies? #:nodoc:
-
!!self[:silence_missing_strategies]
-
end
-
-
# Set the default strategies to use.
-
# :api: public
-
1
def default_strategies(*strategies)
-
1
opts = Hash === strategies.last ? strategies.pop : {}
-
1
hash = self[:default_strategies]
-
1
scope = opts[:scope] || :_all
-
-
1
hash[scope] = strategies.flatten unless strategies.empty?
-
1
hash[scope] || hash[:_all] || []
-
end
-
-
# A short hand way to set up a particular scope
-
# :api: public
-
1
def scope_defaults(scope, opts = {})
-
1
if strategies = opts.delete(:strategies)
-
1
default_strategies(strategies, :scope => scope)
-
end
-
-
1
if opts.empty?
-
1
self[:scope_defaults][scope] || {}
-
else
-
self[:scope_defaults][scope] ||= {}
-
self[:scope_defaults][scope].merge!(opts)
-
end
-
end
-
-
# Quick accessor to strategies from manager
-
# :api: public
-
1
def strategies
-
Warden::Strategies
-
end
-
-
# Hook from configuration to serialize_into_session.
-
# :api: public
-
1
def serialize_into_session(*args, &block)
-
1
Warden::Manager.serialize_into_session(*args, &block)
-
end
-
-
# Hook from configuration to serialize_from_session.
-
# :api: public
-
1
def serialize_from_session(*args, &block)
-
1
Warden::Manager.serialize_from_session(*args, &block)
-
end
-
-
1
protected
-
-
1
def deep_dup(key, other)
-
self[key] = hash = other[key].dup
-
hash.each { |k, v| hash[k] = v.dup }
-
end
-
end
-
end
-
# encoding: utf-8
-
1
module Warden
-
1
class Proxy
-
# Lifted from DataMapper's dm-validations plugin :)
-
# @author Guy van den Berg
-
# @since DM 0.9
-
1
class Errors
-
-
1
include Enumerable
-
-
# Clear existing authentication errors.
-
1
def clear!
-
errors.clear
-
end
-
-
# Add a authentication error. Use the field_name :general if the errors does
-
# not apply to a specific field of the Resource.
-
#
-
# @param <Symbol> field_name the name of the field that caused the error
-
# @param <String> message the message to add
-
1
def add(field_name, message)
-
(errors[field_name] ||= []) << message
-
end
-
-
# Collect all errors into a single list.
-
1
def full_messages
-
errors.inject([]) do |list,pair|
-
list += pair.last
-
end
-
end
-
-
# Return authentication errors for a particular field_name.
-
#
-
# @param <Symbol> field_name the name of the field you want an error for
-
1
def on(field_name)
-
errors_for_field = errors[field_name]
-
blank?(errors_for_field) ? nil : errors_for_field
-
end
-
-
1
def each
-
errors.map.each do |k,v|
-
next if blank?(v)
-
yield(v)
-
end
-
end
-
-
1
def empty?
-
entries.empty?
-
end
-
-
1
def method_missing(meth, *args, &block)
-
errors.send(meth, *args, &block)
-
end
-
-
1
private
-
1
def errors
-
@errors ||= {}
-
end
-
-
1
def blank?(thing)
-
thing.nil? || thing == "" || (thing.respond_to?(:empty?) && thing.empty?)
-
end
-
-
end # class Errors
-
end # Proxy
-
end # Warden
-
# encoding: utf-8
-
1
module Warden
-
1
module Hooks
-
-
# Hook to _run_callbacks asserting for conditions.
-
1
def _run_callbacks(kind, *args) #:nodoc:
-
options = args.last # Last callback arg MUST be a Hash
-
-
send("_#{kind}").each do |callback, conditions|
-
invalid = conditions.find do |key, value|
-
value.is_a?(Array) ? !value.include?(options[key]) : (value != options[key])
-
end
-
-
callback.call(*args) unless invalid
-
end
-
end
-
-
# A callback hook set to run every time after a user is set.
-
# This callback is triggered the first time one of those three events happens
-
# during a request: :authentication, :fetch (from session) and :set_user (when manually set).
-
# You can supply as many hooks as you like, and they will be run in order of decleration.
-
#
-
# If you want to run the callbacks for a given scope and/or event, you can specify them as options.
-
# See parameters and example below.
-
#
-
# Parameters:
-
# <options> Some options which specify when the callback should be executed
-
# scope - Executes the callback only if it maches the scope(s) given
-
# only - Executes the callback only if it matches the event(s) given
-
# except - Executes the callback except if it matches the event(s) given
-
# <block> A block where you can set arbitrary logic to run every time a user is set
-
# Block Parameters: |user, auth, opts|
-
# user - The user object that is being set
-
# auth - The raw authentication proxy object.
-
# opts - any options passed into the set_user call includeing :scope
-
#
-
# Example:
-
# Warden::Manager.after_set_user do |user,auth,opts|
-
# scope = opts[:scope]
-
# if auth.session["#{scope}.last_access"].to_i > (Time.now - 5.minutes)
-
# auth.logout(scope)
-
# throw(:warden, :scope => scope, :reason => "Times Up")
-
# end
-
# auth.session["#{scope}.last_access"] = Time.now
-
# end
-
#
-
# Warden::Manager.after_set_user :except => :fetch do |user,auth,opts|
-
# user.login_count += 1
-
# end
-
#
-
# :api: public
-
1
def after_set_user(options = {}, method = :push, &block)
-
4
raise BlockNotGiven unless block_given?
-
-
4
if options.key?(:only)
-
options[:event] = options.delete(:only)
-
elsif options.key?(:except)
-
2
options[:event] = [:set_user, :authentication, :fetch] - Array(options.delete(:except))
-
end
-
-
4
_after_set_user.send(method, [block, options])
-
end
-
-
# Provides access to the array of after_set_user blocks to run
-
# :api: private
-
1
def _after_set_user # :nodoc:
-
4
@_after_set_user ||= []
-
end
-
-
# after_authentication is just a wrapper to after_set_user, which is only invoked
-
# when the user is set through the authentication path. The options and yielded arguments
-
# are the same as in after_set_user.
-
#
-
# :api: public
-
1
def after_authentication(options = {}, method = :push, &block)
-
1
after_set_user(options.merge(:event => :authentication), method, &block)
-
end
-
-
# after_fetch is just a wrapper to after_set_user, which is only invoked
-
# when the user is fetched from sesion. The options and yielded arguments
-
# are the same as in after_set_user.
-
#
-
# :api: public
-
1
def after_fetch(options = {}, method = :push, &block)
-
after_set_user(options.merge(:event => :fetch), method, &block)
-
end
-
-
# A callback that runs just prior to the failur application being called.
-
# This callback occurs after PATH_INFO has been modified for the failure (default /unauthenticated)
-
# In this callback you can mutate the environment as required by the failure application
-
# If a Rails controller were used for the failure_app for example, you would need to set request[:params][:action] = :unauthenticated
-
#
-
# Parameters:
-
# <options> Some options which specify when the callback should be executed
-
# scope - Executes the callback only if it maches the scope(s) given
-
# <block> A block to contain logic for the callback
-
# Block Parameters: |env, opts|
-
# env - The rack env hash
-
# opts - any options passed into the authenticate call includeing :scope
-
#
-
# Example:
-
# Warden::Manager.before_failure do |env, opts|
-
# params = Rack::Request.new(env).params
-
# params[:action] = :unauthenticated
-
# params[:warden_failure] = opts
-
# end
-
#
-
# :api: public
-
1
def before_failure(options = {}, method = :push, &block)
-
raise BlockNotGiven unless block_given?
-
_before_failure.send(method, [block, options])
-
end
-
-
# Provides access to the callback array for before_failure
-
# :api: private
-
1
def _before_failure
-
@_before_failure ||= []
-
end
-
-
# A callback that runs if no user could be fetched, meaning there is now no user logged in.
-
#
-
# Parameters:
-
# <options> Some options which specify when the callback should be executed
-
# scope - Executes the callback only if it maches the scope(s) given
-
# <block> A block to contain logic for the callback
-
# Block Parameters: |user, auth, scope|
-
# user - The authenticated user for the current scope
-
# auth - The warden proxy object
-
# opts - any options passed into the authenticate call including :scope
-
#
-
# Example:
-
# Warden::Manager.after_failed_fetch do |user, auth, opts|
-
# I18n.locale = :en
-
# end
-
#
-
# :api: public
-
1
def after_failed_fetch(options = {}, method = :push, &block)
-
raise BlockNotGiven unless block_given?
-
_after_failed_fetch.send(method, [block, options])
-
end
-
-
# Provides access to the callback array for after_failed_fetch
-
# :api: private
-
1
def _after_failed_fetch
-
@_after_failed_fetch ||= []
-
end
-
-
# A callback that runs just prior to the logout of each scope.
-
#
-
# Parameters:
-
# <options> Some options which specify when the callback should be executed
-
# scope - Executes the callback only if it maches the scope(s) given
-
# <block> A block to contain logic for the callback
-
# Block Parameters: |user, auth, scope|
-
# user - The authenticated user for the current scope
-
# auth - The warden proxy object
-
# opts - any options passed into the authenticate call including :scope
-
#
-
# Example:
-
# Warden::Manager.before_logout do |user, auth, opts|
-
# user.forget_me!
-
# end
-
#
-
# :api: public
-
1
def before_logout(options = {}, method = :push, &block)
-
1
raise BlockNotGiven unless block_given?
-
1
_before_logout.send(method, [block, options])
-
end
-
-
# Provides access to the callback array for before_logout
-
# :api: private
-
1
def _before_logout
-
1
@_before_logout ||= []
-
end
-
-
# A callback that runs on each request, just after the proxy is initialized
-
#
-
# Parameters:
-
# <block> A block to contain logic for the callback
-
# Block Parameters: |proxy|
-
# proxy - The warden proxy object for the request
-
#
-
# Example:
-
# user = "A User"
-
# Warden::Manager.on_request do |proxy|
-
# proxy.set_user = user
-
# end
-
#
-
# :api: public
-
1
def on_request(options = {}, method = :push, &block)
-
raise BlockNotGiven unless block_given?
-
_on_request.send(method, [block, options])
-
end
-
-
# Provides access to the callback array for before_logout
-
# :api: private
-
1
def _on_request
-
@_on_request ||= []
-
end
-
-
# Add prepend filters version
-
%w(after_set_user after_authentication after_fetch on_request
-
1
before_failure before_logout).each do |filter|
-
6
class_eval <<-METHOD, __FILE__, __LINE__ + 1
-
def prepend_#{filter}(options={}, &block)
-
#{filter}(options, :unshift, &block)
-
end
-
METHOD
-
end
-
end # Hooks
-
end # Warden
-
# encoding: utf-8
-
1
require 'warden/hooks'
-
1
require 'warden/config'
-
-
1
module Warden
-
# The middleware for Rack Authentication
-
# The middlware requires that there is a session upstream
-
# The middleware injects an authentication object into
-
# the rack environment hash
-
1
class Manager
-
1
extend Warden::Hooks
-
-
1
attr_accessor :config
-
-
# Initialize the middleware. If a block is given, a Warden::Config is yielded so you can properly
-
# configure the Warden::Manager.
-
# :api: public
-
1
def initialize(app, options={})
-
1
default_strategies = options.delete(:default_strategies)
-
-
1
@app, @config = app, Warden::Config.new(options)
-
1
@config.default_strategies *default_strategies if default_strategies
-
1
yield @config if block_given?
-
1
self
-
end
-
-
# Invoke the application guarding for throw :warden.
-
# If this is downstream from another warden instance, don't do anything.
-
# :api: private
-
1
def call(env) # :nodoc:
-
return @app.call(env) if env['warden'] && env['warden'].manager != self
-
-
env['warden'] = Proxy.new(env, self)
-
result = catch(:warden) do
-
@app.call(env)
-
end
-
-
result ||= {}
-
case result
-
when Array
-
if result.first == 401 && intercept_401?(env)
-
process_unauthenticated(env)
-
else
-
result
-
end
-
when Hash
-
process_unauthenticated(env, result)
-
end
-
end
-
-
# :api: private
-
1
def _run_callbacks(*args) #:nodoc:
-
self.class._run_callbacks(*args)
-
end
-
-
1
class << self
-
# Prepares the user to serialize into the session.
-
# Any object that can be serialized into the session in some way can be used as a "user" object
-
# Generally however complex object should not be stored in the session.
-
# If possible store only a "key" of the user object that will allow you to reconstitute it.
-
#
-
# You can supply different methods of serialization for different scopes by passing a scope symbol
-
#
-
# Example:
-
# Warden::Manager.serialize_into_session{ |user| user.id }
-
# # With Scope:
-
# Warden::Manager.serialize_into_session(:admin) { |user| user.id }
-
#
-
# :api: public
-
1
def serialize_into_session(scope = nil, &block)
-
1
method_name = scope.nil? ? :serialize : "#{scope}_serialize"
-
1
Warden::SessionSerializer.send :define_method, method_name, &block
-
end
-
-
# Reconstitues the user from the session.
-
# Use the results of user_session_key to reconstitue the user from the session on requests after the initial login
-
# You can supply different methods of de-serialization for different scopes by passing a scope symbol
-
#
-
# Example:
-
# Warden::Manager.serialize_from_session{ |id| User.get(id) }
-
# # With Scope:
-
# Warden::Manager.serialize_from_session(:admin) { |id| AdminUser.get(id) }
-
#
-
# :api: public
-
1
def serialize_from_session(scope = nil, &block)
-
1
method_name = scope.nil? ? :deserialize : "#{scope}_deserialize"
-
1
Warden::SessionSerializer.send :define_method, method_name, &block
-
end
-
end
-
-
1
private
-
-
1
def intercept_401?(env)
-
config[:intercept_401] && !env['warden'].custom_failure?
-
end
-
-
# When a request is unauthenticated, here's where the processing occurs.
-
# It looks at the result of the proxy to see if it's been executed and what action to take.
-
# :api: private
-
1
def process_unauthenticated(env, options={})
-
options[:action] ||= begin
-
opts = config[:scope_defaults][config.default_scope] || {}
-
opts[:action] || 'unauthenticated'
-
end
-
-
proxy = env['warden']
-
result = options[:result] || proxy.result
-
-
case result
-
when :redirect
-
body = proxy.message || "You are being redirected to #{proxy.headers['Location']}"
-
[proxy.status, proxy.headers, [body]]
-
when :custom
-
proxy.custom_response
-
else
-
call_failure_app(env, options)
-
end
-
end
-
-
# Calls the failure app.
-
# The before_failure hooks are run on each failure
-
# :api: private
-
1
def call_failure_app(env, options = {})
-
if config.failure_app
-
options.merge!(:attempted_path => ::Rack::Request.new(env).fullpath)
-
env["PATH_INFO"] = "/#{options[:action]}"
-
env["warden.options"] = options
-
-
_run_callbacks(:before_failure, env, options)
-
config.failure_app.call(env).to_a
-
else
-
raise "No Failure App provided"
-
end
-
end # call_failure_app
-
end
-
end # Warden
-
# encoding: utf-8
-
1
module Warden
-
1
module Mixins
-
1
module Common
-
-
# Convinience method to access the session
-
# :api: public
-
1
def session
-
env['rack.session']
-
end # session
-
-
# Alias :session to :raw_session since the former will be user API for storing scoped data.
-
1
alias :raw_session :session
-
-
# Convenience method to access the rack request.
-
# :api: public
-
1
def request
-
@request ||= Rack::Request.new(@env)
-
end # request
-
-
# Provides a warden repository for cookies. Those are sent to the client
-
# when the response is streamed back from the app.
-
# :api: public
-
1
def warden_cookies
-
warn "warden_cookies was never functional and is going to be removed in next versions"
-
env['warden.cookies'] ||= {}
-
end # warden_cookies
-
-
# Convenience method to access the rack request params
-
# :api: public
-
1
def params
-
request.params
-
end # params
-
-
# Resets the session. By using this non-hash like sessions can
-
# be cleared by overwriting this method in a plugin
-
# @api overwritable
-
1
def reset_session!
-
raw_session.clear
-
end # reset_session!
-
-
end # Common
-
end # Mixins
-
end # Warden
-
# encoding: utf-8
-
-
1
module Warden
-
1
class UserNotSet < RuntimeError; end
-
-
1
class Proxy
-
# An accessor to the winning strategy
-
# :api: private
-
1
attr_accessor :winning_strategy
-
-
# An accessor to the rack env hash, the proxy owner and its config
-
# :api: public
-
1
attr_reader :env, :manager, :config, :winning_strategies
-
-
1
extend ::Forwardable
-
1
include ::Warden::Mixins::Common
-
-
1
ENV_WARDEN_ERRORS = 'warden.errors'.freeze
-
1
ENV_SESSION_OPTIONS = 'rack.session.options'.freeze
-
-
# :api: private
-
1
def_delegators :winning_strategy, :headers, :status, :custom_response
-
-
# :api: public
-
1
def_delegators :config, :default_strategies
-
-
1
def initialize(env, manager) #:nodoc:
-
@env, @users, @winning_strategies, @locked = env, {}, {}, false
-
@manager, @config = manager, manager.config.dup
-
@strategies = Hash.new { |h,k| h[k] = {} }
-
manager._run_callbacks(:on_request, self)
-
end
-
-
# Lazily initiate errors object in session.
-
# :api: public
-
1
def errors
-
@env[ENV_WARDEN_ERRORS] ||= Errors.new
-
end
-
-
# Points to a SessionSerializer instance responsible for handling
-
# everything related with storing, fetching and removing the user
-
# session.
-
# :api: public
-
1
def session_serializer
-
@session_serializer ||= Warden::SessionSerializer.new(@env)
-
end
-
-
# Clear the cache of performed strategies so far. Warden runs each
-
# strategy just once during the request lifecycle. You can clear the
-
# strategies cache if you want to allow a strategy to be run more than
-
# once.
-
#
-
# This method has the same API as authenticate, allowing you to clear
-
# specific strategies for given scope:
-
#
-
# Parameters:
-
# args - a list of symbols (labels) that name the strategies to attempt
-
# opts - an options hash that contains the :scope of the user to check
-
#
-
# Example:
-
# # Clear all strategies for the configured default_scope
-
# env['warden'].clear_strategies_cache!
-
#
-
# # Clear all strategies for the :admin scope
-
# env['warden'].clear_strategies_cache!(:scope => :admin)
-
#
-
# # Clear password strategy for the :admin scope
-
# env['warden'].clear_strategies_cache!(:password, :scope => :admin)
-
#
-
# :api: public
-
1
def clear_strategies_cache!(*args)
-
scope, opts = _retrieve_scope_and_opts(args)
-
-
@winning_strategies.delete(scope)
-
@strategies[scope].each do |k, v|
-
v.clear! if args.empty? || args.include?(k)
-
end
-
end
-
-
# Locks the proxy so new users cannot authenticate during the
-
# request lifecycle. This is useful when the request cannot
-
# be verified (for example, using a CSRF verification token).
-
# Notice that already authenticated users are kept as so.
-
#
-
# :api: public
-
1
def lock!
-
@locked = true
-
end
-
-
# Run the authentiation strategies for the given strategies.
-
# If there is already a user logged in for a given scope, the strategies are not run
-
# This does not halt the flow of control and is a passive attempt to authenticate only
-
# When scope is not specified, the default_scope is assumed.
-
#
-
# Parameters:
-
# args - a list of symbols (labels) that name the strategies to attempt
-
# opts - an options hash that contains the :scope of the user to check
-
#
-
# Example:
-
# env['warden'].authenticate(:password, :basic, :scope => :sudo)
-
#
-
# :api: public
-
1
def authenticate(*args)
-
user, opts = _perform_authentication(*args)
-
user
-
end
-
-
# Same API as authenticated, but returns a boolean instead of a user.
-
# The difference between this method (authenticate?) and authenticated?
-
# is that the former will run strategies if the user has not yet been
-
# authenticated, and the second relies on already performed ones.
-
# :api: public
-
1
def authenticate?(*args)
-
result = !!authenticate(*args)
-
yield if result && block_given?
-
result
-
end
-
-
# The same as +authenticate+ except on failure it will throw an :warden symbol causing the request to be halted
-
# and rendered through the +failure_app+
-
#
-
# Example
-
# env['warden'].authenticate!(:password, :scope => :publisher) # throws if it cannot authenticate
-
#
-
# :api: public
-
1
def authenticate!(*args)
-
user, opts = _perform_authentication(*args)
-
throw(:warden, opts) unless user
-
user
-
end
-
-
# Check to see if there is an authenticated user for the given scope.
-
# This brings the user from the session, but does not run strategies before doing so.
-
# If you want strategies to be run, please check authenticate?.
-
#
-
# Parameters:
-
# scope - the scope to check for authentication. Defaults to default_scope
-
#
-
# Example:
-
# env['warden'].authenticated?(:admin)
-
#
-
# :api: public
-
1
def authenticated?(scope = @config.default_scope)
-
result = !!user(scope)
-
yield if block_given? && result
-
result
-
end
-
-
# Same API as authenticated?, but returns false when authenticated.
-
# :api: public
-
1
def unauthenticated?(scope = @config.default_scope)
-
result = !authenticated?(scope)
-
yield if block_given? && result
-
result
-
end
-
-
# Manually set the user into the session and auth proxy
-
#
-
# Parameters:
-
# user - An object that has been setup to serialize into and out of the session.
-
# opts - An options hash. Use the :scope option to set the scope of the user, set the :store option to false to skip serializing into the session, set the :run_callbacks to false to skip running the callbacks (the default is true).
-
#
-
# :api: public
-
1
def set_user(user, opts = {})
-
scope = (opts[:scope] ||= @config.default_scope)
-
-
# Get the default options from the master configuration for the given scope
-
opts = (@config[:scope_defaults][scope] || {}).merge(opts)
-
opts[:event] ||= :set_user
-
@users[scope] = user
-
-
if opts[:store] != false && opts[:event] != :fetch
-
options = env[ENV_SESSION_OPTIONS]
-
options[:renew] = true if options
-
session_serializer.store(user, scope)
-
end
-
-
run_callbacks = opts.fetch(:run_callbacks, true)
-
manager._run_callbacks(:after_set_user, user, self, opts) if run_callbacks
-
-
@users[scope]
-
end
-
-
# Provides acccess to the user object in a given scope for a request.
-
# Will be nil if not logged in. Please notice that this method does not
-
# perform strategies.
-
#
-
# Example:
-
# # without scope (default user)
-
# env['warden'].user
-
#
-
# # with scope
-
# env['warden'].user(:admin)
-
#
-
# # as a Hash
-
# env['warden'].user(:scope => :admin)
-
#
-
# # with default scope and run_callbacks option
-
# env['warden'].user(:run_callbacks => false)
-
#
-
# # with a scope and run_callbacks option
-
# env['warden'].user(:scope => :admin, :run_callbacks => true)
-
#
-
# :api: public
-
1
def user(argument = {})
-
opts = argument.is_a?(Hash) ? argument : { :scope => argument }
-
scope = (opts[:scope] ||= @config.default_scope)
-
-
if @users.has_key?(scope)
-
@users[scope]
-
else
-
unless user = session_serializer.fetch(scope)
-
run_callbacks = opts.fetch(:run_callbacks, true)
-
manager._run_callbacks(:after_failed_fetch, user, self, :scope => scope) if run_callbacks
-
end
-
-
@users[scope] = user ? set_user(user, opts.merge(:event => :fetch)) : nil
-
end
-
end
-
-
# Provides a scoped session data for authenticated users.
-
# Warden manages clearing out this data when a user logs out
-
#
-
# Example
-
# # default scope
-
# env['warden'].session[:foo] = "bar"
-
#
-
# # :sudo scope
-
# env['warden'].session(:sudo)[:foo] = "bar"
-
#
-
# :api: public
-
1
def session(scope = @config.default_scope)
-
raise NotAuthenticated, "#{scope.inspect} user is not logged in" unless authenticated?(scope)
-
raw_session["warden.user.#{scope}.session"] ||= {}
-
end
-
-
# Provides logout functionality.
-
# The logout also manages any authenticated data storage and clears it when a user logs out.
-
#
-
# Parameters:
-
# scopes - a list of scopes to logout
-
#
-
# Example:
-
# # Logout everyone and clear the session
-
# env['warden'].logout
-
#
-
# # Logout the default user but leave the rest of the session alone
-
# env['warden'].logout(:default)
-
#
-
# # Logout the :publisher and :admin user
-
# env['warden'].logout(:publisher, :admin)
-
#
-
# :api: public
-
1
def logout(*scopes)
-
if scopes.empty?
-
scopes = @users.keys
-
reset_session = true
-
end
-
-
scopes.each do |scope|
-
user = @users.delete(scope)
-
manager._run_callbacks(:before_logout, user, self, :scope => scope)
-
-
raw_session.delete("warden.user.#{scope}.session") unless raw_session.nil?
-
session_serializer.delete(scope, user)
-
end
-
-
reset_session! if reset_session
-
end
-
-
# proxy methods through to the winning strategy
-
# :api: private
-
1
def result # :nodoc:
-
winning_strategy && winning_strategy.result
-
end
-
-
# Proxy through to the authentication strategy to find out the message that was generated.
-
# :api: public
-
1
def message
-
winning_strategy && winning_strategy.message
-
end
-
-
# Provides a way to return a 401 without warden defering to the failure app
-
# The result is a direct passthrough of your own response
-
# :api: public
-
1
def custom_failure!
-
@custom_failure = true
-
end
-
-
# Check to see if the custom failure flag has been set
-
# :api: public
-
1
def custom_failure?
-
!!@custom_failure
-
end
-
-
# Check to see if this is an asset request
-
# :api: public
-
1
def asset_request?
-
::Warden::asset_paths.any? { |r| env['PATH_INFO'].to_s.match(r) }
-
end
-
-
1
def inspect(*args)
-
"Warden::Proxy:#{object_id} @config=#{@config.inspect}"
-
end
-
-
1
def to_s(*args)
-
inspect(*args)
-
end
-
-
1
private
-
-
1
def _perform_authentication(*args)
-
scope, opts = _retrieve_scope_and_opts(args)
-
user = nil
-
-
# Look for an existing user in the session for this scope.
-
# If there was no user in the session. See if we can get one from the request.
-
return user, opts if user = user(opts.merge(:scope => scope))
-
_run_strategies_for(scope, args)
-
-
if winning_strategy && winning_strategy.user
-
opts[:store] = opts.fetch(:store, winning_strategy.store?)
-
set_user(winning_strategy.user, opts.merge!(:event => :authentication))
-
end
-
-
[@users[scope], opts]
-
end
-
-
1
def _retrieve_scope_and_opts(args) #:nodoc:
-
opts = args.last.is_a?(Hash) ? args.pop : {}
-
scope = opts[:scope] || @config.default_scope
-
opts = (@config[:scope_defaults][scope] || {}).merge(opts)
-
[scope, opts]
-
end
-
-
# Run the strategies for a given scope
-
1
def _run_strategies_for(scope, args) #:nodoc:
-
self.winning_strategy = @winning_strategies[scope]
-
return if winning_strategy && winning_strategy.halted?
-
-
# Do not run any strategy if locked
-
return if @locked
-
-
if args.empty?
-
defaults = @config[:default_strategies]
-
strategies = defaults[scope] || defaults[:_all]
-
end
-
-
(strategies || args).each do |name|
-
strategy = _fetch_strategy(name, scope)
-
next unless strategy && !strategy.performed? && strategy.valid?
-
-
self.winning_strategy = @winning_strategies[scope] = strategy
-
strategy._run!
-
break if strategy.halted?
-
end
-
end
-
-
# Fetchs strategies and keep them in a hash cache.
-
1
def _fetch_strategy(name, scope)
-
@strategies[scope][name] ||= if klass = Warden::Strategies[name]
-
klass.new(@env, scope)
-
elsif @config.silence_missing_strategies?
-
nil
-
else
-
raise "Invalid strategy #{name}"
-
end
-
end
-
end # Proxy
-
-
end # Warden
-
# encoding: utf-8
-
1
module Warden
-
1
class SessionSerializer
-
1
attr_reader :env
-
-
1
def initialize(env)
-
@env = env
-
end
-
-
1
def key_for(scope)
-
"warden.user.#{scope}.key"
-
end
-
-
1
def serialize(user)
-
user
-
end
-
-
1
def deserialize(key)
-
key
-
end
-
-
1
def store(user, scope)
-
return unless user
-
method_name = "#{scope}_serialize"
-
specialized = respond_to?(method_name)
-
session[key_for(scope)] = specialized ? send(method_name, user) : serialize(user)
-
end
-
-
1
def fetch(scope)
-
key = session[key_for(scope)]
-
return nil unless key
-
-
method_name = "#{scope}_deserialize"
-
user = respond_to?(method_name) ? send(method_name, key) : deserialize(key)
-
delete(scope) unless user
-
user
-
end
-
-
1
def stored?(scope)
-
!!session[key_for(scope)]
-
end
-
-
1
def delete(scope, user=nil)
-
session.delete(key_for(scope))
-
end
-
-
# We can't cache this result because the session can be lazy loaded
-
1
def session
-
env["rack.session"] || {}
-
end
-
end # SessionSerializer
-
end # Warden
-
# encoding: utf-8
-
1
module Warden
-
1
module Strategies
-
1
class << self
-
# Add a strategy and store it in a hash.
-
1
def add(label, strategy = nil, &block)
-
2
strategy ||= Class.new(Warden::Strategies::Base)
-
2
strategy.class_eval(&block) if block_given?
-
-
2
unless strategy.method_defined?(:authenticate!)
-
raise NoMethodError, "authenticate! is not declared in the #{label.inspect} strategy"
-
end
-
-
2
base = Warden::Strategies::Base
-
2
unless strategy.ancestors.include?(base)
-
raise "#{label.inspect} is not a #{base}"
-
end
-
-
2
_strategies[label] = strategy
-
end
-
-
# Update a previously given strategy.
-
1
def update(label, &block)
-
strategy = _strategies[label]
-
raise "Unknown strategy #{label.inspect}" unless strategy
-
add(label, strategy, &block)
-
end
-
-
# Provides access to strategies by label
-
# :api: public
-
1
def [](label)
-
_strategies[label]
-
end
-
-
# Clears all declared.
-
# :api: public
-
1
def clear!
-
_strategies.clear
-
end
-
-
# :api: private
-
1
def _strategies
-
2
@strategies ||= {}
-
end
-
end # << self
-
end # Strategies
-
end # Warden
-
# encoding: utf-8
-
1
module Warden
-
1
module Strategies
-
# A strategy is a place where you can put logic related to authentication. Any strategy inherits
-
# from Warden::Strategies::Base.
-
#
-
# The Warden::Strategies.add method is a simple way to provide custom strategies.
-
# You _must_ declare an @authenticate!@ method.
-
# You _may_ provide a @valid?@ method.
-
# The valid method should return true or false depending on if the strategy is a valid one for the request.
-
#
-
# The parameters for Warden::Strategies.add method is:
-
# <label: Symbol> The label is the name given to a strategy. Use the label to refer to the strategy when authenticating
-
# <strategy: Class|nil> The optional stragtegy argument if set _must_ be a class that inherits from Warden::Strategies::Base and _must_
-
# implement an @authenticate!@ method
-
# <block> The block acts as a convinient way to declare your strategy. Inside is the class definition of a strategy.
-
#
-
# Examples:
-
#
-
# Block Declared Strategy:
-
# Warden::Strategies.add(:foo) do
-
# def authenticate!
-
# # authentication logic
-
# end
-
# end
-
#
-
# Class Declared Strategy:
-
# Warden::Strategies.add(:foo, MyStrategy)
-
#
-
1
class Base
-
# :api: public
-
1
attr_accessor :user, :message
-
-
# :api: private
-
1
attr_accessor :result, :custom_response
-
-
# :api: public
-
1
attr_reader :env, :scope, :status
-
-
1
include ::Warden::Mixins::Common
-
-
# :api: private
-
1
def initialize(env, scope=nil) # :nodoc:
-
@env, @scope = env, scope
-
@status, @headers = nil, {}
-
@halted, @performed = false, false
-
end
-
-
# The method that is called from above. This method calls the underlying authenticate! method
-
# :api: private
-
1
def _run! # :nodoc:
-
@performed = true
-
authenticate!
-
self
-
end
-
-
# Returns if this strategy was already performed.
-
# :api: private
-
1
def performed? #:nodoc:
-
@performed
-
end
-
-
# Marks this strategy as not performed.
-
# :api: private
-
1
def clear!
-
@performed = false
-
end
-
-
# Acts as a guarding method for the strategy.
-
# If #valid? responds false, the strategy will not be executed
-
# Overwrite with your own logic
-
# :api: overwritable
-
1
def valid?; true; end
-
-
# Provides access to the headers hash for setting custom headers
-
# :api: public
-
1
def headers(header = {})
-
@headers ||= {}
-
@headers.merge! header
-
@headers
-
end
-
-
# Access to the errors object.
-
# :api: public
-
1
def errors
-
@env['warden'].errors
-
end
-
-
# Cause the processing of the strategies to stop and cascade no further
-
# :api: public
-
1
def halt!
-
@halted = true
-
end
-
-
# Checks to see if a strategy was halted
-
# :api: public
-
1
def halted?
-
!!@halted
-
end
-
-
# Checks to see if a strategy should result in a permanent login
-
# :api: public
-
1
def store?
-
true
-
end
-
-
# A simple method to return from authenticate! if you want to ignore this strategy
-
# :api: public
-
1
def pass; end
-
-
# Whenever you want to provide a user object as "authenticated" use the +success!+ method.
-
# This will halt the strategy, and set the user in the approprieate scope.
-
# It is the "login" method
-
#
-
# Parameters:
-
# user - The user object to login. This object can be anything you have setup to serialize in and out of the session
-
#
-
# :api: public
-
1
def success!(user, message = nil)
-
halt!
-
@user = user
-
@message = message
-
@result = :success
-
end
-
-
# This causes the strategy to fail. It does not throw an :warden symbol to drop the request out to the failure application
-
# You must throw an :warden symbol somewhere in the application to enforce this
-
# Halts the strategies so that this is the last strategy checked
-
# :api: public
-
1
def fail!(message = "Failed to Login")
-
halt!
-
@message = message
-
@result = :failure
-
end
-
-
# Casuses the strategy to fail, but not halt. The strategies will cascade after this failure and warden will check the next strategy. The last strategy to fail will have it's message displayed.
-
# :api: public
-
1
def fail(message = "Failed to Login")
-
@message = message
-
@result = :failure
-
end
-
-
# Causes the authentication to redirect. An :warden symbol must be thrown to actually execute this redirect
-
#
-
# Parameters:
-
# url <String> - The string representing the URL to be redirected to
-
# pararms <Hash> - Any parameters to encode into the URL
-
# opts <Hash> - Any options to recirect with.
-
# available options: permanent => (true || false)
-
#
-
# :api: public
-
1
def redirect!(url, params = {}, opts = {})
-
halt!
-
@status = opts[:permanent] ? 301 : 302
-
headers["Location"] = url
-
headers["Location"] << "?" << Rack::Utils.build_query(params) unless params.empty?
-
headers["Content-Type"] = opts[:content_type] || 'text/plain'
-
-
@message = opts[:message] || "You are being redirected to #{headers["Location"]}"
-
@result = :redirect
-
-
headers["Location"]
-
end
-
-
# Return a custom rack array. You must throw an :warden symbol to activate this
-
# :api: public
-
1
def custom!(response)
-
halt!
-
@custom_response = response
-
@result = :custom
-
end
-
-
end # Base
-
end # Strategies
-
end # Warden